├── .gitignore
├── .settings
└── org.eclipse.core.resources.prefs
├── .travis.yml
├── AUTHORS.rst
├── CONTRIBUTING.rst
├── HISTORY.rst
├── LICENSE
├── MANIFEST.in
├── Makefile
├── README.rst
├── Tests
├── .gitignore
├── __init__.py
├── test_ChainContext.py
├── test_CosmoHammerSampler.py
├── test_InMemoryStorageUtil.py
├── test_LikelihoodComputationChain.py
├── test_MpiUtil.py
├── test_Params.py
├── test_ParticleSwarmOptimizer.py
├── test_PositionGenerators.py
└── test_SampleFileUtil.py
├── cosmoHammer
├── ChainContext.py
├── ConcurrentMpiCosmoHammerSampler.py
├── Constants.py
├── CosmoHammerSampler.py
├── LikelihoodComputationChain.py
├── MpiCosmoHammerSampler.py
├── __init__.py
├── exceptions.py
├── modules
│ ├── MultivarianteGaussianModule.py
│ ├── PseudoCmbModule.py
│ ├── RosenbrockModule.py
│ └── __init__.py
├── pso
│ ├── BestFitPositionGenerator.py
│ ├── CurvatureFitter.py
│ ├── MpiParticleSwarmOptimizer.py
│ ├── ParticleSwarmOptimizer.py
│ └── __init__.py
└── util
│ ├── FlatPositionGenerator.py
│ ├── IPythonUtil.py
│ ├── InMemoryStorageUtil.py
│ ├── IterationStopCriteriaStrategy.py
│ ├── MpiUtil.py
│ ├── Params.py
│ ├── SampleBallPositionGenerator.py
│ ├── SampleFileUtil.py
│ └── __init__.py
├── doc
├── .gitignore
├── Makefile
├── check_sphinx.py
└── source
│ ├── api.rst
│ ├── authors.rst
│ ├── conf.py
│ ├── contributing.rst
│ ├── history.rst
│ ├── index.rst
│ └── user
│ ├── HowToCosmoHammer.rst
│ ├── benchmark.png
│ ├── benchmark.rst
│ ├── chscheme.jpg
│ ├── install.rst
│ ├── parallelisation.jpg
│ ├── parallelization.rst
│ ├── pso.gif
│ ├── pso.rst
│ └── usage.rst
├── examples
├── .gitignore
├── DerivedParamterFileUtil.py
├── DummyCoreModule.py
├── DummyLikelihoodModule.py
├── README.rst
├── __init__.py
├── pseudo_cmb.png
├── runCosmoHammer.py
├── runCosmoHammerGaussian.py
├── runCosmoHammerPseudoCmb.py
├── runCosmoHammerRosenbrock.py
└── wmap_tester.py
├── requirements.txt
├── setup.py
└── tox.ini
/.gitignore:
--------------------------------------------------------------------------------
1 | *.py[cod]
2 |
3 | # C extensions
4 | *.so
5 |
6 | # Packages
7 | *.egg
8 | *.egg-info
9 | dist
10 | build
11 | eggs
12 | parts
13 | bin
14 | var
15 | sdist
16 | develop-eggs
17 | .installed.cfg
18 | lib
19 | lib64
20 | .DS_Store
21 | *.log
22 |
23 | # Installer logs
24 | pip-log.txt
25 |
26 | # Unit test / coverage reports
27 | .coverage
28 | .tox
29 | nosetests.xml
30 | *junit-*
31 | htmlcov
32 | coverage.xml
33 |
34 | # Translations
35 | *.mo
36 |
37 | # Mr Developer
38 | .mr.developer.cfg
39 | .project
40 | .pydevproject
41 |
42 | # Complexity
43 | output/*.html
44 | output/*/index.html
45 |
46 | # Sphinx
47 | doc/build
48 |
--------------------------------------------------------------------------------
/.settings/org.eclipse.core.resources.prefs:
--------------------------------------------------------------------------------
1 | eclipse.preferences.version=1
2 | encoding//doc/source/conf.py=utf-8
3 | encoding/setup.py=utf-8
4 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: python
2 | python:
3 | - "2.7"
4 | - "3.6"
5 |
6 | before_install:
7 | - sudo apt-get update
8 | - sudo add-apt-repository -y ppa:ubuntu-toolchain-r/test
9 | - sudo apt-get -qq update
10 | - sudo apt-get -qq install g++-4.8 gcc-4.8
11 | - sudo ln -sf /usr/bin/gcc-4.8 /usr/bin/gcc
12 | - sudo ln -sf /usr/bin/g++-4.8 /usr/bin/g++
13 | # We do this conditionally because it saves us some downloading if the
14 | # version is the same.
15 | - if [[ "$TRAVIS_PYTHON_VERSION" == "2.7" ]]; then
16 | wget https://repo.continuum.io/miniconda/Miniconda-latest-Linux-x86_64.sh -O miniconda.sh;
17 | else
18 | wget https://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh -O miniconda.sh;
19 | fi
20 | - bash miniconda.sh -b -p $HOME/miniconda
21 | - export PATH="$HOME/miniconda/bin:$PATH"
22 | - conda update --yes conda
23 | - travis_retry conda install --yes python=$TRAVIS_PYTHON_VERSION pip numpy scipy
24 |
25 | install:
26 | - travis_retry pip install coveralls
27 | - travis_retry pip install -r requirements.txt
28 |
29 | # command to run tests, e.g. python setup.py test
30 | script: coverage run --source cosmoHammer setup.py test
31 | after_success:
32 | coveralls
33 |
--------------------------------------------------------------------------------
/AUTHORS.rst:
--------------------------------------------------------------------------------
1 | =======
2 | Credits
3 | =======
4 |
5 | Development Lead
6 | ----------------
7 |
8 | - Joel Akeret (ETHZ)
9 | - Sebastian Seehars (ETHZ)
10 |
11 | Contributors
12 | ------------
13 |
14 | - sibirrer (Simon Birrer)
15 |
16 | Citations
17 | ---------
18 |
19 | As you use **CosmoHammer** for your exciting discoveries, please cite the paper that describes the package:
20 |
21 | Akeret, J., Seehars, S., Amara, A, Refregier, A., and Csillaghy, A., Astronomy and Computing (2013)
22 |
--------------------------------------------------------------------------------
/CONTRIBUTING.rst:
--------------------------------------------------------------------------------
1 | ============
2 | Contributing
3 | ============
4 |
5 | Contributions are welcome, and they are greatly appreciated! Every
6 | little bit helps, and credit will always be given.
7 |
8 | You can contribute in many ways:
9 |
10 | Types of Contributions
11 | ----------------------
12 |
13 | Report Bugs
14 | ~~~~~~~~~~~
15 |
16 | If you are reporting a bug, please include:
17 |
18 | * Your operating system name and version.
19 | * Any details about your local setup that might be helpful in troubleshooting.
20 | * Detailed steps to reproduce the bug.
21 |
22 | Fix Bugs
23 | ~~~~~~~~
24 |
25 | Implement Features
26 | ~~~~~~~~~~~~~~~~~~
27 |
28 | Write Documentation
29 | ~~~~~~~~~~~~~~~~~~~
30 |
31 | CosmoHammer could always use more documentation, whether as part of the
32 | official CosmoHammer docs, in docstrings, or even on the web in blog posts,
33 | articles, and such.
34 |
35 | Submit Feedback
36 | ~~~~~~~~~~~~~~~
37 |
38 | If you are proposing a feature:
39 |
40 | * Explain in detail how it would work.
41 | * Keep the scope as narrow as possible, to make it easier to implement.
42 | * Remember that this is a volunteer-driven project, and that contributions
43 | are welcome :)
44 |
45 | Pull Request Guidelines
46 | -----------------------
47 |
48 | Before you submit a pull request, check that it meets these guidelines:
49 |
50 | 1. The pull request should include tests.
51 | 2. If the pull request adds functionality, the docs should be updated. Put
52 | your new functionality into a function with a docstring, and add the
53 | feature to the list in README.rst.
54 | 3. The pull request should work for Python 2.6, 2.7, and 3.3, and for PyPy.
55 | make sure that the tests pass for all supported Python versions.
56 |
57 |
58 | Tips
59 | ----
60 |
61 | To run a subset of tests::
62 |
63 | $ py.test test/test_CosmoHammerSampler.py
--------------------------------------------------------------------------------
/HISTORY.rst:
--------------------------------------------------------------------------------
1 | .. :changelog:
2 |
3 | History
4 | -------
5 |
6 | 0.6.1 (2018-03-05)
7 | ++++++++++++++++++
8 | - Fixed numpy compatibility issue
9 |
10 | 0.6.0 (2016-08-15)
11 | ++++++++++++++++++
12 | - Order preserving parameter objects
13 | - Fixing logging issue
14 | - Prettified examples
15 |
16 | 0.5.0 (2015-05-12)
17 | ++++++++++++++++++
18 | - Flat package structure
19 | - Separation of sampling and modules
20 | - improved documentation
21 |
22 | 0.4.0 (2015-03-16)
23 | ++++++++++++++++++
24 | - Support for Python 3
25 | - Change in package structure
26 | - Fixed bug in mpi pso
27 |
28 | 0.3.0 (2014-03-22)
29 | ++++++++++++++++++
30 | - Better exception handling
31 | - Particle swarm optimization module
32 | - Higher test coverage
33 | - Some bug fixes
34 | - Extended documentation
35 | - Support for PyCamb
36 |
37 | 0.2.1 (2013-09-05)
38 | ++++++++++++++++++
39 | - Some bug fixes
40 |
41 | 0.2.0 (2013-08-28)
42 | ++++++++++++++++++
43 | - Revised version - not backwards compatible!
44 | - Bug fixes and major code refactoring
45 | - New documentation
46 |
47 | 0.1.0 (2013-01-03)
48 | ++++++++++++++++++
49 | - First release
50 |
51 | 0.0.3 (2012-11-23)
52 | ++++++++++++++++++
53 | - First release candidate
54 |
55 | 0.0.1 (2012-05-09)
56 | ++++++++++++++++++
57 | - Initial creation
58 |
59 |
60 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/MANIFEST.in:
--------------------------------------------------------------------------------
1 | include AUTHORS.rst
2 | include HISTORY.rst
3 | include README.rst
4 | include LICENSE
5 | include doc/*
6 | include doc/source/*
7 | include doc/source/user/*
8 | include Tests/*
9 | include examples/*.py
10 | include Makefile
11 |
12 | exclude .settings/*
13 | exclude .pydevproject
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | .PHONY: help clean clean-pyc clean-build list test test-all coverage docs release sdist
2 |
3 | help:
4 | @echo "clean-build - remove build artifacts"
5 | @echo "clean-pyc - remove Python file artifacts"
6 | @echo "lint - check style with flake8"
7 | @echo "test - run tests quickly with the default Python"
8 | @echo "test-all - run tests on every Python version with tox"
9 | @echo "coverage - check code coverage quickly with the default Python"
10 | @echo "docs - generate Sphinx HTML documentation, including API docs"
11 | @echo "sdist - package"
12 |
13 | clean: clean-build clean-pyc
14 |
15 | clean-build:
16 | rm -fr build/
17 | rm -fr dist/
18 | rm -fr *.egg-info
19 |
20 | clean-pyc:
21 | find . -name '*.pyc' -exec rm -f {} +
22 | find . -name '*.pyo' -exec rm -f {} +
23 | find . -name '*~' -exec rm -f {} +
24 |
25 | lint:
26 | flake8 cosmoHammer test
27 |
28 | test:
29 | python setup.py test
30 |
31 | test-all:
32 | tox
33 |
34 | coverage:
35 | coverage run --source cosmoHammer setup.py test
36 | coverage report -m
37 | coverage html
38 | open htmlcov/index.html
39 |
40 | docs:
41 | rm -f docs/cosmoHammer.rst
42 | rm -f docs/modules.rst
43 | sphinx-apidoc -o doc/api/ cosmoHammer
44 | $(MAKE) -C doc clean
45 | $(MAKE) -C doc html
46 | open doc/build/html/index.html
47 |
48 | sdist: clean
49 | # pip freeze > requirements.txt
50 | python setup.py sdist
51 | ls -l dist
52 |
--------------------------------------------------------------------------------
/README.rst:
--------------------------------------------------------------------------------
1 | =======================================================
2 | Cosmological parameter estimation with the MCMC Hammer
3 | =======================================================
4 |
5 | .. image:: https://badge.fury.io/py/cosmoHammer.png
6 | :target: http://badge.fury.io/py/cosmoHammer
7 |
8 | .. image:: https://travis-ci.org/cosmo-ethz/CosmoHammer.png?branch=master
9 | :target: https://travis-ci.org/cosmo-ethz/CosmoHammer
10 |
11 | .. image:: https://coveralls.io/repos/cosmo-ethz/CosmoHammer/badge.svg
12 | :target: https://coveralls.io/r/cosmo-ethz/CosmoHammer
13 |
14 | .. image:: https://readthedocs.org/projects/cosmohammer/badge/?version=latest
15 | :target: http://cosmohammer.readthedocs.io/en/latest/?badge=latest
16 | :alt: Documentation Status
17 |
18 | .. image:: http://img.shields.io/badge/arXiv-1212.1721-orange.svg?style=flat
19 | :target: http://arxiv.org/abs/1212.1721
20 |
21 |
22 |
23 | CosmoHammer is a framework which embeds `emcee `_ , an implementation by Foreman-Mackey et al. (2012) of the `Affine Invariant Markov chain Monte Carlo (MCMC) Ensemble sampler `_ by Goodman and Weare (2010).
24 |
25 | It gives the user the possibility to plug in modules for the computation of any desired likelihood. The major goal of the software is to reduce the complexity when one wants to extend or replace the existing computation by modules which fit the user's needs as well as to provide the possibility to easily use large scale computing environments.
26 |
27 | We published a `paper `_ in the `Astronomy and Computing Journal `_ which discusses the advantages and performance of our framework.
28 |
29 | This project has been realized in collaboration with the `Institute of 4D Technologies `_ of the `University of Applied Sciences and Arts Northwest Switzerland `_ (Fachhochschule Nordwestschweiz - FHNW).
30 |
31 | The development is coordinated on `GitHub `_ and contributions are welcome. The documentation of **CosmoHammer** is available at `readthedocs.org `_ and the package is distributed over `PyPI `_.
32 |
33 | For all public modules such as PyCamb, WMAP, Planck and more, see the cosmoHammerPlugins project at http://github.com/cosmo-ethz/CosmoHammerPlugins.
34 |
35 |
--------------------------------------------------------------------------------
/Tests/.gitignore:
--------------------------------------------------------------------------------
1 | /__pycache__
2 |
--------------------------------------------------------------------------------
/Tests/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cosmo-ethz/CosmoHammer/b6c65ccff7c3f83623264b7d57e05310755f761b/Tests/__init__.py
--------------------------------------------------------------------------------
/Tests/test_ChainContext.py:
--------------------------------------------------------------------------------
1 | """
2 | Test the CosmoHammerSampler module.
3 |
4 | Execute with py.test -v
5 |
6 | """
7 | from __future__ import print_function, division, absolute_import, unicode_literals
8 |
9 | from cosmoHammer.ChainContext import ChainContext
10 |
11 | import numpy as np
12 |
13 | class TestCosmoHammerSampler(object):
14 | ctx = None
15 | params = np.array([[1,2,3],[4,5,6]])
16 |
17 | def setup(self):
18 | self.ctx=ChainContext(self, self.params)
19 |
20 | def test_no_data(self):
21 | assert self.ctx.getParent() == self
22 | assert self.ctx.getParams() is self.params
23 | assert self.ctx.contains("key") == False
24 | assert self.ctx.getData() is not None
25 | assert len(list(self.ctx.getData().items())) == 0
26 |
27 | def test_add_data(self):
28 | assert self.ctx.contains("key") == False
29 | assert self.ctx.getData() is not None
30 |
31 | self.ctx.add("key", "value")
32 |
33 | assert self.ctx.contains("key") == True
34 | assert self.ctx.getData() is not None
35 |
36 | assert self.ctx.get("key") == "value"
37 |
38 | def test_remove_data(self):
39 | assert self.ctx.contains("key2") == False
40 | assert self.ctx.getData() is not None
41 |
42 | self.ctx.add("key2", "value")
43 |
44 | assert self.ctx.contains("key2") == True
45 | assert self.ctx.getData() is not None
46 |
47 | assert self.ctx.get("key2") == "value"
48 |
49 | self.ctx.remove("key2")
50 | assert self.ctx.contains("key2") == False
51 |
52 | def test_get_default(self):
53 | assert self.ctx.contains("aaa") == False
54 | assert self.ctx.get("aaa", "default") == "default"
55 |
56 |
57 | def test_additional_data(self):
58 | assert self.ctx.getData() is not None
59 | assert len(list(self.ctx.getData().items())) == 0
60 |
61 | self.ctx.getData()["moreData"] = "data"
62 | assert len(list(self.ctx.getData().items())) == 1
--------------------------------------------------------------------------------
/Tests/test_CosmoHammerSampler.py:
--------------------------------------------------------------------------------
1 | ##!/usr/bin/env python
2 | """
3 | Test the CosmoHammerSampler module.
4 |
5 | Execute with py.test -v
6 |
7 | """
8 | import numpy as np
9 | import os
10 | import tempfile
11 |
12 | from cosmoHammer import LikelihoodComputationChain
13 | from cosmoHammer.modules.PseudoCmbModule import PseudoCmbModule
14 |
15 | from cosmoHammer.util.IterationStopCriteriaStrategy import IterationStopCriteriaStrategy
16 |
17 | from cosmoHammer.CosmoHammerSampler import CosmoHammerSampler
18 |
19 | from cosmoHammer.util import SampleBallPositionGenerator
20 | from cosmoHammer.util import FlatPositionGenerator
21 | from cosmoHammer.util import InMemoryStorageUtil
22 | from cosmoHammer.util import SampleFileUtil
23 |
24 | class TestCosmoHammerSampler(object):
25 | params = None
26 | sampler = None
27 |
28 | def setup(self):
29 | """
30 | Initialise some data vectors used for the comparisons by the other functions.
31 | """
32 | self.params = np.array([[70, 40, 100, 3],
33 | [0.0226, 0.005, 0.1, 0.001],
34 | [0.122, 0.01, 0.99, 0.01],
35 | [2.1e-9, 1.48e-9, 5.45e-9, 1e-10],
36 | [0.96, 0.5, 1.5, 0.02],
37 | [0.09, 0.01, 0.8, 0.03],
38 | [1,0,2,0.4] ])
39 |
40 |
41 | #the real means..
42 | means = [70.704, 0.02256, 0.1115, 2.18474E-09, 0.9688, 0.08920]
43 |
44 | # ...and non-trivial covariance matrix.
45 | cov = np.array([[6.11E+00, 0, 0, 0, 0, 0],
46 | [7.19E-04, 3.26E-07, 0, 0, 0, 0],
47 | [-1.19E-02, -3.37E-07, 3.14E-05, 0, 0, 0],
48 | [-3.56E-11, 1.43E-14, 1.76E-13, 5.96E-21, 0, 0],
49 | [2.01E-02, 6.37E-06, -2.13E-05, 3.66E-13, 1.90E-04, 0],
50 | [1.10E-02, 2.36E-06, -1.92E-05, 8.70E-13, 7.32E-05, 2.23E-04]])
51 | cov += cov.T - np.diag(cov.diagonal())
52 |
53 | # Invert the covariance matrix
54 | icov = np.linalg.inv(cov)
55 |
56 | chain = LikelihoodComputationChain()
57 | pseudoLikelihood = PseudoCmbModule(icov, means)
58 |
59 | chain.addLikelihoodModule(pseudoLikelihood)
60 | chain.setup()
61 |
62 | posGen = FlatPositionGenerator()
63 |
64 | self.sampler = CosmoHammerSampler(
65 | params= self.params,
66 | likelihoodComputationChain=chain,
67 | filePrefix=self._getTempFilePrefix(),
68 | walkersRatio=10,
69 | burninIterations=1,
70 | sampleIterations=11,
71 | initPositionGenerator=posGen,
72 | storageUtil=InMemoryStorageUtil())
73 |
74 | def test_init(self):
75 | self.sampler = CosmoHammerSampler(
76 | params= self.params,
77 | likelihoodComputationChain=LikelihoodComputationChain(),
78 | filePrefix=self._getTempFilePrefix(),
79 | walkersRatio=10,
80 | burninIterations=1,
81 | sampleIterations=1)
82 |
83 | assert isinstance(self.sampler.storageUtil, SampleFileUtil)
84 | assert isinstance(self.sampler.stopCriteriaStrategy, IterationStopCriteriaStrategy)
85 | assert isinstance(self.sampler.initPositionGenerator, SampleBallPositionGenerator)
86 | assert self.sampler.likelihoodComputationChain.params is not None
87 |
88 |
89 | def test_no_burn_in(self):
90 | self.sampler.resetSampler()
91 | self.sampler.burninIterations = 0;
92 | self.sampler.startSampling()
93 |
94 | assert self.sampler.storageUtil.samplesBurnin == None
95 | assert self.sampler.storageUtil.probBurnin == None
96 |
97 | def test_one_iter_burn_in(self):
98 | self.sampler.resetSampler()
99 | self.sampler.burninIterations = 1;
100 | self.sampler.walkersRatio = 10;
101 | self.sampler.startSampling()
102 |
103 | assert self.sampler.storageUtil.samplesBurnin is not None
104 | assert self.sampler.storageUtil.probBurnin is not None
105 |
106 | params = 7
107 | samples = params * self.sampler.burninIterations * self.sampler.walkersRatio
108 | assert self.sampler.storageUtil.samplesBurnin.shape == (samples, params)
109 | assert self.sampler.storageUtil.probBurnin.shape == (samples, )
110 |
111 | def test_one_iter_sampling(self):
112 | self.sampler.resetSampler()
113 | self.sampler.burninIterations = 0;
114 | self.sampler.sampleIterations = 1;
115 | self.sampler.walkersRatio = 10;
116 | self.sampler.startSampling()
117 |
118 | params = 7
119 | samples = params * self.sampler.sampleIterations * self.sampler.walkersRatio
120 |
121 | assert self.sampler.storageUtil.samplesBurnin is None
122 | assert self.sampler.storageUtil.probBurnin is None
123 | assert self.sampler.storageUtil.samples.shape == (samples, params)
124 | assert self.sampler.storageUtil.prob.shape == (samples, )
125 |
126 | def _getTempFilePrefix(self):
127 | return os.path.join(tempfile.mkdtemp(), "pseudoCmb")
--------------------------------------------------------------------------------
/Tests/test_InMemoryStorageUtil.py:
--------------------------------------------------------------------------------
1 | ##!/usr/bin/env python
2 | """
3 | Test the CosmoHammerSampler module.
4 |
5 | Execute with py.test -v
6 |
7 | """
8 | from cosmoHammer.util.InMemoryStorageUtil import InMemoryStorageUtil
9 |
10 | import numpy as np
11 |
12 | class TestCosmoHammerSampler(object):
13 | storageUtil = None
14 | samples = np.array([[1,2,3],[4,5,6]])
15 | prob = np.array([1,1])
16 |
17 | def setup(self):
18 | self.storageUtil=InMemoryStorageUtil()
19 |
20 | def test_no_data(self):
21 |
22 | assert self.storageUtil.samplesBurnin == None
23 | assert self.storageUtil.probBurnin == None
24 |
25 | def test_persistBurninValues(self):
26 | self.storageUtil.persistBurninValues(self.samples, self.prob, [])
27 |
28 | assert self.storageUtil.samplesBurnin is not None
29 | assert self.storageUtil.probBurnin is not None
30 | assert self.storageUtil.samplesBurnin.shape == (2, 3)
31 | assert self.storageUtil.probBurnin.shape == (2, )
32 |
33 | self.storageUtil.persistBurninValues(self.samples, self.prob, [])
34 |
35 | assert self.storageUtil.samplesBurnin is not None
36 | assert self.storageUtil.probBurnin is not None
37 | assert self.storageUtil.samplesBurnin.shape == (4, 3)
38 | assert self.storageUtil.probBurnin.shape == (4, )
39 |
40 | def test_persistSamplingValues(self):
41 | self.storageUtil.persistSamplingValues(self.samples, self.prob, [])
42 |
43 | assert self.storageUtil.samples is not None
44 | assert self.storageUtil.prob is not None
45 | assert self.storageUtil.samples.shape == (2, 3)
46 | assert self.storageUtil.prob.shape == (2, )
47 |
48 | self.storageUtil.persistSamplingValues(self.samples, self.prob, [])
49 |
50 | assert self.storageUtil.samples is not None
51 | assert self.storageUtil.prob is not None
52 | assert self.storageUtil.samples.shape == (4, 3)
53 | assert self.storageUtil.prob.shape == (4, )
54 |
55 |
--------------------------------------------------------------------------------
/Tests/test_LikelihoodComputationChain.py:
--------------------------------------------------------------------------------
1 | ##!/usr/bin/env python
2 | """
3 | Test the LikelihoodComputationChain module.
4 |
5 | Execute with py.test -v
6 |
7 | """
8 |
9 | import numpy as np
10 | from cosmoHammer import LikelihoodComputationChain
11 | from cosmoHammer.util import Params
12 |
13 | class TestLikelihoodComputationChain(object):
14 |
15 | def test_modules(self):
16 | chain = LikelihoodComputationChain()
17 |
18 | assert len(chain.getCoreModules())==0
19 | assert len(chain.getLikelihoodModules())==0
20 |
21 | coreModule = DummyModule()
22 | likeModule = DummyModule()
23 | chain.addCoreModule(coreModule)
24 | chain.addLikelihoodModule(likeModule)
25 | assert len(chain.getCoreModules())==1
26 | assert len(chain.getLikelihoodModules())==1
27 |
28 | chain.setup()
29 | assert coreModule.init
30 | assert likeModule.init
31 |
32 | like, data = chain([0])
33 |
34 | assert coreModule.called
35 | assert likeModule.compLike
36 |
37 | assert like == DummyModule.like
38 | assert len(data) == 1
39 | assert data["data"] == DummyModule.data
40 |
41 | def test_isValid(self):
42 | chain = LikelihoodComputationChain()
43 | assert chain.isValid([0])
44 |
45 | chain = LikelihoodComputationChain(min=[0])
46 | assert chain.isValid([1])
47 | assert chain.isValid([0])
48 | assert not chain.isValid([-1])
49 |
50 | chain = LikelihoodComputationChain(min=[0, 1])
51 | assert chain.isValid([1, 2])
52 | assert chain.isValid([0, 1])
53 | assert not chain.isValid([-1, 1])
54 | assert not chain.isValid([0, 0])
55 | assert not chain.isValid([-1, 0])
56 |
57 | chain = LikelihoodComputationChain(max=[1])
58 | assert chain.isValid([1])
59 | assert chain.isValid([0])
60 | assert not chain.isValid([2])
61 |
62 | chain = LikelihoodComputationChain(max=[1, 2])
63 | assert chain.isValid([0, 1])
64 | assert chain.isValid([1, 2])
65 | assert not chain.isValid([2, 2])
66 | assert not chain.isValid([1, 3])
67 | assert not chain.isValid([2, 3])
68 |
69 | chain = LikelihoodComputationChain(min=[0, 1], max=[1, 2])
70 | assert chain.isValid([1, 2])
71 | assert chain.isValid([0, 1])
72 | assert chain.isValid([0, 1])
73 | assert chain.isValid([1, 2])
74 | assert not chain.isValid([-1, 1])
75 | assert not chain.isValid([0, 0])
76 | assert not chain.isValid([-1, 0])
77 | assert not chain.isValid([2, 2])
78 | assert not chain.isValid([1, 3])
79 | assert not chain.isValid([2, 3])
80 |
81 | like, data = chain([-1, 0])
82 | assert like == -np.inf
83 | assert len(data) == 0
84 |
85 | like, data = chain([2, 3])
86 | assert like == -np.inf
87 | assert len(data) == 0
88 |
89 | def test_createChainContext(self):
90 | chain = LikelihoodComputationChain()
91 |
92 | p = np.array([1,2])
93 | ctx = chain.createChainContext(p)
94 | assert ctx is not None
95 | assert np.all(ctx.getParams() == p)
96 |
97 | def test_createChainContext_params_invalid(self):
98 | chain = LikelihoodComputationChain()
99 | chain.values = []
100 |
101 | p = np.array([1,2])
102 | ctx = chain.createChainContext(p)
103 |
104 | assert ctx is not None
105 | assert np.all(ctx.getParams() == p)
106 |
107 | def test_createChainContext_params(self):
108 | keys = ["a", "b"]
109 | params = Params((keys[0], 0),
110 | (keys[1], 1))
111 | chain = LikelihoodComputationChain()
112 | chain.params = params
113 |
114 | p = np.array([1,2])
115 | ctx = chain.createChainContext(p)
116 |
117 | assert ctx is not None
118 | assert np.all(ctx.getParams().keys == keys)
119 | assert np.all(ctx.getParams()[0] == p[0])
120 | assert np.all(ctx.getParams()[1] == p[1])
121 |
122 |
123 |
124 | class DummyModule(object):
125 |
126 | like = 0
127 | data = 1
128 |
129 | def __init__(self):
130 | self.init = False
131 | self.called = False
132 | self.compLike = False
133 |
134 | def setup(self):
135 | self.init = True
136 |
137 | def __call__(self, ctx):
138 | self.called = True
139 | ctx.getData()["data"] = self.data
140 |
141 | def computeLikelihood(self, ctx):
142 | self.compLike = True
143 | return self.like
--------------------------------------------------------------------------------
/Tests/test_MpiUtil.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2014 ETH Zurich, Institute for Astronomy
2 |
3 | '''
4 | Created on Jul 29, 2014
5 |
6 | author: jakeret
7 | '''
8 | from __future__ import print_function, division, absolute_import, unicode_literals
9 |
10 | import numpy as np
11 | from mock import patch
12 |
13 | from cosmoHammer.util import MpiUtil
14 |
15 | class TestMpiUtil(object):
16 |
17 | @patch("cosmoHammer.util.MpiUtil.MPI")
18 | def test_splitlist_1(self, mpi_mock):
19 | sequence = self._get_sequence(7)
20 | n = 1
21 | sList = MpiUtil.splitList(sequence, n)
22 | assert len(sList) == n
23 | for i in range(len(sequence)):
24 | assert np.all(sList[0][i] == sequence[i])
25 |
26 | @patch("cosmoHammer.util.MpiUtil.MPI")
27 | def test_splitlist_2(self, mpi_mock):
28 | sequence = self._get_sequence(7)
29 | n = 2
30 | sList = MpiUtil.splitList(sequence, n)
31 | assert len(sList) == n
32 |
33 | assert len(sList[0]) == 4
34 | for i in range(4):
35 | assert np.all(sList[0][i] == sequence[0+i])
36 |
37 | assert len(sList[1]) == 3
38 | for i in range(3):
39 | assert np.all(sList[1][i] == sequence[4+i])
40 |
41 | @patch("cosmoHammer.util.MpiUtil.MPI")
42 | def test_splitlist_3(self, mpi_mock):
43 | sequence = self._get_sequence(7)
44 | n = 3
45 | sList = MpiUtil.splitList(sequence, n)
46 | assert len(sList) == n
47 |
48 | l0 = 2
49 | assert len(sList[0]) == l0
50 | for i in range(l0):
51 | assert np.all(sList[0][i] == sequence[0+i])
52 |
53 | l1 = 3
54 | assert len(sList[1]) == l1
55 | for i in range(l1):
56 | assert np.all(sList[1][i] == sequence[2+i])
57 |
58 | l2 = 2
59 | assert len(sList[2]) == l2
60 | for i in range(l2):
61 | assert np.all(sList[2][i] == sequence[5+i])
62 |
63 | @patch("cosmoHammer.util.MpiUtil.MPI")
64 | def test_splitlist_equal(self, mpi_mock):
65 | sequence = self._get_sequence(10)
66 |
67 | n = 10
68 | sList = MpiUtil.splitList(sequence, n)
69 | assert len(sList) == n
70 |
71 | l0 = 1
72 | for k in range(n):
73 | assert len(sList[k]) == l0
74 | for i in range(l0):
75 | assert np.all(sList[k][i] == sequence[(k*l0)+i])
76 |
77 | @patch("cosmoHammer.util.MpiUtil.MPI")
78 | def test_splitlist_80(self, mpi_mock):
79 | sequence = self._get_sequence(160)
80 |
81 | n = 80
82 | sList = MpiUtil.splitList(sequence, n)
83 | assert len(sList) == n
84 |
85 | l0 = 2
86 | for k in range(n):
87 | assert len(sList[k]) == l0
88 | for i in range(l0):
89 | assert np.all(sList[k][i] == sequence[(k*l0)+i])
90 |
91 |
92 | def _get_sequence(self, lenght):
93 | sequence = (np.ones((lenght,4)).T * np.arange(lenght)).T
94 | sequence = [sequence[i] for i in range(len(sequence))]
95 | return sequence
--------------------------------------------------------------------------------
/Tests/test_Params.py:
--------------------------------------------------------------------------------
1 | # Copyright (C) 2015 ETH Zurich, Institute for Astronomy
2 |
3 | '''
4 | Created on Aug 5, 2015
5 |
6 | author: jakeret
7 | '''
8 | from __future__ import print_function, division, absolute_import, unicode_literals
9 | from cosmoHammer.util import Params
10 | import pytest
11 | import numpy as np
12 | class TestParams(object):
13 |
14 | def test_attr_looup(self):
15 | params = Params(("attr1", 1),
16 | ("attr2", 2))
17 |
18 | assert params.attr1 == 1
19 | assert params.attr2 == 2
20 |
21 | with pytest.raises(AttributeError):
22 | params.inexistent
23 |
24 | def test_get(self):
25 | params = Params(("attr1", 1),
26 | ("attr2", 2))
27 |
28 | assert params.get("attr1") == 1
29 | assert params.get("attr2") == 2
30 |
31 | with pytest.raises(KeyError):
32 | params.get("inexistent")
33 |
34 | def test_params_access_1d(self):
35 | values = [1,2]
36 | params = Params(("attr1", values[0]),
37 | ("attr2", values[1]))
38 |
39 | assert np.all(params.values == values)
40 |
41 | def test_params_access_2d(self):
42 | values = np.array([[1,2,3,4],
43 | [5,6,7,8]])
44 | params = Params(("attr1", values[0]),
45 | ("attr2", values[1]))
46 |
47 | assert np.all(params.values == values)
48 |
49 |
50 | def test_slicing(self):
51 | values = np.array([[1,2,3,4],
52 | [5,6,7,8]])
53 | params = Params(("attr1", values[0]),
54 | ("attr2", values[1]))
55 |
56 | assert np.all(values[0] == values[0])
57 | assert np.all(values[:, 1] == values[:, 1])
58 |
59 | def test_names_access(self):
60 | keys = ["attr1","attr2"]
61 | params = Params((keys[0], 1),
62 | (keys[1], 2))
63 |
64 | assert np.all(params.keys == keys)
65 |
66 | def test_names_immutability(self):
67 | keys = ["attr1","attr2"]
68 | params = Params((keys[0], 1),
69 | (keys[1], 2))
70 |
71 | params.keys.append("irrelevant")
72 |
73 | assert np.all(params.keys == keys)
74 |
75 |
76 | def test_copy(self):
77 | params = Params(("attr1", 1),
78 | ("attr2", 2))
79 |
80 | params2 = params.copy()
81 |
82 | assert np.all(params.keys == params2.keys)
83 | assert np.all(params.values == params2.values)
84 |
85 | def test_str(self):
86 | params = Params(("attr1", 1))
87 | s = str(params)
88 | assert "=" in s
89 |
90 | def test_value_assignment(self):
91 | values = np.array([[1,2,3,4],
92 | [5,6,7,8]])
93 | params = Params(("attr1", values[0]),
94 | ("attr2", values[1]))
95 |
96 | params[:,0] = 0
97 | assert np.all(params[:,0] == 0)
98 |
99 | def test_duplicated_key(self):
100 | with pytest.raises(KeyError):
101 | _ = Params(("attr1", 1),
102 | ("attr1", 2))
103 |
104 |
--------------------------------------------------------------------------------
/Tests/test_ParticleSwarmOptimizer.py:
--------------------------------------------------------------------------------
1 | """
2 | Test the CosmoHammerSampler module.
3 |
4 | Execute with py.test -v
5 |
6 | """
7 | import numpy as np
8 |
9 | from cosmoHammer.ChainContext import ChainContext
10 | from cosmoHammer.pso.ParticleSwarmOptimizer import ParticleSwarmOptimizer
11 | from cosmoHammer.pso.ParticleSwarmOptimizer import Particle
12 |
13 | class TestCosmoHammerSampler(object):
14 | ctx = None
15 | params = np.array([[1,2,3],[4,5,6]])
16 |
17 | def setup(self):
18 | self.ctx=ChainContext(self, self.params)
19 |
20 | def test_Particle(self):
21 | particle = Particle.create(2)
22 | assert particle.fitness == -np.inf
23 |
24 | assert particle == particle.pbest
25 |
26 | particle2 = particle.copy()
27 | assert particle.fitness == particle2.fitness
28 | assert particle.paramCount == particle2.paramCount
29 | assert (particle.position == particle2.position).all()
30 | assert (particle.velocity == particle2.velocity).all()
31 |
32 |
33 | particle.fitness = 1
34 | particle.updatePBest()
35 |
36 | assert particle.pbest.fitness == 1
37 |
38 |
39 | def test_setup(self):
40 | low = np.zeros(2)
41 | high = np.ones(2)
42 | pso = ParticleSwarmOptimizer(None, low, high, 10)
43 |
44 | assert pso.swarm is not None
45 | assert len(pso.swarm) == 10
46 |
47 | position = [part.position for part in pso.swarm]
48 |
49 | assert (position>=low).all()
50 | assert (position<=high).all()
51 |
52 | velocity = [part.velocity for part in pso.swarm]
53 | assert (velocity == np.zeros(2)).all()
54 |
55 | fitness = [part.fitness == 0 for part in pso.swarm]
56 | assert all(fitness)
57 |
58 | assert pso.gbest.fitness == -np.inf
59 |
60 |
61 | def test_optimize(self):
62 | low = np.zeros(2)
63 | high = np.ones(2)
64 | func = lambda p: (-np.random.rand(), None)
65 | pso = ParticleSwarmOptimizer(func, low, high, 10)
66 |
67 | maxIter=10
68 | swarms, gbests = pso.optimize(maxIter)
69 | assert swarms is not None
70 | assert gbests is not None
71 | assert len(swarms) == maxIter
72 | assert len(gbests) == maxIter
73 |
74 | fitness = [part.fitness != 0 for part in pso.swarm]
75 | assert all(fitness)
76 |
77 | assert pso.gbest.fitness != -np.inf
78 |
79 |
--------------------------------------------------------------------------------
/Tests/test_PositionGenerators.py:
--------------------------------------------------------------------------------
1 | ##!/usr/bin/env python
2 | """
3 | Test the TestSampleFileUtil module.
4 |
5 | Execute with py.test -v
6 |
7 | """
8 |
9 | from cosmoHammer.util import SampleBallPositionGenerator
10 | from cosmoHammer.util import FlatPositionGenerator
11 |
12 | class TestPositionGenerators(object):
13 |
14 | nwalkers = 10
15 |
16 | def setup(self):
17 | self.sampler = DummySampler([1,2], 2, [1,1], self.nwalkers)
18 |
19 | def test_SampleBallPositionGenerator(self):
20 | gen = SampleBallPositionGenerator()
21 | gen.setup(self.sampler)
22 |
23 | pos = gen.generate()
24 | assert pos is not None
25 | assert len(pos) == self.nwalkers
26 |
27 | def test_FlatPositionGenerator(self):
28 | gen = FlatPositionGenerator()
29 | gen.setup(self.sampler)
30 |
31 | pos = gen.generate()
32 | assert pos is not None
33 | assert len(pos) == self.nwalkers
34 |
35 | class DummySampler(object):
36 |
37 | def __init__(self, paramValues, paramCount, paramWidths, nwalkers):
38 | self.paramValues = paramValues
39 | self.paramCount = paramCount
40 | self.paramWidths = paramWidths
41 | self.nwalkers = nwalkers
--------------------------------------------------------------------------------
/Tests/test_SampleFileUtil.py:
--------------------------------------------------------------------------------
1 | """
2 | Test the TestSampleFileUtil module.
3 |
4 | Execute with py.test -v
5 |
6 | """
7 | from __future__ import print_function, division, absolute_import, unicode_literals
8 |
9 | import tempfile
10 | import os
11 | import numpy
12 |
13 | import cosmoHammer.Constants as c
14 | from cosmoHammer.util.SampleFileUtil import SampleFileUtil
15 |
16 | class TestSampleFileUtil(object):
17 |
18 | prefix = "test"
19 |
20 | def createFileUtil(self):
21 | tempPath = tempfile.mkdtemp()
22 | tempPath = os.path.join(tempPath, self.prefix)
23 | fileUtil = SampleFileUtil(tempPath, True)
24 | return fileUtil, tempPath
25 |
26 | def test_not_master(self):
27 | tempPath = tempfile.mkdtemp()
28 | SampleFileUtil(tempPath, False)
29 | fileList = os.listdir(tempPath)
30 | assert len(fileList) == 0
31 |
32 |
33 | def test_persistBurninValues(self):
34 | fileUtil, tempPath = self.createFileUtil()
35 |
36 | pos = numpy.ones((10,5))
37 | prob = numpy.zeros(10)
38 |
39 | fileUtil.persistBurninValues(pos, prob, None)
40 |
41 | cPos = numpy.loadtxt(tempPath + c.BURNIN_SUFFIX)
42 | cProb = numpy.loadtxt(tempPath + c.BURNIN_PROB_SUFFIX)
43 |
44 | assert (pos == cPos).all()
45 | assert (prob == cProb).all()
46 |
47 |
48 | def test_persistSamplingValues(self):
49 | fileUtil, tempPath = self.createFileUtil()
50 |
51 | pos = numpy.ones((10,5))
52 | prob = numpy.zeros(10)
53 |
54 | fileUtil.persistSamplingValues(pos, prob, None)
55 |
56 | cPos = numpy.loadtxt(tempPath + c.FILE_SUFFIX)
57 | cProb = numpy.loadtxt(tempPath + c.PROB_SUFFIX)
58 |
59 | assert (pos == cPos).all()
60 | assert (prob == cProb).all()
61 |
62 | def test_importFromFile(self):
63 | fileUtil, tempPath = self.createFileUtil()
64 |
65 | pos = numpy.ones((10,5))
66 | prob = numpy.zeros(10)
67 |
68 | fileUtil.persistSamplingValues(pos, prob, None)
69 |
70 | cPos = fileUtil.importFromFile(tempPath + c.FILE_SUFFIX)
71 | cProb = fileUtil.importFromFile(tempPath + c.PROB_SUFFIX)
72 |
73 | assert (pos == cPos).all()
74 | assert (prob == cProb).all()
75 |
76 | def test_storeRandomState(self):
77 | fileUtil, tempPath = self.createFileUtil()
78 |
79 | rstate = numpy.random.mtrand.RandomState()
80 | fileUtil.storeRandomState(tempPath+c.BURNIN_STATE_SUFFIX, rstate)
81 |
82 | cRstate = fileUtil.importRandomState(tempPath+c.BURNIN_STATE_SUFFIX)
83 |
84 | print(rstate.get_state())
85 | oState = rstate.get_state()
86 | nState = cRstate.get_state()
87 |
88 | assert oState[0] == nState[0]
89 | assert all(oState[1] == nState[1])
90 | assert oState[2] == nState[2]
91 | assert oState[3] == nState[3]
92 | assert oState[4] == nState[4]
93 |
--------------------------------------------------------------------------------
/cosmoHammer/ChainContext.py:
--------------------------------------------------------------------------------
1 |
2 | PARENT_KEY = "key_parent"
3 | PARAMS_KEY = "key_params"
4 | DATA_KEY = "key_data"
5 |
6 | class ChainContext(object):
7 | """
8 | Context holding a dict to store data and information durring the computation of the likelihood
9 | """
10 |
11 | def __init__(self, parent, params):
12 | """
13 | Constructor of the context
14 | """
15 |
16 | self._data = dict()
17 | self.add(PARENT_KEY, parent)
18 | self.add(PARAMS_KEY, params)
19 | self.add(DATA_KEY, dict())
20 |
21 | def add(self, key, value):
22 | """
23 | Adds the value to the context using the key
24 |
25 | :param key: string
26 | key to use
27 | :param value: object
28 | the value to store
29 |
30 | """
31 | self._data[key] = value
32 |
33 | def remove(self, key):
34 | """
35 | Removes the value from the context
36 |
37 | :param key: string
38 | key to remove from the context
39 | """
40 | assert key != None
41 | del(self._data[key])
42 |
43 | def contains(self, key):
44 | """
45 | Checks if the key is in the context
46 |
47 | :param key: string
48 | key to check
49 |
50 | :return: True if the key is in the context
51 | """
52 | return key in self._data
53 |
54 | def get(self, key, default=None):
55 | """
56 | Returns the value stored in the context at the key or the default value in the
57 | context doesn't contain the key
58 |
59 | :param key: string
60 | key to use
61 | :param default: string
62 | the default value to use if the key is not available
63 | """
64 | if(self.contains(key)):
65 | return self._data[key]
66 |
67 | return default
68 |
69 | def getParams(self):
70 | """
71 | Returns the currently processed parameters
72 |
73 | :return: The param of this context
74 | """
75 | return self.get(PARAMS_KEY)
76 |
77 | def getParent(self):
78 | """
79 | Returns the parent
80 |
81 | :return: The parent chain of this context
82 | """
83 | return self.get(PARENT_KEY)
84 |
85 | def getData(self):
86 | """
87 | Returns the data
88 |
89 | :return: The data of this context
90 | """
91 | return self.get(DATA_KEY)
92 |
--------------------------------------------------------------------------------
/cosmoHammer/ConcurrentMpiCosmoHammerSampler.py:
--------------------------------------------------------------------------------
1 |
2 | import multiprocessing
3 | from cosmoHammer.MpiCosmoHammerSampler import MpiCosmoHammerSampler
4 |
5 |
6 | class ConcurrentMpiCosmoHammerSampler(MpiCosmoHammerSampler):
7 | """
8 | A sampler implementation extending the mpi sampler in order to allow to
9 | distribute the computation with MPI and using multiprocessing on a single node.
10 |
11 | :param threads: (optional)
12 | The number of threads to use for parallelization. If ``threads == 1``,
13 | then the ``multiprocessing`` module is not used but if
14 | ``threads > 1``, then a ``Pool`` object is created
15 |
16 | :param kwargs: key word arguments passed to the CosmoHammerSampler
17 |
18 | """
19 | def __init__(self, threads=1, **kwargs):
20 | """
21 | CosmoHammer sampler implementation
22 |
23 | """
24 |
25 | self.threads = threads
26 |
27 | super(ConcurrentMpiCosmoHammerSampler, self).__init__(**kwargs)
28 |
29 |
30 | def _getMapFunction(self):
31 | if self.threads > 1:
32 | pool = multiprocessing.Pool(self.threads)
33 | return pool.map
34 | else:
35 | return map
36 |
--------------------------------------------------------------------------------
/cosmoHammer/Constants.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | """
3 | Some constants used by the samplers
4 |
5 | """
6 |
7 | FILE_SUFFIX = ".out"
8 |
9 | LOG_FILE_SUFFIX = ".log"
10 |
11 | PROB_PREFIX = "prob"
12 |
13 | BURNIN_PREFIX = "burnin"
14 |
15 | STATE_PREFIX = "state"
16 |
17 | PROB_SUFFIX = PROB_PREFIX+FILE_SUFFIX
18 |
19 | BURNIN_SUFFIX = BURNIN_PREFIX+FILE_SUFFIX
20 |
21 | BURNIN_PROB_SUFFIX = BURNIN_PREFIX+PROB_PREFIX+FILE_SUFFIX
22 |
23 | BURNIN_STATE_SUFFIX = BURNIN_PREFIX+STATE_PREFIX+FILE_SUFFIX
24 |
--------------------------------------------------------------------------------
/cosmoHammer/CosmoHammerSampler.py:
--------------------------------------------------------------------------------
1 | from __future__ import print_function, division, absolute_import, unicode_literals
2 |
3 | import emcee
4 | import numpy as np
5 | import logging
6 | import time
7 |
8 | import cosmoHammer
9 | import cosmoHammer.Constants as c
10 |
11 | from cosmoHammer import getLogger
12 | from cosmoHammer.util import SampleFileUtil
13 | from cosmoHammer.util import SampleBallPositionGenerator
14 | from cosmoHammer.util.IterationStopCriteriaStrategy import IterationStopCriteriaStrategy
15 |
16 |
17 |
18 | class CosmoHammerSampler(object):
19 | """
20 | A complete sampler implementation taking care of correct setup, chain burn in and sampling.
21 |
22 | :param params: the parameter of the priors
23 | :param likelihoodComputationChain: the callable computation chain
24 | :param filePrefix: the prefix for the log and output files
25 | :param walkersRatio: the ratio of walkers and the count of sampled parameters
26 | :param burninIterations: number of iteration for burn in
27 | :param sampleIterations: number of iteration to sample
28 | :param stopCriteriaStrategy: the strategy to stop the sampling.
29 | Default is None an then IterationStopCriteriaStrategy is used
30 | :param initPositionGenerator: the generator for the init walker position.
31 | Default is None an then SampleBallPositionGenerator is used
32 | :param storageUtil: util used to store the results
33 | :param threadCount: The count of threads to be used for the computation. Default is 1
34 | :param reuseBurnin: Flag if the burn in should be reused.
35 | If true the values will be read from the file System. Default is False
36 |
37 | """
38 |
39 | def __init__(self, params, likelihoodComputationChain, filePrefix, walkersRatio, burninIterations,
40 | sampleIterations, stopCriteriaStrategy=None, initPositionGenerator=None,
41 | storageUtil=None, threadCount=1, reuseBurnin=False, logLevel=logging.INFO, pool=None):
42 | """
43 | CosmoHammer sampler implementation
44 |
45 | """
46 | self.params = params
47 | self.likelihoodComputationChain = likelihoodComputationChain
48 | self.walkersRatio = walkersRatio
49 | self.reuseBurnin = reuseBurnin
50 | self.filePrefix = filePrefix
51 | self.threadCount = threadCount
52 | self.paramCount = len(self.paramValues)
53 | self.nwalkers = self.paramCount*walkersRatio
54 | self.burninIterations = burninIterations
55 | self.sampleIterations = sampleIterations
56 |
57 | assert likelihoodComputationChain is not None, "The sampler needs a chain"
58 | assert sampleIterations > 0, "CosmoHammer needs to sample for at least one iterations"
59 |
60 | if not hasattr(self.likelihoodComputationChain, "params"):
61 | self.likelihoodComputationChain.params = params
62 |
63 | # setting up the logging
64 | self._configureLogging(filePrefix+c.LOG_FILE_SUFFIX, logLevel)
65 |
66 | if self.isMaster(): self.log("Using CosmoHammer "+str(cosmoHammer.__version__))
67 |
68 | # The sampler object
69 | self._sampler = self.createEmceeSampler(likelihoodComputationChain, pool=pool)
70 |
71 | if(storageUtil is None):
72 | storageUtil = self.createSampleFileUtil()
73 |
74 | self.storageUtil = storageUtil
75 |
76 | if(stopCriteriaStrategy is None):
77 | stopCriteriaStrategy = self.createStopCriteriaStrategy()
78 |
79 | stopCriteriaStrategy.setup(self)
80 | self.stopCriteriaStrategy = stopCriteriaStrategy
81 |
82 | if(initPositionGenerator is None):
83 | initPositionGenerator = self.createInitPositionGenerator()
84 |
85 | initPositionGenerator.setup(self)
86 | self.initPositionGenerator = initPositionGenerator
87 |
88 |
89 | def _configureLogging(self, filename, logLevel):
90 | logger = getLogger()
91 | logger.setLevel(logLevel)
92 | fh = logging.FileHandler(filename, "w")
93 | fh.setLevel(logLevel)
94 | # create console handler with a higher log level
95 | ch = logging.StreamHandler()
96 | ch.setLevel(logging.ERROR)
97 | # create formatter and add it to the handlers
98 | formatter = logging.Formatter('%(asctime)s %(levelname)s:%(message)s')
99 | fh.setFormatter(formatter)
100 | ch.setFormatter(formatter)
101 | # add the handlers to the logger
102 | for handler in logger.handlers[:]:
103 | logger.removeHandler(handler)
104 | logger.addHandler(fh)
105 | logger.addHandler(ch)
106 | # logging.basicConfig(format='%(asctime)s %(levelname)s:%(message)s',
107 | # filename=filename, filemode='w', level=logLevel)
108 |
109 |
110 | def createStopCriteriaStrategy(self):
111 | """
112 | Returns a new instance of a stop criteria stategy
113 | """
114 | return IterationStopCriteriaStrategy()
115 |
116 | def createSampleFileUtil(self):
117 | """
118 | Returns a new instance of a File Util
119 | """
120 | return SampleFileUtil(self.filePrefix, reuseBurnin=self.reuseBurnin)
121 |
122 | def createInitPositionGenerator(self):
123 | """
124 | Returns a new instance of a Init Position Generator
125 | """
126 | return SampleBallPositionGenerator()
127 |
128 | @property
129 | def paramValues(self):
130 | return self.params[:,0]
131 |
132 | @property
133 | def paramWidths(self):
134 | return self.params[:,3]
135 |
136 | def startSampling(self):
137 | """
138 | Launches the sampling
139 | """
140 | try:
141 | if self.isMaster(): self.log(self.__str__())
142 | if(self.burninIterations>0):
143 |
144 | if(self.reuseBurnin):
145 | pos, prob, rstate = self.loadBurnin()
146 | datas = [None]*len(pos)
147 |
148 | else:
149 | pos, prob, rstate, datas = self.startSampleBurnin()
150 | else:
151 | pos = self.createInitPos()
152 | prob = None
153 | rstate = None
154 | datas = None
155 | # Starting from the final position in the burn-in chain, sample for 1000
156 | # steps.
157 | self.log("start sampling after burn in")
158 | start = time.time()
159 | self.sample(pos, prob, rstate, datas)
160 | end = time.time()
161 | self.log("sampling done! Took: " + str(round(end-start,4))+"s")
162 |
163 | # Print out the mean acceptance fraction. In general, acceptance_fraction
164 | # has an entry for each walker
165 | self.log("Mean acceptance fraction:"+ str(round(np.mean(self._sampler.acceptance_fraction), 4)))
166 | finally:
167 | if self._sampler.pool is not None:
168 | try:
169 | self._sampler.pool.close()
170 | except AttributeError:
171 | pass
172 | try:
173 | self.storageUtil.close()
174 | except AttributeError:
175 | pass
176 |
177 |
178 |
179 | def loadBurnin(self):
180 | """
181 | loads the burn in form the file system
182 | """
183 | self.log("reusing previous burn in")
184 |
185 | pos = self.storageUtil.importFromFile(self.filePrefix+c.BURNIN_SUFFIX)[-self.nwalkers:]
186 |
187 | prob = self.storageUtil.importFromFile(self.filePrefix+c.BURNIN_PROB_SUFFIX)[-self.nwalkers:]
188 |
189 | rstate= self.storageUtil.importRandomState(self.filePrefix+c.BURNIN_STATE_SUFFIX)
190 |
191 | self.log("loading done")
192 | return pos, prob, rstate
193 |
194 |
195 | def startSampleBurnin(self):
196 | """
197 | Runs the sampler for the burn in
198 | """
199 | self.log("start burn in")
200 | start = time.time()
201 | p0 = self.createInitPos()
202 | pos, prob, rstate, data = self.sampleBurnin(p0)
203 | end = time.time()
204 | self.log("burn in sampling done! Took: " + str(round(end-start,4))+"s")
205 | self.log("Mean acceptance fraction for burn in:" + str(round(np.mean(self._sampler.acceptance_fraction), 4)))
206 |
207 | self.resetSampler()
208 |
209 | return pos, prob, rstate, data
210 |
211 |
212 | def resetSampler(self):
213 | """
214 | Resets the emcee sampler in the master node
215 | """
216 | if self.isMaster():
217 | self.log("Reseting emcee sampler")
218 | # Reset the chain to remove the burn-in samples.
219 | self._sampler.reset()
220 |
221 |
222 |
223 | def sampleBurnin(self, p0):
224 | """
225 | Run the emcee sampler for the burnin to create walker which are independent form their starting position
226 | """
227 |
228 | counter = 1
229 | for pos, prob, rstate, datas in self._sampler.sample(p0, iterations=self.burninIterations):
230 | if self.isMaster():
231 | self.storageUtil.persistBurninValues(pos, prob, datas)
232 | if(counter%10==0):
233 | self.log("Iteration finished:" + str(counter))
234 |
235 | counter = counter + 1
236 |
237 | if self.isMaster():
238 | self.log("storing random state")
239 | self.storageUtil.storeRandomState(self.filePrefix+c.BURNIN_STATE_SUFFIX, rstate)
240 |
241 | return pos, prob, rstate, datas
242 |
243 |
244 | def sample(self, burninPos, burninProb=None, burninRstate=None, datas=None):
245 | """
246 | Starts the sampling process
247 | """
248 | counter = 1
249 | for pos, prob, _, datas in self._sampler.sample(burninPos, lnprob0=burninProb, rstate0=burninRstate,
250 | blobs0=datas, iterations=self.sampleIterations):
251 | if self.isMaster():
252 | self.log("Iteration done. Persisting", logging.DEBUG)
253 | self.storageUtil.persistSamplingValues(pos, prob, datas)
254 |
255 | if(self.stopCriteriaStrategy.hasFinished()):
256 | break
257 |
258 | if(counter%10==0):
259 | self.log("Iteration finished:" + str(counter))
260 |
261 | counter = counter + 1
262 |
263 |
264 | def isMaster(self):
265 | """
266 | Returns True. Can be overridden for multitasking i.e. with MPI
267 | """
268 | return True
269 |
270 | def log(self, message, level=logging.INFO):
271 | """
272 | Logs a message to the logfile
273 | """
274 | getLogger().log(level, message)
275 |
276 |
277 | def createEmceeSampler(self, callable, **kwargs):
278 | """
279 | Factory method to create the emcee sampler
280 | """
281 | if self.isMaster(): self.log("Using emcee "+str(emcee.__version__))
282 | return emcee.EnsembleSampler(self.nwalkers,
283 | self.paramCount,
284 | callable,
285 | threads=self.threadCount,
286 | **kwargs)
287 |
288 | def createInitPos(self):
289 | """
290 | Factory method to create initial positions
291 | """
292 | return self.initPositionGenerator.generate()
293 |
294 |
295 | def getChain(self):
296 | """
297 | Returns the sample chain
298 | """
299 | return self._sampler.chain
300 |
301 | def __str__(self, *args, **kwargs):
302 | """
303 | Returns the string representation of the sampler config
304 | """
305 | desc = "Sampler: " + str(type(self))+"\n" \
306 | "configuration: \n" \
307 | " Params: " +str(self.paramValues)+"\n" \
308 | " Burnin iterations: " +str(self.burninIterations)+"\n" \
309 | " Samples iterations: " +str(self.sampleIterations)+"\n" \
310 | " Walkers ratio: " +str(self.walkersRatio)+"\n" \
311 | " Reusing burn in: " +str(self.reuseBurnin)+"\n" \
312 | " init pos generator: " +str(self.initPositionGenerator)+"\n" \
313 | " stop criteria: " +str(self.stopCriteriaStrategy)+"\n" \
314 | " storage util: " +str(self.storageUtil)+"\n" \
315 | "likelihoodComputationChain: \n" + str(self.likelihoodComputationChain) \
316 | +"\n"
317 |
318 | return desc
319 |
--------------------------------------------------------------------------------
/cosmoHammer/LikelihoodComputationChain.py:
--------------------------------------------------------------------------------
1 | from __future__ import print_function, division, absolute_import, unicode_literals
2 | import numpy as np
3 | from collections import deque
4 | import os
5 |
6 | from cosmoHammer.ChainContext import ChainContext
7 | from cosmoHammer.exceptions import LikelihoodComputationException
8 | from cosmoHammer import getLogger
9 | from cosmoHammer.util import Params
10 |
11 | class LikelihoodComputationChain(object):
12 | """
13 | Implementation of a likelihood computation chain.
14 | """
15 |
16 | def __init__(self, min=None, max=None):
17 | """
18 | Constructor for the likelihood chain
19 |
20 | :param min: array
21 | lower bound for the parameters
22 | :param max: array
23 | upper bound for the parameters
24 | """
25 | self.min = min
26 | self.max = max
27 | self._likelihoodModules = deque();
28 | self._coreModules = deque();
29 |
30 |
31 | def getCoreModules(self):
32 | """pointer to the likelihood module list """
33 | return self._coreModules
34 |
35 | def getLikelihoodModules(self):
36 | """pointer to the core module list """
37 | return self._likelihoodModules
38 |
39 | def addLikelihoodModule(self, module):
40 | """
41 | adds a module to the likelihood module list
42 |
43 | :param module: callable
44 | the callable module to add for the likelihood computation
45 | """
46 | self.getLikelihoodModules().append(module)
47 |
48 | def addCoreModule(self, module):
49 | """
50 | adds a module to the likelihood module list
51 |
52 | :param module: callable
53 | the callable module to add for the computation of the data
54 | """
55 | self.getCoreModules().append(module)
56 |
57 |
58 | def isValid(self, p):
59 | """
60 | checks if the given parameters are valid
61 | """
62 | if(self.min is not None):
63 | for i in range(len(p)):
64 | if (p[i]self.max[i]):
71 | getLogger().debug("Params out of bounds i="+str(i)+" params "+str(p))
72 | return False
73 |
74 | return True
75 |
76 |
77 | def setup(self):
78 | """sets up the chain and its modules """
79 | for cModule in self.getCoreModules():
80 | cModule.setup()
81 |
82 | for cModule in self.getLikelihoodModules():
83 | cModule.setup()
84 |
85 |
86 | def __call__(self, p):
87 | """
88 | Computes the log likelihood by calling all the core and likelihood modules.
89 |
90 | :param p: the parameter array for which the likelihood should be evaluated
91 |
92 | :return: the current likelihood and a dict with additional data
93 | """
94 | try:
95 | getLogger().debug("pid: %s, processing: %s"%(os.getpid(), p))
96 | if not self.isValid(p):
97 | raise LikelihoodComputationException()
98 |
99 | ctx = self.createChainContext(p)
100 |
101 | self.invokeCoreModules(ctx)
102 |
103 | likelihood = self.computeLikelihoods(ctx)
104 | getLogger().debug("pid: %s, processed. Returning: %s"%(os.getpid(), likelihood))
105 | return likelihood, ctx.getData()
106 | except LikelihoodComputationException:
107 | getLogger().debug("pid: %s, processed. Returning: %s"%(os.getpid(), -np.inf))
108 | return -np.inf, []
109 |
110 | def createChainContext(self, p):
111 | """
112 | Returns a new instance of a chain context
113 | """
114 | try:
115 | p = Params(*zip(self.params.keys, p))
116 | except Exception:
117 | # no params or params has no keys
118 | pass
119 | return ChainContext(self, p)
120 |
121 | def invokeCoreModules(self, ctx):
122 | """
123 | Iterates thru the core modules and invokes them
124 | """
125 | for cModule in self.getCoreModules():
126 | self.invokeCoreModule(cModule, ctx)
127 |
128 |
129 | def invokeCoreModule(self, coreModule, ctx):
130 | """
131 | Invokes the given module with the given ChainContext
132 | """
133 | coreModule(ctx)
134 |
135 |
136 | def computeLikelihoods(self, ctx):
137 | """
138 | Computes the likelihoods by iterating thru all the modules.
139 | Sums up the log likelihoods.
140 | """
141 | likelihood = 0
142 |
143 | for lModule in self.getLikelihoodModules():
144 | likelihood += self.invokeLikelihoodModule(lModule, ctx)
145 |
146 | return likelihood
147 |
148 | def invokeLikelihoodModule(self, likelihoodModule, ctx):
149 | """
150 | Invokes the given module with the given ChainContext
151 | """
152 | return likelihoodModule.computeLikelihood(ctx)
153 |
154 | def __str__(self, *args, **kwargs):
155 | s = "Core Modules: \n "
156 | s = s + "\n ".join([type(o).__name__ for o in self.getCoreModules()])
157 |
158 | s = s + "\nLikelihood Modules: \n "
159 | s = s + "\n ".join([type(o).__name__ for o in self.getLikelihoodModules()])
160 | return s
161 |
--------------------------------------------------------------------------------
/cosmoHammer/MpiCosmoHammerSampler.py:
--------------------------------------------------------------------------------
1 |
2 | from cosmoHammer import CosmoHammerSampler
3 |
4 | from cosmoHammer.util.SampleFileUtil import SampleFileUtil
5 | from cosmoHammer.util.MpiUtil import MpiPool, mpiBCast
6 |
7 | class MpiCosmoHammerSampler(CosmoHammerSampler):
8 | """
9 | A sampler implementation extending the regular sampler in order to allow for distributing
10 | the computation with MPI.
11 |
12 | :param kwargs:
13 | key word arguments passed to the CosmoHammerSampler
14 |
15 | """
16 | def __init__(self, **kwargs):
17 | """
18 | CosmoHammer sampler implementation
19 |
20 | """
21 | self.pool = MpiPool(self._getMapFunction())
22 | self.rank = self.pool.rank
23 |
24 | super(MpiCosmoHammerSampler, self).__init__(pool=self.pool, **kwargs)
25 |
26 |
27 |
28 | def _getMapFunction(self):
29 | """
30 | Returns the build in map function
31 | """
32 | return map
33 |
34 | def createSampleFileUtil(self):
35 | """
36 | Returns a new instance of a File Util
37 | """
38 | return SampleFileUtil(self.filePrefix, self.isMaster(), reuseBurnin=self.reuseBurnin)
39 |
40 |
41 | def sampleBurnin(self, p0):
42 | """
43 | Starts the sampling process. The master node (mpi rank = 0) persists the result to the disk
44 | """
45 | p0 = mpiBCast(p0)
46 |
47 | self.log("MPI Process rank "+ str(self.rank)+" starts sampling")
48 | return super(MpiCosmoHammerSampler, self).sampleBurnin(p0);
49 |
50 | def sample(self, burninPos, burninProb, burninRstate, datas):
51 | """
52 | Starts the sampling process. The master node (mpi rank = 0) persists the result to the disk
53 | """
54 | burninPos = mpiBCast(burninPos)
55 | burninProb = mpiBCast(burninProb)
56 | burninRstate = mpiBCast(burninRstate)
57 |
58 | self.log("MPI Process rank "+ str(self.rank)+" starts sampling")
59 | super(MpiCosmoHammerSampler, self).sample(burninPos, burninProb, burninRstate, datas);
60 |
61 |
62 | def loadBurnin(self):
63 | """
64 | loads the burn in form the file system
65 | """
66 | if(self.isMaster()):
67 | pos, prob, rstate = super(MpiCosmoHammerSampler, self).loadBurnin()
68 | else:
69 | pos, prob, rstate = []
70 |
71 | pos = mpiBCast(pos)
72 | prob = mpiBCast(prob)
73 | rstate = mpiBCast(rstate)
74 |
75 | self.log("loading done")
76 | return pos, prob, rstate
77 |
78 | def createInitPos(self):
79 | """
80 | Factory method to create initial positions
81 | """
82 | #bcast the positions to ensure that all mpi nodes start at the same position
83 | return mpiBCast(super(MpiCosmoHammerSampler, self).createInitPos())
84 |
85 |
86 | def isMaster(self):
87 | """
88 | Returns true if the rank is 0
89 | """
90 | return self.pool.isMaster()
--------------------------------------------------------------------------------
/cosmoHammer/__init__.py:
--------------------------------------------------------------------------------
1 | import logging
2 |
3 | # Author: Joel Akeret
4 | # Contact: jakeret@phys.ethz.ch
5 | """
6 | This is the CosmoHammer package.
7 | """
8 |
9 | __version__ = '0.6.1'
10 | __author__ = 'Joel Akeret'
11 | __credits__ = 'Institute for Astronomy ETHZ, Institute of 4D Technologies FHNW'
12 |
13 | def getLogger():
14 | return logging.getLogger(__name__)
15 |
16 |
17 | from cosmoHammer.CosmoHammerSampler import CosmoHammerSampler
18 | from cosmoHammer.MpiCosmoHammerSampler import MpiCosmoHammerSampler
19 | from cosmoHammer.ConcurrentMpiCosmoHammerSampler import ConcurrentMpiCosmoHammerSampler
20 |
21 | from cosmoHammer.LikelihoodComputationChain import LikelihoodComputationChain
22 | from cosmoHammer.ChainContext import ChainContext
23 |
24 | from cosmoHammer.pso.ParticleSwarmOptimizer import ParticleSwarmOptimizer
25 | from cosmoHammer.pso.MpiParticleSwarmOptimizer import MpiParticleSwarmOptimizer
26 |
--------------------------------------------------------------------------------
/cosmoHammer/exceptions.py:
--------------------------------------------------------------------------------
1 | #Created on Nov 11, 2013
2 | #author: jakeret
3 |
4 |
5 | class LikelihoodComputationException(Exception):
6 | '''
7 | Exception for likelihood computation
8 | '''
9 | def __init__(self):
10 | '''
11 | Constructor
12 | '''
13 | pass
14 |
15 | class InvalidLikelihoodException(LikelihoodComputationException):
16 | """
17 | Exception for invalid likelihoods e.g. -loglike >= 0.0
18 | """
19 |
20 | def __init__(self, params=None):
21 | self.params = params
22 |
23 |
--------------------------------------------------------------------------------
/cosmoHammer/modules/MultivarianteGaussianModule.py:
--------------------------------------------------------------------------------
1 | from __future__ import print_function, division, absolute_import, unicode_literals
2 |
3 | import numpy as np
4 | from cosmoHammer import getLogger
5 |
6 | class MultivarianteGaussianModule(object):
7 | """
8 | Chain for computing the likelihood of a multivariante gaussian distribution
9 | """
10 | def __init__(self, icov, mu):
11 | self.icov = icov
12 | self.mu = mu
13 |
14 |
15 | def computeLikelihood(self, ctx):
16 | x = ctx.getParams()
17 | diff = x-self.mu
18 | return -np.dot(diff,np.dot(self.icov,diff))/2.0
19 |
20 | def setup(self):
21 | getLogger().info("Multivariante Gaussian setup")
22 |
23 |
24 |
--------------------------------------------------------------------------------
/cosmoHammer/modules/PseudoCmbModule.py:
--------------------------------------------------------------------------------
1 | from __future__ import print_function, division, absolute_import, unicode_literals
2 |
3 | import numpy as np
4 | from cosmoHammer import getLogger
5 |
6 |
7 | #the real means..
8 | WMAP7_MEANS = [70.704, 0.02256, 0.1115, 2.18474E-09, 0.9688, 0.08920]
9 |
10 | # ...and non-trivial covariance matrix.
11 | _cov = np.array([[6.11E+00, 0, 0, 0, 0, 0],
12 | [7.19E-04, 3.26E-07, 0, 0, 0, 0],
13 | [-1.19E-02, -3.37E-07, 3.14E-05, 0, 0, 0],
14 | [-3.56E-11, 1.43E-14, 1.76E-13, 5.96E-21, 0, 0],
15 | [2.01E-02, 6.37E-06, -2.13E-05, 3.66E-13, 1.90E-04, 0],
16 | [1.10E-02, 2.36E-06, -1.92E-05, 8.70E-13, 7.32E-05, 2.23E-04]])
17 | _cov += _cov.T - np.diag(_cov.diagonal())
18 |
19 | # Invert the covariance matrix
20 | WMAP7_ICOV = np.linalg.inv(_cov)
21 |
22 |
23 | class PseudoCmbModule(object):
24 | """
25 | Chain for computing the likelihood of a multivariante gaussian distribution
26 | """
27 | def __init__(self, icov=WMAP7_ICOV, mu=WMAP7_MEANS, min_sz=0, max_sz=2):
28 | self.icov = icov
29 | self.mu = mu
30 | self.a = min_sz
31 | self.b = max_sz
32 |
33 |
34 | def computeLikelihood(self, ctx):
35 | x = ctx.getParams()
36 |
37 | diff = x[:6]-self.mu
38 |
39 | lnprob = -np.dot(diff,np.dot(self.icov,diff))/2.0
40 |
41 | lnprob -= np.log(self.b-self.a)
42 | return lnprob
43 |
44 | def setup(self):
45 | getLogger().info("Pseudo cmb setup")
46 |
47 |
48 |
--------------------------------------------------------------------------------
/cosmoHammer/modules/RosenbrockModule.py:
--------------------------------------------------------------------------------
1 | from __future__ import print_function, division, absolute_import, unicode_literals
2 | from cosmoHammer import getLogger
3 |
4 | class RosenbrockModule(object):
5 | """
6 | A module for the computation of the rosenbrock likelihood
7 | """
8 |
9 | def __init__(self):
10 | self.a1 = 100.0
11 | self.a2 = 20.0
12 |
13 | def computeLikelihood(self, ctx):
14 | p = ctx.getParams()
15 | return -(self.a1 * (p.y - p.x**2)**2 + (1 - p.x)**2) / self.a2
16 |
17 | def setup(self):
18 | getLogger().info("Rosenbrock setup")
--------------------------------------------------------------------------------
/cosmoHammer/modules/__init__.py:
--------------------------------------------------------------------------------
1 | from cosmoHammer.modules.RosenbrockModule import RosenbrockModule
2 | from cosmoHammer.modules.MultivarianteGaussianModule import MultivarianteGaussianModule
3 | from cosmoHammer.modules.PseudoCmbModule import PseudoCmbModule
4 |
--------------------------------------------------------------------------------
/cosmoHammer/pso/BestFitPositionGenerator.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on Oct 22, 2013
3 |
4 | @author: J.Akeret
5 | '''
6 | from __future__ import print_function, division, absolute_import, unicode_literals
7 |
8 | import numpy
9 | from cosmoHammer.pso.ParticleSwarmOptimizer import ParticleSwarmOptimizer
10 | from cosmoHammer.pso.CurvatureFitter import CurvatureFitter
11 |
12 | class BestFitPositionGenerator(object):
13 | '''
14 | A position generator which uses a particle swarm optimization algorithm
15 | to find the best fit value and the collapsed swarm to estimate the curvature matrix
16 | at that point. The optimization process can be parallelized over
17 | MPI and python multiprocessing.
18 |
19 | :param mpi: True if a MPI implementation of the PSO should be used. Default is False
20 | :param threads: Number of multiprocessing thread that should be started. Default is 1
21 | :param particleCount: Number of particle to use for the optimization. If none
22 | the number is derrived according to the size of the parameter space. Default is None
23 | :param maxIter: the maximal number of iterations. Default will be set to MAX_PSO_ITER
24 |
25 | '''
26 |
27 | MAX_PSO_ITER = 1000
28 |
29 | MIN_PARTICLE_COUNT = 20
30 |
31 | BEST_FILE_NAME = "_best_fit_global.out"
32 |
33 | BEST_INFO_FILE_NAME = "_best_fit_info.out"
34 |
35 | def __init__(self, mpi=False, threads=1, particleCount=None, maxIter=None):
36 | """
37 | default constructor
38 | """
39 | self.mpi = mpi
40 | self.threads = threads
41 | self.particleCount = particleCount
42 |
43 | self.maxIter = maxIter
44 | if(self.maxIter is None):
45 | self.maxIter = self.MAX_PSO_ITER
46 |
47 |
48 | def setup(self, sampler):
49 | """
50 | setup the generator
51 | """
52 | self.sampler = sampler
53 |
54 | def generate(self):
55 | """
56 | generates the positions by running the PSO and using the chain's min and max and then calling
57 | the paraboloid fitter in order to estimate the covariance matrix. The position will then
58 | be generated by drawing position from a multivariant gaussian distribution defined by
59 | the best fit and the estimated covariance matrix.
60 | The progress of the PSO is successively stored to a the disk.
61 | """
62 |
63 | chain = self.sampler.likelihoodComputationChain
64 |
65 | if(self.particleCount is None):
66 | self.particleCount = self.get_particle_count()
67 |
68 | if(self.mpi):
69 | #only import when needed in order to avoid an error in case mpi4py is not installed
70 | from cosmoHammer.sampler.util.pso.MpiParticleSwarmOptimizer import MpiParticleSwarmOptimizer
71 |
72 | pso = MpiParticleSwarmOptimizer(chain, chain.min, chain.max, self.particleCount, threads=self.threads)
73 | else:
74 | pso = ParticleSwarmOptimizer(chain, chain.min, chain.max, self.particleCount, threads=self.threads)
75 |
76 | swarm = []
77 | with open(self.sampler.filePrefix+self.BEST_FILE_NAME, "w") as f:
78 | for i, cswarm in enumerate(pso.sample(self.maxIter)):
79 | self._save(f, i, pso)
80 | if(i>=0):
81 | swarm.append(cswarm)
82 |
83 | self._save(f, i+1, pso)
84 | self.sampler.log("Best fit found after %s iteration: %f %s"%(i+1, pso.gbest.fitness, pso.gbest.position))
85 |
86 |
87 | fswarm = []
88 | for i in range(1,5):
89 | fswarm += swarm[-i]
90 |
91 | self._storeSwarm(fswarm)
92 |
93 | fitter = CurvatureFitter(fswarm, pso.gbest)
94 | mean, _cov = fitter.fit()
95 |
96 | self._storeFit(pso.gbest, _cov)
97 |
98 | # dim = len(mean)-1
99 | # sigma = 0.4
100 | # factor = _cov[dim,dim] / numpy.sqrt(sigma)
101 | # _cov[:-1,dim] = _cov[:-1,dim]/factor
102 | # _cov[dim,:-1] = _cov[dim,:-1]/factor
103 | # _cov[dim,dim] = sigma
104 | # print ""
105 | # fitter = ParaboloidFitter(fswarm, pso.gbest, True)
106 | # mean, _cov = fitter.fit()
107 | sigma = numpy.sqrt(numpy.diag(_cov))
108 | print("=> found sigma:", sigma)
109 |
110 | # fitter = ParaboloidFitter(pso.swarm, pso.gbest)
111 | # mean, _cov = fitter.fit()
112 | # sigma = numpy.sqrt(numpy.diag(_cov))
113 | # print "=> found sigma:", sigma
114 |
115 | samples = numpy.random.multivariate_normal(mean, _cov, self.sampler.nwalkers)
116 | # print numpy.std(samples, axis=0)
117 | return samples
118 |
119 | # self.sampler.paramValues = pso.gbest.position
120 | # self.sampler.paramWidths = self.sampler.paramValues * self.SPREAD_FACTOR
121 | # generator = SampleBallPositionGenerator()
122 | # generator.setup(self.sampler)
123 | # return generator.generate()
124 |
125 |
126 |
127 |
128 | def get_particle_count(self):
129 | """
130 | Generates the number of particles to use by using a logarithmic function of the parameter count
131 | """
132 | return int(self.MIN_PARTICLE_COUNT + self.MIN_PARTICLE_COUNT*numpy.log(self.sampler.paramCount))
133 |
134 | def __str__(self, *args, **kwargs):
135 | return "BestFitPositionGenerator: particleCount=%s, mpi=%s, threads=%s"%(self.particleCount, self.mpi, self.threads)
136 |
137 | def _save(self, f, i, pso):
138 | if(pso.isMaster()):
139 | particle = pso.gbest
140 | f.write("%s\t%f\t"%(i, particle.fitness))
141 | f.write("\t".join([str(p) for p in particle.position]))
142 | f.write("\n")
143 | f.flush()
144 |
145 | def _storeFit(self, gbest, _cov):
146 | with open(self.sampler.filePrefix+self.BEST_INFO_FILE_NAME, "w") as f:
147 | f.write("#Best fit: %s\n"%(gbest.fitness))
148 | f.write(", ".join([str(i) for i in gbest.position]))
149 | f.write("\n#Estimated covariance matrix:\n")
150 | for row in _cov:
151 | f.write ("[" + ", ".join([str(i) for i in row]) + "]\n")
152 |
153 | def _storeSwarm(self, swarm):
154 | with open(self.sampler.filePrefix+"swarm", "w") as f:
155 | for particle in swarm:
156 | f.write(str(particle.fitness))
157 | f.write("\t")
158 | f.write("\t".join([str(p) for p in particle.position]))
159 | f.write("\n")
--------------------------------------------------------------------------------
/cosmoHammer/pso/CurvatureFitter.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on Oct 30, 2013
3 |
4 | @author: J.Akeret
5 | '''
6 | from __future__ import print_function, division, absolute_import, \
7 | unicode_literals
8 |
9 | from numpy.linalg.linalg import norm
10 | from scipy.optimize.minpack import leastsq
11 | from scipy.optimize import minimize
12 | import numpy
13 | import sys
14 |
15 | def parabola(p, theta, thetabar=1):
16 | """
17 | Computation of the paraboloid for the given curvature matrix and samples.
18 | :param p: list of samples
19 | :param theta: vector containing the lower triangle of the matrix and the offset from the true mean
20 |
21 | :return: vector y from f(x,p)
22 | """
23 |
24 | leng, dim = theta.shape
25 | corrm, v, mu = transform(dim, p)
26 |
27 | # _cov = corr2cov(corrm, v)
28 | # R = numpy.linalg.inv(_cov)
29 | if(any(v==0)):
30 | vi = v
31 | else:
32 | vi = numpy.diag(1/v)
33 |
34 | R = numpy.dot(vi, numpy.dot(numpy.linalg.inv(corrm), vi))
35 |
36 | v = numpy.zeros(leng)
37 | for i,thetaj in enumerate(theta):
38 | thetaj = thetaj / thetabar
39 | v[i] = numpy.dot(thetaj.T,numpy.dot(R, thetaj)) #+ numpy.dot(thetaj, mu)
40 |
41 | return numpy.array(v)
42 |
43 |
44 | def errfunc(p,theta,delta, thetabar):
45 | """
46 | Error function defined by f(theta) - delta
47 | :param p: list of samples
48 | :param theta: the curvature matrix. see parabola def
49 | :param delta: the measured values
50 | """
51 | return parabola(p, theta, thetabar) - delta
52 |
53 | def errfunc2(p,theta,delta, thetabar):
54 | """
55 | Error function defined by f(theta) - delta
56 | :param p: the curvature matrix. see parabola def
57 | :param theta: list of samples
58 | :param delta: the measured values
59 | """
60 | return sum((parabola(p, theta, thetabar) - delta)**2)
61 |
62 | def transform(dim, p):
63 | """
64 | Transforms a vector containg the lower triangle of a matrix into a symmetric matrix
65 |
66 | :param p: the vector
67 |
68 | :return: the matrix and left over values
69 | """
70 | corrm = numpy.identity(dim)
71 | k=0
72 | for i in range(1,dim):
73 | for j in range(0,i):
74 | corrm[i,j]= p[k]
75 | k +=1
76 |
77 | corrm += corrm.T - numpy.diag(corrm.diagonal())
78 |
79 | vars = p[k:k+dim]
80 | mu = p[k+dim:]
81 |
82 | return corrm, vars, mu
83 |
84 | def reverse(dim, R, vars):
85 | """
86 | Transforms a symmetric matrix into a vector containig the lower triangle
87 |
88 | :param R: the symmetric matrix
89 |
90 | :return: the vector
91 | """
92 | p = numpy.zeros(dim*(dim-1)/2)
93 | k=0
94 | for i in range(1,dim):
95 | for j in range(0,i):
96 | p[k] = R[i,j]
97 | k +=1
98 |
99 | p = numpy.append(p, vars)
100 | return numpy.append(p, numpy.zeros_like(vars))
101 |
102 | def bound(x):
103 | dim = int(1./2 * (numpy.sqrt(8*len(x)+1)-1))
104 | _, stds, _ = transform(dim, x)
105 | return stds
106 |
107 |
108 | class CurvatureFitter(object):
109 | '''
110 | Fits a paraboloid centered around the global best fit of the PSO by estimating a curvarture
111 | matrix with the particle given in the swarm
112 |
113 | :param swarm: list of particles
114 | :param gbest: the global best particle at the last iteration
115 | '''
116 |
117 |
118 | def __init__(self, swarm, gbest):
119 | '''
120 | Constructor
121 | '''
122 | self.swarm = swarm
123 | self.gbest = gbest
124 |
125 | def fit(self):
126 | """
127 | Fits the paraboloid to the swarm particles
128 |
129 | :return: the mean = global best position and the estimated covariance matrix
130 | """
131 |
132 | scale = 10**0
133 | dim = len(self.gbest.position)
134 |
135 | x = numpy.array([particle.position * scale for particle in self.swarm])
136 | theta = (x - self.gbest.position * scale) #/ (self.gbest.position * scale)
137 | norms = numpy.array(list(map(norm, theta)))
138 |
139 | b = (norms < 0.1)
140 | theta = theta[b]
141 | fitness = numpy.array([particle.fitness * scale for particle in self.swarm])
142 |
143 | fitness = fitness[b]
144 | delta = -2*(fitness - self.gbest.fitness * scale)
145 |
146 | _cov = self.minimize1(dim, theta, delta)
147 | _cov = self.minimize2(dim, theta, delta)
148 |
149 | return self.gbest.position, _cov
150 |
151 | def minimize1(self, dim, theta, delta):
152 | p0Cor = numpy.random.uniform(-1,1,dim**2).reshape(dim, dim)
153 | p0Cor = p0Cor - numpy.diag(p0Cor) + numpy.identity(dim)
154 |
155 | p0 = reverse(dim, numpy.identity(dim), numpy.ones(dim)/20)
156 | popt, _,infodict,mesg,_ = leastsq(errfunc, p0, args=(theta, delta, self.gbest.position),full_output=True)
157 | print(mesg)
158 |
159 |
160 | ss_err=(infodict['fvec']**2).sum()
161 | ss_tot=((delta-delta.mean())**2).sum()
162 | rsquared=1-(ss_err/ss_tot)
163 | print("rsquared", rsquared)
164 |
165 | corrm, var, mu = transform(dim, popt)
166 | var = var * self.gbest.position
167 | _cov = corr2cov(corrm, var)
168 |
169 | print("used mu:", mu)
170 | print("found _cov:\n", _cov)
171 |
172 | sigma = numpy.sqrt(numpy.diag(_cov))
173 | print( "=> found sigma:", sigma)
174 |
175 | return _cov
176 |
177 | def minimize2(self, dim, theta, delta):
178 | cons = (
179 | {'type': 'ineq',
180 | 'fun' : lambda x: bound(x)})
181 |
182 | p0 = reverse(dim, numpy.identity(dim), numpy.ones(dim)*self.gbest.position/10)
183 | res = minimize(errfunc2, p0, args=(theta, delta, self.gbest.position), constraints=cons, method='SLSQP', options={'disp': True, "ftol":10**-17})
184 | popt=res.x
185 |
186 | corrm, var, mu = transform(dim, popt)
187 | var = var * self.gbest.position
188 | _cov = corr2cov(corrm, var)
189 |
190 | print("used mu:", mu)
191 | print("found _cov:\n", _cov)
192 |
193 | sigma = numpy.sqrt(numpy.diag(_cov))
194 | print( "=> found sigma:", sigma)
195 |
196 | return _cov
197 |
198 | def corr2cov(corrm, var):
199 | dim = len(var)
200 | covm = numpy.empty((dim,dim))
201 | for i in range(len(corrm)):
202 | for j in range(len(corrm)):
203 | covm[i,j] = corrm[i,j]*var[i]*var[j]
204 |
205 | return covm
206 |
207 | def rescale(_cov, v, dim):
208 | #rescaling
209 | cov2 = numpy.empty((dim, dim))
210 | for i in range(dim):
211 | for j in range(dim):
212 | cov2[i,j] = _cov[i,j] * v[i] * v[j]
213 | return cov2
--------------------------------------------------------------------------------
/cosmoHammer/pso/MpiParticleSwarmOptimizer.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on Oct 28, 2013
3 |
4 | @author: J.Akeret
5 | '''
6 | from __future__ import print_function, division, absolute_import, \
7 | unicode_literals
8 |
9 | import multiprocessing
10 | import numpy
11 |
12 | from cosmoHammer.util.MpiUtil import MpiPool, mpiBCast
13 | from cosmoHammer.pso.ParticleSwarmOptimizer import ParticleSwarmOptimizer
14 |
15 |
16 |
17 | class MpiParticleSwarmOptimizer(ParticleSwarmOptimizer):
18 | """
19 | PSO with support for MPI to distribute the workload over multiple nodes
20 | """
21 |
22 | def __init__(self, func, low, high, particleCount=25, threads=1):
23 | self.threads = threads
24 | pool = MpiPool(self._getMapFunction())
25 | super(MpiParticleSwarmOptimizer, self).__init__(func, low, high, particleCount=particleCount, pool=pool)
26 |
27 |
28 | def _getMapFunction(self):
29 | if self.threads > 1:
30 | pool = multiprocessing.Pool(self.threads)
31 | return pool.map
32 | else:
33 | return map
34 |
35 | def _converged(self, it, p, m, n):
36 |
37 | if(self.isMaster()):
38 | converged = super(MpiParticleSwarmOptimizer, self)._converged(it, p, m, n)
39 | else:
40 | converged = False
41 |
42 | converged = mpiBCast(converged)
43 | return converged
44 |
45 | def _get_fitness(self,swarm):
46 | mapFunction = self.pool.map
47 |
48 | mpiSwarm = mpiBCast(swarm)
49 |
50 | pos = numpy.array([part.position for part in mpiSwarm])
51 | results = mapFunction(self.func, pos)
52 | lnprob = numpy.array([l[0] for l in results])
53 | for i, particle in enumerate(swarm):
54 | particle.fitness = lnprob[i]
55 | particle.position = pos[i]
56 |
57 | def isMaster(self):
58 | return self.pool.isMaster()
--------------------------------------------------------------------------------
/cosmoHammer/pso/ParticleSwarmOptimizer.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on Sep 30, 2013
3 |
4 | @author: J. Akeret
5 | '''
6 | from __future__ import print_function, division, absolute_import, unicode_literals
7 | from copy import copy
8 | from math import floor
9 | import math
10 | import multiprocessing
11 | import numpy
12 |
13 | class ParticleSwarmOptimizer(object):
14 | '''
15 | Optimizer using a swarm of particles
16 |
17 | :param func:
18 | A function that takes a vector in the parameter space as input and
19 | returns the natural logarithm of the posterior probability for that
20 | position.
21 |
22 | :param low: array of the lower bound of the parameter space
23 | :param high: array of the upper bound of the parameter space
24 | :param particleCount: the number of particles to use.
25 | :param threads: (optional)
26 | The number of threads to use for parallelization. If ``threads == 1``,
27 | then the ``multiprocessing`` module is not used but if
28 | ``threads > 1``, then a ``Pool`` object is created and calls to
29 | ``lnpostfn`` are run in parallel.
30 |
31 | :param pool: (optional)
32 | An alternative method of using the parallelized algorithm. If
33 | provided, the value of ``threads`` is ignored and the
34 | object provided by ``pool`` is used for all parallelization. It
35 | can be any object with a ``map`` method that follows the same
36 | calling sequence as the built-in ``map`` function.
37 |
38 | '''
39 |
40 |
41 | def __init__(self, func, low, high, particleCount=25, threads=1, pool=None):
42 | '''
43 | Constructor
44 | '''
45 | self.func = func
46 | self.low = low
47 | self.high = high
48 | self.particleCount = particleCount
49 | self.threads = threads
50 | self.pool = pool
51 |
52 | if self.threads > 1 and self.pool is None:
53 | self.pool = multiprocessing.Pool(self.threads)
54 |
55 | self.paramCount = len(self.low)
56 |
57 | self.swarm = self._initSwarm()
58 | self.gbest = Particle.create(self.paramCount)
59 |
60 | def _initSwarm(self):
61 | swarm = []
62 | for _ in range(self.particleCount):
63 | swarm.append(Particle(numpy.random.uniform(self.low, self.high, size=self.paramCount), numpy.zeros(self.paramCount)))
64 |
65 | return swarm
66 |
67 | def sample(self, maxIter=1000, c1=1.193, c2=1.193, p=0.7, m=10**-3, n=10**-2):
68 | """
69 | Launches the PSO. Yields the complete swarm per iteration
70 |
71 | :param maxIter: maximum iterations
72 | :param c1: cognitive weight
73 | :param c2: social weight
74 | :param p: stop criterion, percentage of particles to use
75 | :param m: stop criterion, difference between mean fitness and global best
76 | :param n: stop criterion, difference between norm of the particle vector and norm of the global best
77 | """
78 | self._get_fitness(self.swarm)
79 | i = 0
80 | while True:
81 |
82 |
83 | for particle in self.swarm:
84 | if ((self.gbest.fitness) particle.pbest.fitness):
91 | particle.updatePBest()
92 |
93 | if(i>=maxIter):
94 | print("max iteration reached! stoping")
95 | return
96 |
97 | if(self._converged(i, p=p,m=m, n=n)):
98 | if(self.isMaster()):
99 | print("converged after %s iterations!"%i)
100 | print("best fit found: ", self.gbest.fitness, self.gbest.position)
101 | return
102 |
103 |
104 | for particle in self.swarm:
105 |
106 | w = 0.5 + numpy.random.uniform(0,1,size=self.paramCount)/2
107 | #w=0.72
108 | part_vel = w * particle.velocity
109 | cog_vel = c1 * numpy.random.uniform(0,1,size=self.paramCount) * (particle.pbest.position - particle.position)
110 | soc_vel = c2 * numpy.random.uniform(0,1,size=self.paramCount) * (self.gbest.position - particle.position)
111 | particle.velocity = part_vel + cog_vel + soc_vel
112 | particle.position = particle.position + particle.velocity
113 |
114 | self._get_fitness(self.swarm)
115 |
116 | swarm = []
117 | for particle in self.swarm:
118 | swarm.append(particle.copy())
119 | yield swarm
120 |
121 | i+=1
122 |
123 | def optimize(self, maxIter=1000, c1=1.193, c2=1.193, p=0.7, m=10**-3, n=10**-2):
124 | """
125 | Runs the complete optimiziation.
126 |
127 | :param maxIter: maximum iterations
128 | :param c1: cognitive weight
129 | :param c2: social weight
130 | :param p: stop criterion, percentage of particles to use
131 | :param m: stop criterion, difference between mean fitness and global best
132 | :param n: stop criterion, difference between norm of the particle vector and norm of the global best
133 |
134 | :return swarms, gBests: the swarms and the global bests of all iterations
135 | """
136 |
137 | swarms = []
138 | gBests = []
139 | for swarm in self.sample(maxIter,c1,c2,p,m,n):
140 | swarms.append(swarm)
141 | gBests.append(self.gbest.copy())
142 |
143 | return swarms, gBests
144 |
145 | def _get_fitness(self,swarm):
146 |
147 | # If the `pool` property of the pso has been set (i.e. we want
148 | # to use `multiprocessing`), use the `pool`'s map method. Otherwise,
149 | # just use the built-in `map` function.
150 | if self.pool is not None:
151 | mapFunction = self.pool.map
152 | else:
153 | mapFunction = map
154 |
155 | pos = numpy.array([part.position for part in swarm])
156 | results = mapFunction(self.func, pos)
157 | lnprob = numpy.array([l[0] for l in results])
158 | for i, particle in enumerate(swarm):
159 | particle.fitness = lnprob[i]
160 |
161 | def _converged(self, it, p, m, n):
162 | # test = self._convergedSpace2(p=p)
163 | # print(test)
164 | fit = self._convergedFit(it=it, p=p, m=m)
165 | if(fit):
166 | space = self._convergedSpace(it=it, p=p, m=n)
167 | return space
168 | else:
169 | return False
170 |
171 | def _convergedFit(self, it, p, m):
172 | bestSort = numpy.sort([particle.pbest.fitness for particle in self.swarm])[::-1]
173 | meanFit = numpy.mean(bestSort[1:int(math.floor(self.particleCount*p))])
174 | # print( "best %f, meanFit %f, ration %f"%( self.gbest[0], meanFit, abs((self.gbest[0]-meanFit))))
175 | return (abs(self.gbest.fitness-meanFit) ['key1', 'key2']
26 |
27 | $ print(params.key1)
28 | > [1, 2, 3]
29 |
30 | $ params[:,0] = 0
31 |
32 | $ print(params.values)
33 | > [[0 2 3]
34 | [0 2 3]]
35 |
36 | $ print(params[:,1])
37 | > [2 2]
38 |
39 | """
40 |
41 | def __init__(self, *args):
42 |
43 | values = []
44 | self._keys = []
45 | for k,v in args:
46 | if k in self._keys:
47 | raise KeyError("Duplicated key '%s'"%k)
48 |
49 | self.__dict__[k] = v
50 | self._keys.append(k)
51 | values.append(v)
52 | self._values = np.array(values)
53 |
54 | def __getitem__(self, slice):
55 | return self.values[slice]
56 |
57 | def __setitem__(self, slice, value):
58 | self.values[slice] = value
59 |
60 | def __str__(self):
61 | return ",".join(("%s=%s"%(k,v) for k,v in zip(self.keys, self.values)))
62 |
63 | @property
64 | def keys(self):
65 | return copy(self._keys)
66 |
67 | @property
68 | def values(self):
69 | return self._values
70 |
71 | def get(self, key):
72 | return self.__dict__[key]
73 |
74 | def copy(self):
75 | return Params(*zip(self.keys, self.values))
--------------------------------------------------------------------------------
/cosmoHammer/util/SampleBallPositionGenerator.py:
--------------------------------------------------------------------------------
1 |
2 | import numpy as np
3 |
4 |
5 | class SampleBallPositionGenerator(object):
6 | """
7 | Generates samples in a very thight n-dimensional ball
8 | """
9 |
10 | def setup(self, sampler):
11 | """
12 | setup the generator
13 | """
14 | self.sampler = sampler
15 |
16 | def generate(self):
17 | """
18 | generates the positions
19 | """
20 |
21 | return [self.sampler.paramValues+np.random.normal(size=self.sampler.paramCount)*self.sampler.paramWidths for i in range(self.sampler.nwalkers)]
22 |
23 | def __str__(self, *args, **kwargs):
24 | return "SampleBallPositionGenerator"
--------------------------------------------------------------------------------
/cosmoHammer/util/SampleFileUtil.py:
--------------------------------------------------------------------------------
1 |
2 | import pickle
3 | import numpy as np
4 | import cosmoHammer.Constants as c
5 |
6 | class SampleFileUtil(object):
7 | """
8 | Util for handling sample files
9 |
10 | :param filePrefix: the prefix to use
11 | :param master: True if the sampler instance is the master
12 | :param reuseBurnin: True if the burn in data from a previous run should be used
13 |
14 | """
15 |
16 | def __init__(self, filePrefix, master=True, reuseBurnin=False):
17 | self.filePrefix = filePrefix
18 |
19 | if(master):
20 | if(reuseBurnin):
21 | mode = "r"
22 | else:
23 | mode = "w"
24 | self.samplesFileBurnin = open(self.filePrefix+c.BURNIN_SUFFIX, mode)
25 | self.probFileBurnin = open(self.filePrefix+c.BURNIN_PROB_SUFFIX, mode)
26 |
27 | self.samplesFile = open(self.filePrefix+c.FILE_SUFFIX, "w")
28 | self.probFile = open(self.filePrefix+c.PROB_SUFFIX, "w")
29 |
30 | def importFromFile(self, filePath):
31 | values = np.loadtxt(filePath, dtype=float)
32 | return values
33 |
34 | def storeRandomState(self, filePath, randomState):
35 | with open(filePath,'wb') as f:
36 | pickle.dump(randomState, f)
37 |
38 | def importRandomState(self, filePath):
39 | with open(filePath,'rb') as f:
40 | state = pickle.load(f)
41 | return state
42 |
43 | def persistBurninValues(self, pos, prob, data):
44 | self.persistValues(self.samplesFileBurnin, self.probFileBurnin, pos, prob, data)
45 |
46 | def persistSamplingValues(self, pos, prob, data):
47 | self.persistValues(self.samplesFile, self.probFile, pos, prob, data)
48 |
49 |
50 | def persistValues(self, posFile, probFile, pos, prob, data):
51 | """
52 | Writes the walker positions and the likelihood to the disk
53 | """
54 | posFile.write("\n".join(["\t".join([str(q) for q in p]) for p in pos]))
55 | posFile.write("\n")
56 | posFile.flush()
57 |
58 | probFile.write("\n".join([str(p) for p in prob]))
59 | probFile.write("\n")
60 | probFile.flush();
61 |
62 | def close(self):
63 | self.samplesFileBurnin.close()
64 | self.probFileBurnin.close()
65 | self.samplesFile.close()
66 | self.probFile.close()
67 |
68 | def __str__(self, *args, **kwargs):
69 | return "SampleFileUtil"
--------------------------------------------------------------------------------
/cosmoHammer/util/__init__.py:
--------------------------------------------------------------------------------
1 |
2 | from cosmoHammer.util.SampleFileUtil import SampleFileUtil
3 | from cosmoHammer.util.InMemoryStorageUtil import InMemoryStorageUtil
4 | from cosmoHammer.util.SampleBallPositionGenerator import SampleBallPositionGenerator
5 | from cosmoHammer.util.FlatPositionGenerator import FlatPositionGenerator
6 | from cosmoHammer.util.Params import Params
7 |
--------------------------------------------------------------------------------
/doc/.gitignore:
--------------------------------------------------------------------------------
1 | /api
2 | /build
3 |
--------------------------------------------------------------------------------
/doc/Makefile:
--------------------------------------------------------------------------------
1 | # Makefile for Sphinx documentation
2 | #
3 |
4 | # You can set these variables from the command line.
5 | SPHINXOPTS =
6 | SPHINXBUILD = sphinx-build
7 | PAPER =
8 | BUILDDIR = build
9 |
10 | # Internal variables.
11 | PAPEROPT_a4 = -D latex_paper_size=a4
12 | PAPEROPT_letter = -D latex_paper_size=letter
13 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source
14 | # the i18n builder cannot share the environment and doctrees with the others
15 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source
16 |
17 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
18 |
19 | help:
20 | @echo "Please use \`make ' where is one of"
21 | @echo " html to make standalone HTML files"
22 | @echo " dirhtml to make HTML files named index.html in directories"
23 | @echo " singlehtml to make a single large HTML file"
24 | @echo " pickle to make pickle files"
25 | @echo " json to make JSON files"
26 | @echo " htmlhelp to make HTML files and a HTML help project"
27 | @echo " qthelp to make HTML files and a qthelp project"
28 | @echo " devhelp to make HTML files and a Devhelp project"
29 | @echo " epub to make an epub"
30 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
31 | @echo " latexpdf to make LaTeX files and run them through pdflatex"
32 | @echo " text to make text files"
33 | @echo " man to make manual pages"
34 | @echo " texinfo to make Texinfo files"
35 | @echo " info to make Texinfo files and run them through makeinfo"
36 | @echo " gettext to make PO message catalogs"
37 | @echo " changes to make an overview of all changed/added/deprecated items"
38 | @echo " linkcheck to check all external links for integrity"
39 | @echo " doctest to run all doctests embedded in the documentation (if enabled)"
40 |
41 | clean:
42 | -rm -rf $(BUILDDIR)/*
43 |
44 | html:
45 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
46 | @echo
47 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
48 |
49 | dirhtml:
50 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
51 | @echo
52 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
53 |
54 | singlehtml:
55 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
56 | @echo
57 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
58 |
59 | pickle:
60 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
61 | @echo
62 | @echo "Build finished; now you can process the pickle files."
63 |
64 | json:
65 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
66 | @echo
67 | @echo "Build finished; now you can process the JSON files."
68 |
69 | htmlhelp:
70 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
71 | @echo
72 | @echo "Build finished; now you can run HTML Help Workshop with the" \
73 | ".hhp project file in $(BUILDDIR)/htmlhelp."
74 |
75 | qthelp:
76 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
77 | @echo
78 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \
79 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:"
80 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/CosmoHammer.qhcp"
81 | @echo "To view the help file:"
82 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/CosmoHammer.qhc"
83 |
84 | devhelp:
85 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
86 | @echo
87 | @echo "Build finished."
88 | @echo "To view the help file:"
89 | @echo "# mkdir -p $$HOME/.local/share/devhelp/CosmoHammer"
90 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/CosmoHammer"
91 | @echo "# devhelp"
92 |
93 | epub:
94 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
95 | @echo
96 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub."
97 |
98 | latex:
99 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
100 | @echo
101 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
102 | @echo "Run \`make' in that directory to run these through (pdf)latex" \
103 | "(use \`make latexpdf' here to do that automatically)."
104 |
105 | latexpdf:
106 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
107 | @echo "Running LaTeX files through pdflatex..."
108 | $(MAKE) -C $(BUILDDIR)/latex all-pdf
109 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
110 |
111 | text:
112 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
113 | @echo
114 | @echo "Build finished. The text files are in $(BUILDDIR)/text."
115 |
116 | man:
117 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
118 | @echo
119 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man."
120 |
121 | texinfo:
122 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
123 | @echo
124 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
125 | @echo "Run \`make' in that directory to run these through makeinfo" \
126 | "(use \`make info' here to do that automatically)."
127 |
128 | info:
129 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
130 | @echo "Running Texinfo files through makeinfo..."
131 | make -C $(BUILDDIR)/texinfo info
132 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
133 |
134 | gettext:
135 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
136 | @echo
137 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
138 |
139 | changes:
140 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
141 | @echo
142 | @echo "The overview file is in $(BUILDDIR)/changes."
143 |
144 | linkcheck:
145 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
146 | @echo
147 | @echo "Link check complete; look for any errors in the above output " \
148 | "or in $(BUILDDIR)/linkcheck/output.txt."
149 |
150 | doctest:
151 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
152 | @echo "Testing of doctests in the sources finished, look at the " \
153 | "results in $(BUILDDIR)/doctest/output.txt."
154 |
--------------------------------------------------------------------------------
/doc/check_sphinx.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on Dec 2, 2013
3 |
4 | @author: jakeret
5 | '''
6 | import py
7 | import subprocess
8 | def test_linkcheck(tmpdir):
9 | doctrees = tmpdir.join("doctrees")
10 | htmldir = tmpdir.join("html")
11 | subprocess.check_call(
12 | ["sphinx-build", "-blinkcheck",
13 | "-d", str(doctrees), "./source", str(htmldir)])
14 |
15 | def test_build_docs(tmpdir):
16 | doctrees = tmpdir.join("doctrees")
17 | htmldir = tmpdir.join("html")
18 | subprocess.check_call([
19 | "sphinx-build", "-bhtml",
20 | "-d", str(doctrees), "./source", str(htmldir)])
--------------------------------------------------------------------------------
/doc/source/api.rst:
--------------------------------------------------------------------------------
1 | .. _api:
2 |
3 | API
4 | ***
5 |
6 | .. automodule:: cosmoHammer
7 |
8 | This page details the methods and classes provided by the ``cosmoHammer`` module.
9 |
10 |
11 | Samplers
12 | --------
13 |
14 | :mod:`CosmoHammerSampler` Module
15 | ===================================
16 |
17 | Standard usage of ``CosmoHammer`` involves instantiating an
18 | :class:`CosmoHammerSampler`.
19 |
20 | .. autoclass:: cosmoHammer.CosmoHammerSampler
21 | :members:
22 |
23 |
24 | :mod:`MpiCosmoHammerSampler` Module
25 | ===================================
26 |
27 | To distribute ``CosmoHammer`` in a cluster involves instantiating an
28 | :class:`MpiCosmoHammerSampler`.
29 |
30 | .. autoclass:: cosmoHammer.MpiCosmoHammerSampler
31 | :show-inheritance:
32 |
33 | :mod:`ConcurrentMpiCosmoHammerSampler` Module
34 | =============================================
35 |
36 | To distribute ``CosmoHammer`` in a cluster and to spawn multiple processes involves instantiating an
37 | :class:`ConcurrentMpiCosmoHammerSampler`.
38 |
39 | .. autoclass:: cosmoHammer.ConcurrentMpiCosmoHammerSampler
40 | :members:
41 | :show-inheritance:
42 |
43 | CosmoHammer Chains
44 | -------------------------------------
45 |
46 | ``CosmoHammer`` comes with a plain vanillia chain implementation
47 | :class:`LikelihoodComputationChain`.
48 |
49 | .. autoclass:: cosmoHammer.LikelihoodComputationChain
50 | :members:
51 |
52 | .. autoclass:: cosmoHammer.ChainContext
53 | :members:
54 |
55 | CosmoHammer Exceptions
56 | -------------------------------------
57 |
58 | ``CosmoHammer`` may raise the following exceptions while execution
59 |
60 | .. automodule:: cosmoHammer.exceptions
61 | :members:
62 | :undoc-members:
63 | :show-inheritance:
64 |
65 |
66 | CosmoHammer Utils
67 | -------------------------------------
68 |
69 | .. autoclass:: cosmoHammer.util.Params
70 | :members:
71 |
72 | .. autoclass:: cosmoHammer.util.SampleBallPositionGenerator
73 | :members:
74 |
75 | .. autoclass:: cosmoHammer.util.FlatPositionGenerator
76 | :members:
77 |
78 | .. autoclass:: cosmoHammer.util.SampleFileUtil
79 | :members:
80 |
81 | .. autoclass:: cosmoHammer.util.InMemoryStorageUtil
82 | :members:
83 |
84 |
85 |
86 | ParticleSwarmOptimizer Package
87 | ------------------------------
88 |
89 | :mod:`ParticleSwarmOptimizer` Module
90 | ====================================
91 |
92 | .. autoclass:: cosmoHammer.ParticleSwarmOptimizer
93 | :members:
94 |
95 |
96 | :mod:`MpiParticleSwarmOptimizer` Module
97 | =======================================
98 |
99 | .. autoclass:: cosmoHammer.MpiParticleSwarmOptimizer
100 | :members:
101 |
102 |
--------------------------------------------------------------------------------
/doc/source/authors.rst:
--------------------------------------------------------------------------------
1 | .. include:: ../../AUTHORS.rst
--------------------------------------------------------------------------------
/doc/source/conf.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | #
3 | # CosmoHammer documentation build configuration file, created by
4 | # sphinx-quickstart on Fri Oct 12 13:39:48 2012.
5 | #
6 | # This file is execfile()d with the current directory set to its containing dir.
7 | #
8 | # Note that not all possible configuration values are present in this
9 | # autogenerated file.
10 | #
11 | # All configuration values have a default; values that are commented out
12 | # serve to show the default.
13 |
14 | import sys, os
15 |
16 | # If extensions (or modules to document with autodoc) are in another directory,
17 | # add these directories to sys.path here. If the directory is relative to the
18 | # documentation root, use os.path.abspath to make it absolute, like shown here.
19 | #sys.path.insert(0, os.path.abspath('../../cosmoHammer'))
20 | sys.path.insert(0, os.path.abspath('../..'))
21 | import cosmoHammer
22 | from cosmoHammer import __version__
23 |
24 |
25 | # -- General configuration -----------------------------------------------------
26 |
27 | # If your documentation needs a minimal Sphinx version, state it here.
28 | #needs_sphinx = '1.0'
29 |
30 | # Add any Sphinx extension module names here, as strings. They can be extensions
31 | # coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
32 | extensions = ['sphinx.ext.autodoc', 'sphinx.ext.coverage', 'sphinx.ext.mathjax', 'sphinx.ext.viewcode']
33 |
34 | # Add any paths that contain templates here, relative to this directory.
35 | templates_path = ['_templates']
36 |
37 | # The suffix of source filenames.
38 | source_suffix = '.rst'
39 |
40 | # The encoding of source files.
41 | #source_encoding = 'utf-8-sig'
42 |
43 | # The master toctree document.
44 | master_doc = 'index'
45 |
46 | # General information about the project.
47 | project = u'CosmoHammer'
48 | copyright = u'2014, Joel Akeret'
49 |
50 | # The version info for the project you're documenting, acts as replacement for
51 | # |version| and |release|, also used in various other places throughout the
52 | # built documents.
53 | #
54 | # The short X.Y version.
55 | version = __version__
56 | # The full version, including alpha/beta/rc tags.
57 | release = __version__
58 |
59 | # The language for content autogenerated by Sphinx. Refer to documentation
60 | # for a list of supported languages.
61 | #language = None
62 |
63 | # There are two options for replacing |today|: either, you set today to some
64 | # non-false value, then it is used:
65 | #today = ''
66 | # Else, today_fmt is used as the format for a strftime call.
67 | #today_fmt = '%B %d, %Y'
68 |
69 | # List of patterns, relative to source directory, that match files and
70 | # directories to ignore when looking for source files.
71 | exclude_patterns = []
72 |
73 | # The reST default role (used for this markup: `text`) to use for all documents.
74 | #default_role = None
75 |
76 | # If true, '()' will be appended to :func: etc. cross-reference text.
77 | #add_function_parentheses = True
78 |
79 | # If true, the current module name will be prepended to all description
80 | # unit titles (such as .. function::).
81 | #add_module_names = True
82 |
83 | # If true, sectionauthor and moduleauthor directives will be shown in the
84 | # output. They are ignored by default.
85 | #show_authors = False
86 |
87 | # The name of the Pygments (syntax highlighting) style to use.
88 | pygments_style = 'sphinx'
89 |
90 | # A list of ignored prefixes for module index sorting.
91 | #modindex_common_prefix = []
92 |
93 |
94 | # -- Options for HTML output ---------------------------------------------------
95 |
96 | # The theme to use for HTML and HTML Help pages. See the documentation for
97 | # a list of builtin themes.
98 | #html_theme = 'agogo'
99 |
100 | # Theme options are theme-specific and customize the look and feel of a theme
101 | # further. For a list of options available for each theme, see the
102 | # documentation.
103 | #html_theme_options = {
104 | # "headerbg": "#52ADE7",
105 | # "headercolor1": "#000000",
106 | # "headercolor2": "#52ADE7",
107 | # "linkcolor": "#000000",
108 | # "headerlinkcolor": "#000000",
109 | # "bodyfont": "sans-serif;"
110 | # }
111 |
112 | # Add any paths that contain custom themes here, relative to this directory.
113 | #html_theme_path = []
114 |
115 | # The name for this set of Sphinx documents. If None, it defaults to
116 | # " v documentation".
117 | #html_title = None
118 |
119 | # A shorter title for the navigation bar. Default is the same as html_title.
120 | #html_short_title = None
121 |
122 | # The name of an image file (relative to this directory) to place at the top
123 | # of the sidebar.
124 | #html_logo = None
125 |
126 | # The name of an image file (within the static path) to use as favicon of the
127 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
128 | # pixels large.
129 | #html_favicon = None
130 |
131 | # Add any paths that contain custom static files (such as style sheets) here,
132 | # relative to this directory. They are copied after the builtin static files,
133 | # so a file named "default.css" will overwrite the builtin "default.css".
134 | # html_static_path = ['_static']
135 |
136 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
137 | # using the given strftime format.
138 | #html_last_updated_fmt = '%b %d, %Y'
139 |
140 | # If true, SmartyPants will be used to convert quotes and dashes to
141 | # typographically correct entities.
142 | #html_use_smartypants = True
143 |
144 | # Custom sidebar templates, maps document names to template names.
145 | #html_sidebars = {}
146 |
147 | # Additional templates that should be rendered to pages, maps page names to
148 | # template names.
149 | #html_additional_pages = {}
150 |
151 | # If false, no module index is generated.
152 | #html_domain_indices = True
153 |
154 | # If false, no index is generated.
155 | #html_use_index = True
156 |
157 | # If true, the index is split into individual pages for each letter.
158 | #html_split_index = False
159 |
160 | # If true, links to the reST sources are added to the pages.
161 | #html_show_sourcelink = True
162 |
163 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
164 | #html_show_sphinx = True
165 |
166 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
167 | #html_show_copyright = True
168 |
169 | # If true, an OpenSearch description file will be output, and all pages will
170 | # contain a tag referring to it. The value of this option must be the
171 | # base URL from which the finished HTML is served.
172 | #html_use_opensearch = ''
173 |
174 | # This is the file name suffix for HTML files (e.g. ".xhtml").
175 | #html_file_suffix = None
176 |
177 | # Output file base name for HTML help builder.
178 | htmlhelp_basename = 'CosmoHammerdoc'
179 |
180 |
181 | # -- Options for LaTeX output --------------------------------------------------
182 |
183 | latex_elements = {
184 | # The paper size ('letterpaper' or 'a4paper').
185 | #'papersize': 'letterpaper',
186 |
187 | # The font size ('10pt', '11pt' or '12pt').
188 | #'pointsize': '10pt',
189 |
190 | # Additional stuff for the LaTeX preamble.
191 | #'preamble': '',
192 | }
193 |
194 | # Grouping the document tree into LaTeX files. List of tuples
195 | # (source start file, target name, title, author, documentclass [howto/manual]).
196 | latex_documents = [
197 | ('index', 'CosmoHammer.tex', u'CosmoHammer Documentation',
198 | u'Joel Akeret', 'manual'),
199 | ]
200 |
201 | # The name of an image file (relative to this directory) to place at the top of
202 | # the title page.
203 | #latex_logo = None
204 |
205 | # For "manual" documents, if this is true, then toplevel headings are parts,
206 | # not chapters.
207 | #latex_use_parts = False
208 |
209 | # If true, show page references after internal links.
210 | #latex_show_pagerefs = False
211 |
212 | # If true, show URL addresses after external links.
213 | #latex_show_urls = False
214 |
215 | # Documents to append as an appendix to all manuals.
216 | #latex_appendices = []
217 |
218 | # If false, no module index is generated.
219 | #latex_domain_indices = True
220 |
221 |
222 | # -- Options for manual page output --------------------------------------------
223 |
224 | # One entry per manual page. List of tuples
225 | # (source start file, name, description, authors, manual section).
226 | man_pages = [
227 | ('index', 'cosmohammer', u'CosmoHammer Documentation',
228 | [u'Joel Akeret'], 1)
229 | ]
230 |
231 | # If true, show URL addresses after external links.
232 | #man_show_urls = False
233 |
234 |
235 | # -- Options for Texinfo output ------------------------------------------------
236 |
237 | # Grouping the document tree into Texinfo files. List of tuples
238 | # (source start file, target name, title, author,
239 | # dir menu entry, description, category)
240 | texinfo_documents = [
241 | ('index', 'CosmoHammer', u'CosmoHammer Documentation',
242 | u'Joel Akeret', 'CosmoHammer', 'One line description of project.',
243 | 'Miscellaneous'),
244 | ]
245 |
246 | # Documents to append as an appendix to all manuals.
247 | #texinfo_appendices = []
248 |
249 | # If false, no module index is generated.
250 | #texinfo_domain_indices = True
251 |
252 | # How to display URL addresses: 'footnote', 'no', or 'inline'.
253 | #texinfo_show_urls = 'footnote'
254 | try:
255 | import sphinx_eth_theme
256 | html_theme = "sphinx_eth_theme"
257 | html_theme_path = [sphinx_eth_theme.get_html_theme_path()]
258 | except ImportError:
259 | html_theme = 'default'
--------------------------------------------------------------------------------
/doc/source/contributing.rst:
--------------------------------------------------------------------------------
1 | .. include:: ../../CONTRIBUTING.rst
--------------------------------------------------------------------------------
/doc/source/history.rst:
--------------------------------------------------------------------------------
1 | .. include:: ../../HISTORY.rst
--------------------------------------------------------------------------------
/doc/source/index.rst:
--------------------------------------------------------------------------------
1 | .. complexity documentation master file, created by
2 | sphinx-quickstart on Tue Jul 9 22:26:36 2013.
3 | You can adapt this file completely to your liking, but it should at least
4 | contain the root `toctree` directive.
5 |
6 | .. include:: ../../README.rst
7 |
8 | User Guide
9 | ----------
10 |
11 | .. toctree::
12 | :maxdepth: 2
13 |
14 | user/install
15 | user/usage
16 | user/benchmark
17 | user/pso
18 | user/parallelization
19 | user/HowToCosmoHammer
20 |
21 | API Documentation
22 | -----------------
23 |
24 | .. toctree::
25 | :maxdepth: 2
26 |
27 | api
28 |
29 |
30 | Contents:
31 | ---------
32 |
33 | .. toctree::
34 | :maxdepth: 2
35 |
36 | contributing
37 | authors
38 | history
39 |
40 |
41 |
42 | License
43 | -------
44 | CosmoHammer is free software: you can redistribute it and/or modify
45 | it under the terms of the GNU General Public License as published by
46 | the Free Software Foundation, either version 3 of the License, or
47 | (at your option) any later version.
48 |
49 | CosmoHammer is distributed in the hope that it will be useful,
50 | but WITHOUT ANY WARRANTY; without even the implied warranty of
51 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
52 | GNU General Public License for more details.
53 |
54 | You should have received a copy of the GNU General Public License
55 | along with CosmoHammer. If not, see .
56 |
--------------------------------------------------------------------------------
/doc/source/user/HowToCosmoHammer.rst:
--------------------------------------------------------------------------------
1 | .. _HowToCosmoHammer:
2 |
3 | How to...
4 | =========
5 |
6 | When using CosmoHammer for sampling your own likelihood, the central component is the LikelihoodComputationChain. As shown in the Figure, the LikelihoodComputationChain is invoked by the sampler at every position in the Monte Carlo Markov chain in order to compute the likelihood of the proposed position in parameter space. The chain itself has three components:
7 |
8 | .. image:: chscheme.jpg
9 | :alt: Visulalization of the CosmoHammer LikelihoodComputationChain scheme.
10 | :align: left
11 |
12 |
13 | - **Context**: The context is a dictionary for storing information created during the evaluation of the likelihood. It at least contains the parameter values of the current position proposed by the sampler.
14 |
15 | - **CoreModules**: The CoreModules can be used to calculate information which is needed for the evaluation of the likelihood. The information can then stored in the context.
16 |
17 | - **LikelihoodModules**: The LikelihoodModules use the information in the context to calculate the likelihood of the proposed position and return the log-likelihood to the chain.
18 |
19 | The LikelihoodComputationChain (a) first stores the proposed parameters in the context , then (b) moves on and invokes all available CoreModules before (c) calling the LikelihoodModules. The resulting log-likelihood values are gathered, summed, and returned to the sampler.
20 |
21 | In the following, CoreModule and LikelihoodModule are explained in more detail.
22 |
23 | write own CoreModules
24 | ---------------------
25 |
26 | The minimal CoreModule is a callable module that takes only the context as an argument and has a setup routine for doing expansive calculations that can be precomputed. For every result that is to be stored in the context, you need to come up with a unique key which allows the other modules to get the information from the context. An example for such a minimal CoreModule can be found in the ``DummyCoreModule.py`` file in the examples::
27 |
28 | class DummyCoreModule(object):
29 | """
30 | Dummy Core Module for calculating the squares of parameters.
31 | """
32 |
33 | def __init__(self):
34 | """
35 | Constructor of the DummyCoreModule
36 | """
37 | pass
38 |
39 | def __call__(self, ctx):
40 | """
41 | Computes something and stores it in the context
42 | """
43 | # Get the parameters from the context
44 | p = ctx.getParams()
45 |
46 | # Calculate something
47 | squares = p**2
48 | # Add the result to the context using a unique key
49 | ctx.add('squares_key', squares)
50 |
51 | # Store derived parameters for post processing
52 | derived_parms = sum(squares) % 2
53 | ctx.getData()["derived_params_key"] = derived_parms
54 |
55 | def setup(self):
56 | """
57 | Sets up the core module.
58 | Tasks that need to be executed once per run
59 | """
60 | #e.g. load data from files
61 |
62 | print("DummyCoreModule setup done")
63 |
64 | write own LikelihoodModules
65 | ---------------------------
66 |
67 | The minimal LikelihoodModule is a module with a computeLikelihood function that takes only the context as an argument and returns the likelihood and a setup routine for doing expansive calculations that can be precomputed. An example for such a minimal LikelihoodModule can be found in the ``DummyLikelihoodModule.py`` file in the examples.::
68 |
69 | class DummyLikelihoodModule(object):
70 | """
71 | Dummy object for calculating a likelihood
72 | """
73 |
74 | def __init__(self):
75 | """
76 | Constructor of the DummyLikelihoodModule
77 | """
78 | pass
79 |
80 | def computeLikelihood(self, ctx):
81 | """
82 | Computes the likelihood using information from the context
83 | """
84 | # Get information from the context. This can be results from a core
85 | # module or the parameters coming from the sampler
86 | squares = ctx.get('squares_key')
87 |
88 | # Calculate a likelihood up to normalization
89 | lnprob = -sum(squares)/2.0
90 |
91 | # Return the likelihood
92 | return lnprob
93 |
94 | def setup(self):
95 | """
96 | Sets up the likelihood module.
97 | Tasks that need to be executed once per run
98 | """
99 | #e.g. load data from files
100 |
101 | print("DummyLikelihoodModule setup done")
102 |
--------------------------------------------------------------------------------
/doc/source/user/benchmark.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cosmo-ethz/CosmoHammer/b6c65ccff7c3f83623264b7d57e05310755f761b/doc/source/user/benchmark.png
--------------------------------------------------------------------------------
/doc/source/user/benchmark.rst:
--------------------------------------------------------------------------------
1 | .. _benchmark:
2 |
3 | Benchmark
4 | ============
5 |
6 | Sampling the WMAP 7 year likelihood with CAMB required a large amount of computational power. We therefore decided to explore the possible benefits of cloud computing by means of CosmoHammer. One of the major advantages of this computing strategy is that the configuration of the cloud can be easily tailored to the problem at hand. In the cloud more computational power can be added within minutes by renting extra compute instances on demand, resulting in an optimised execution time.
7 |
8 | As cloud service provider we decided to use `Amazon EC2 `_. The high performance computing cluster consisted of one master node and several worker nodes. At the moment of the benchmarks one cc2.8xlarge Instance ships with 2 × Intel Xeon E5-2670, eight-core architecture with Hyper-Threading, resulting in 32 cores per node. We used a m1.large instance as master node mainly to benefit from the high I / O performance in order to reduce the loading time of the WMAP data.
9 |
10 | .. image:: benchmark.png
11 | :alt: Run time behaviour of CosmoHammer with changing number of cores using different parallelisation schemes.
12 | :align: right
13 |
14 | The results depicted in the figure have been realised with one to 64 worker nodes (32 - 2048 cores) and different combinations of processes and threads per node. The processes define the number of computations executed in parallel and the threads represent the number of cores used for one computation.
15 |
16 | As it can be seen CosmoHammer scales almost linearly with increasing number of computational cores. The best result was achieved using 64 nodes with 32 cores, four processes and eight threads. Using this configuration, the computation took about 16 Minutes.
17 |
--------------------------------------------------------------------------------
/doc/source/user/chscheme.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cosmo-ethz/CosmoHammer/b6c65ccff7c3f83623264b7d57e05310755f761b/doc/source/user/chscheme.jpg
--------------------------------------------------------------------------------
/doc/source/user/install.rst:
--------------------------------------------------------------------------------
1 | .. _install:
2 |
3 | Installation
4 | ============
5 |
6 | Since ``CosmoHammer`` is a pure Python module, it should be pretty easy to install.
7 |
8 | At the command line via pip::
9 |
10 | $ pip install cosmohammer
11 |
12 | This will install the package and all of the required dependencies.
13 |
14 | .. note:: If you wish to use `CosmoHammer` on a cluster with MPI you need to manually install `mpi4py `_.
15 |
16 | From source
17 | -----------
18 |
19 | Once you've downloaded and unpacked the source, you can navigate into the
20 | root source directory and run:
21 |
22 | ::
23 |
24 | $ python setup.py build
25 | $ python setup.py install --user
26 |
27 |
28 |
29 | You might need to run this using ``sudo`` depending on your Python
30 | installation.
31 |
32 | Cosmological parameters from CMB data
33 | ------------------------------------------------------------------------
34 |
35 | To estimate cosmological parameters you will need likelihood and core modules for CosmoHammer.
36 | See the cosmoHammerPlugins project `GitHub `_ for the modules publicly available at the moment.
37 |
--------------------------------------------------------------------------------
/doc/source/user/parallelisation.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/cosmo-ethz/CosmoHammer/b6c65ccff7c3f83623264b7d57e05310755f761b/doc/source/user/parallelisation.jpg
--------------------------------------------------------------------------------
/doc/source/user/parallelization.rst:
--------------------------------------------------------------------------------
1 | .. _parallelization:
2 |
3 | Parallelization
4 | ===============
5 |
6 | .. image:: parallelisation.jpg
7 | :alt: Run time behaviour of CosmoHammer with changing number of cores using different parallelisation schemes.
8 | :align: left
9 |
10 | ``CosmoHammer`` allows for parallelizing the evaluation of the likelihood from a single computer to a large scale computing environment like a compute cluster or a cloud infrastructure.
11 |
12 | In the simple case where ``CosmoHammer`` is executed on a single physical computer with one or multiple threads the parallelization is either solved thru `OpenMP `_ or the built in Python `multiprocessing `_. In the case of OpenMP the parallelization is done by executing multiple threads within a shared-memory machine. This is typically a use case when your likelihood code is written in C/C++ or FORTRAN like the theory prediction module `CAMB `_.
13 |
14 | With multiprocessing it is important to note that the module spawns a certain number of Python processes within a machine in order to execute the code in parallel. This causes some overhead during the parallelization process so that a performance gain is only achieved if the computations are resource demanding.
15 |
16 | In the non-trivial case where ``CosmoHammer`` should take advantage of a computation cluster with multiple physical nodes like a cloud or grid computer the parallelization is solved by using the Message Passing Interface (MPI/`mpi4py `_). This requires that mpi4py is `installed `_ on your system. Note, however, that this way of parallelisation is only beneficial when the executed computations are time and resource consuming. Distributing the workload in a compute cluster always implies the transfer of information over the network which is typically slower than transferring information between local processes by an order of magnitude. Therefore, the advantage of additional computing resources and the disadvantage of the network overhead have to be weighted.
17 |
18 | When using a compute cluster the nodes often come with a large number of computational cores. Writing code that fully benefits from such a large number of cores is usually difficult. Therefore, it makes sense to split the workload also on the node since using a smaller number of cores per computation while performing multiple computations in parallel is typically more efficient. In this case ``CosmoHammer`` helps you to combine the parallelization schemes mention above.
19 |
20 |
21 | Examples
22 | --------
23 |
24 | *Parallelization of* ``CosmoHammer`` *on a* **single machine** *with n cores.*
25 |
26 | 1) Using only Python multiprocessing:
27 | ::
28 | from cosmoHammer.CosmoHammerSampler import CosmoHammerSampler
29 | sampler = CosmoHammerSampler(params, likelihoodComputationChain, filePrefix,
30 | walkersRatio, burninIterations, sampleIterations, threadCount=n)
31 |
32 | 2) Using only OpenMP:
33 |
34 | ``$ export OMP_NUM_THREADS=n``
35 | ::
36 | from cosmoHammer.CosmoHammerSampler import CosmoHammerSampler
37 | sampler = CosmoHammerSampler(params, likelihoodComputationChain, filePrefix,
38 | walkersRatio, burninIterations, sampleIterations)
39 |
40 | 3) Using OpenMP and Python multiprocessing (choose the the number m of OpenMP threads and the number k of multiprocessing threads such that k*m = n):
41 |
42 | ``$ export OMP_NUM_THREADS=m``
43 | ::
44 | from cosmoHammer.CosmoHammerSampler import CosmoHammerSampler
45 | sampler = CosmoHammerSampler(params, likelihoodComputationChain, filePrefix,
46 | walkersRatio, burninIterations, sampleIterations, threadCount=k)
47 |
48 |
49 |
50 | *Parallelization of* ``CosmoHammer`` *on a* **cluster or cloud** *with N nodes and n cores per node. For distributing the workload between different nodes in the cluster, MPI has to be used. Run your python script with:*
51 |
52 | ``mpiexec -n $NUM ./