├── COPYING
├── COPYING.LESSER
├── README
├── project.clj
└── src
└── probabilistic_clojure
├── embedded
├── api.clj
├── choice_points.clj
├── demos.clj
├── fit_poly.clj
├── lda_demo.clj
├── sampling.clj
├── test_deps.clj
├── test_sampling.clj
└── tests.clj
├── monadic
├── api.clj
└── demos.clj
├── original
├── constraint-propagation.clj
├── demos.clj
├── metropolis_hastings.clj
└── scratch.clj
└── utils
├── finite_distributions.clj
├── sampling.clj
└── stuff.clj
/COPYING:
--------------------------------------------------------------------------------
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 |
--------------------------------------------------------------------------------
/COPYING.LESSER:
--------------------------------------------------------------------------------
1 | GNU LESSER 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 |
9 | This version of the GNU Lesser General Public License incorporates
10 | the terms and conditions of version 3 of the GNU General Public
11 | License, supplemented by the additional permissions listed below.
12 |
13 | 0. Additional Definitions.
14 |
15 | As used herein, "this License" refers to version 3 of the GNU Lesser
16 | General Public License, and the "GNU GPL" refers to version 3 of the GNU
17 | General Public License.
18 |
19 | "The Library" refers to a covered work governed by this License,
20 | other than an Application or a Combined Work as defined below.
21 |
22 | An "Application" is any work that makes use of an interface provided
23 | by the Library, but which is not otherwise based on the Library.
24 | Defining a subclass of a class defined by the Library is deemed a mode
25 | of using an interface provided by the Library.
26 |
27 | A "Combined Work" is a work produced by combining or linking an
28 | Application with the Library. The particular version of the Library
29 | with which the Combined Work was made is also called the "Linked
30 | Version".
31 |
32 | The "Minimal Corresponding Source" for a Combined Work means the
33 | Corresponding Source for the Combined Work, excluding any source code
34 | for portions of the Combined Work that, considered in isolation, are
35 | based on the Application, and not on the Linked Version.
36 |
37 | The "Corresponding Application Code" for a Combined Work means the
38 | object code and/or source code for the Application, including any data
39 | and utility programs needed for reproducing the Combined Work from the
40 | Application, but excluding the System Libraries of the Combined Work.
41 |
42 | 1. Exception to Section 3 of the GNU GPL.
43 |
44 | You may convey a covered work under sections 3 and 4 of this License
45 | without being bound by section 3 of the GNU GPL.
46 |
47 | 2. Conveying Modified Versions.
48 |
49 | If you modify a copy of the Library, and, in your modifications, a
50 | facility refers to a function or data to be supplied by an Application
51 | that uses the facility (other than as an argument passed when the
52 | facility is invoked), then you may convey a copy of the modified
53 | version:
54 |
55 | a) under this License, provided that you make a good faith effort to
56 | ensure that, in the event an Application does not supply the
57 | function or data, the facility still operates, and performs
58 | whatever part of its purpose remains meaningful, or
59 |
60 | b) under the GNU GPL, with none of the additional permissions of
61 | this License applicable to that copy.
62 |
63 | 3. Object Code Incorporating Material from Library Header Files.
64 |
65 | The object code form of an Application may incorporate material from
66 | a header file that is part of the Library. You may convey such object
67 | code under terms of your choice, provided that, if the incorporated
68 | material is not limited to numerical parameters, data structure
69 | layouts and accessors, or small macros, inline functions and templates
70 | (ten or fewer lines in length), you do both of the following:
71 |
72 | a) Give prominent notice with each copy of the object code that the
73 | Library is used in it and that the Library and its use are
74 | covered by this License.
75 |
76 | b) Accompany the object code with a copy of the GNU GPL and this license
77 | document.
78 |
79 | 4. Combined Works.
80 |
81 | You may convey a Combined Work under terms of your choice that,
82 | taken together, effectively do not restrict modification of the
83 | portions of the Library contained in the Combined Work and reverse
84 | engineering for debugging such modifications, if you also do each of
85 | the following:
86 |
87 | a) Give prominent notice with each copy of the Combined Work that
88 | the Library is used in it and that the Library and its use are
89 | covered by this License.
90 |
91 | b) Accompany the Combined Work with a copy of the GNU GPL and this license
92 | document.
93 |
94 | c) For a Combined Work that displays copyright notices during
95 | execution, include the copyright notice for the Library among
96 | these notices, as well as a reference directing the user to the
97 | copies of the GNU GPL and this license document.
98 |
99 | d) Do one of the following:
100 |
101 | 0) Convey the Minimal Corresponding Source under the terms of this
102 | License, and the Corresponding Application Code in a form
103 | suitable for, and under terms that permit, the user to
104 | recombine or relink the Application with a modified version of
105 | the Linked Version to produce a modified Combined Work, in the
106 | manner specified by section 6 of the GNU GPL for conveying
107 | Corresponding Source.
108 |
109 | 1) Use a suitable shared library mechanism for linking with the
110 | Library. A suitable mechanism is one that (a) uses at run time
111 | a copy of the Library already present on the user's computer
112 | system, and (b) will operate properly with a modified version
113 | of the Library that is interface-compatible with the Linked
114 | Version.
115 |
116 | e) Provide Installation Information, but only if you would otherwise
117 | be required to provide such information under section 6 of the
118 | GNU GPL, and only to the extent that such information is
119 | necessary to install and execute a modified version of the
120 | Combined Work produced by recombining or relinking the
121 | Application with a modified version of the Linked Version. (If
122 | you use option 4d0, the Installation Information must accompany
123 | the Minimal Corresponding Source and Corresponding Application
124 | Code. If you use option 4d1, you must provide the Installation
125 | Information in the manner specified by section 6 of the GNU GPL
126 | for conveying Corresponding Source.)
127 |
128 | 5. Combined Libraries.
129 |
130 | You may place library facilities that are a work based on the
131 | Library side by side in a single library together with other library
132 | facilities that are not Applications and are not covered by this
133 | License, and convey such a combined library under terms of your
134 | choice, if you do both of the following:
135 |
136 | a) Accompany the combined library with a copy of the same work based
137 | on the Library, uncombined with any other library facilities,
138 | conveyed under the terms of this License.
139 |
140 | b) Give prominent notice with the combined library that part of it
141 | is a work based on the Library, and explaining where to find the
142 | accompanying uncombined form of the same work.
143 |
144 | 6. Revised Versions of the GNU Lesser General Public License.
145 |
146 | The Free Software Foundation may publish revised and/or new versions
147 | of the GNU Lesser General Public License from time to time. Such new
148 | versions will be similar in spirit to the present version, but may
149 | differ in detail to address new problems or concerns.
150 |
151 | Each version is given a distinguishing version number. If the
152 | Library as you received it specifies that a certain numbered version
153 | of the GNU Lesser General Public License "or any later version"
154 | applies to it, you have the option of following the terms and
155 | conditions either of that published version or of any later version
156 | published by the Free Software Foundation. If the Library as you
157 | received it does not specify a version number of the GNU Lesser
158 | General Public License, you may choose any version of the GNU Lesser
159 | General Public License ever published by the Free Software Foundation.
160 |
161 | If the Library as you received it specifies that a proxy can decide
162 | whether future versions of the GNU Lesser General Public License shall
163 | apply, that proxy's public statement of acceptance of any version is
164 | permanent authorization for you to choose that version for the
165 | Library.
166 |
--------------------------------------------------------------------------------
/README:
--------------------------------------------------------------------------------
1 | This is an implementation of the probability monad. Inspired by the bher compiler of the MIT Scheme dialect Church (see http://projects.csail.mit.edu/church/wiki/Church) it uses Metropolis Hastings MCMC to sample from probabilistic programs.
2 |
3 | The file src/probabilistic_clojure/monadic/api.clj contains the basic API for using the library. In the same directory, the file demos.clj demonstrates how generative models can be implemented. It relies on incanter (available from incanter.org) for graphical output and probability distributions.
4 |
5 | For a quick start clone the repository, add the src directory (as well as incanter.jar) to your Java classpath and (use 'probabilistic-clojure.monadic.demos). Then run (test-mixture mixture-mem) to fit a Dirichlet mixture of Gaussian with three components to some test data.
6 |
7 | LICENSE
8 |
9 | This software is released under the LGPL. See COPYING.LESSER for details.
--------------------------------------------------------------------------------
/project.clj:
--------------------------------------------------------------------------------
1 | (defproject probnice "0.7.5"
2 | :description "Embedded probabilistic programming in Clojure."
3 | :url "https://github.com/bertschi/ProbClojureNice"
4 | :dependencies [[org.clojure/clojure "1.4.0"]
5 | [org.clojure/algo.monads "0.1.0"]
6 | [incanter "1.3.0-SNAPSHOT"]
7 | [org.apache.commons/commons-math "2.2"]]
8 | :plugins [[codox "0.6.1"]
9 | ;; [lein-swank "1.4.4"]])
10 | ;; [lein-ritz "0.5.0"]])
11 | [org.clojure/tools.nrepl "0.2.0-beta10"]])
12 |
13 |
--------------------------------------------------------------------------------
/src/probabilistic_clojure/embedded/api.clj:
--------------------------------------------------------------------------------
1 | ;;; Copyright (C) 2011 Nils Bertschinger
2 |
3 | ;;; This file is part of Probabilistic-Clojure
4 |
5 | ;;; Probabilistic-Clojure is free software: you can redistribute it and/or modify
6 | ;;; it under the terms of the GNU Lesser General Public License as published by
7 | ;;; the Free Software Foundation, either version 3 of the License, or
8 | ;;; (at your option) any later version.
9 |
10 | ;;; Probabilistic-Clojure is distributed in the hope that it will be useful,
11 | ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | ;;; GNU Lesser General Public License for more details.
14 |
15 | ;;; You should have received a copy of the GNU Lesser General Public License
16 | ;;; along with Probabilistic-Clojure. If not, see .
17 |
18 | (ns
19 | ^{:author "Nils Bertschinger"
20 | :doc "This library implements probabilistic programming for Clojure.
21 | The program is considered as a network of probabilistic (and deterministic)
22 | choice points as specified by the user. Metropolis Hastings sampling is then
23 | used to obtain samples from the probability distribution corresponding to
24 | the probabilistic program.
25 | The system allows to condition and memoize probabilistic choice points and
26 | can be extended by user defined distributions."}
27 | probabilistic-clojure.embedded.api
28 | (:use [clojure.set :only (union difference intersection)])
29 | (:use [probabilistic-clojure.utils.sampling :only (sample-from normalize random-selection random-selection-alias)]
30 | [probabilistic-clojure.utils.stuff :only (ensure-list error)]))
31 |
32 | (in-ns 'probabilistic-clojure.embedded.api)
33 |
34 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
35 | ;;;
36 | ;;; Basic data structures for the global store and choice points
37 | ;;;
38 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
39 |
40 | (defrecord State
41 | [choice-points recomputed newly-created possibly-removed failed?])
42 |
43 | (defn fresh-state
44 | "Returns a fresh global store containing the given choice points.
45 | The sets of recomputed, newly-created and possibly-removed choice points
46 | are all initially empty and failed? is false."
47 | [choice-points]
48 | (State. choice-points #{} #{} #{} false))
49 |
50 | (def ^:dynamic *global-store*
51 | (atom (fresh-state {})))
52 |
53 | (defmacro with-fresh-store
54 | "Creates a fresh binding for the global store and evaluates the body in this context."
55 | [choice-points & body]
56 | `(binding [*global-store* (atom (fresh-state ~choice-points))]
57 | ~@body))
58 |
59 | (defn reset-store! []
60 | (swap! *global-store* (constantly (fresh-state {}))))
61 |
62 | (defmacro update-in-store!
63 | "Syntax like update-in, but updates the global store as a side effect.
64 | The global store should not be accessed directly, but only through this and
65 | the related macros assoc-in-store! and fetch-store. This way the representation
66 | of the global store could be changed with minimum effort."
67 | [[& keys] update-fn & args]
68 | `(swap! ~'*global-store*
69 | update-in ~(vec keys) ~update-fn ~@args))
70 |
71 | (defmacro assoc-in-store!
72 | "Assoc-in for the global store of choice points. See also update-in-store!."
73 | [[& keys] new-val]
74 | `(swap! ~'*global-store*
75 | assoc-in ~(vec keys) ~new-val))
76 |
77 | (defmacro fetch-store
78 | "Macro for reading from the global store. The syntax resembles the chaining macro ->, i.e.
79 | each key-form gets an automatic first argument inserted."
80 | [& key-forms]
81 | `(-> (deref ~'*global-store*) ~@key-forms))
82 |
83 | ;;; choice points are maps with the following keys:
84 | ;;; name type recomputed recreate body dependents depends-on
85 | ;;;
86 | ;;; probabilistic choice points have additional keys:
87 | ;;; value log-lik sampler calc-log-lik proposer conditioned?
88 |
89 | (def no-value ::unbound)
90 |
91 | (defn make-choice-point
92 | "Create a new choice point with an unbound value and no dependencies."
93 | [name type whole body]
94 | {:name name :type type :recomputed no-value
95 | :whole whole :body body
96 | :dependents #{} :depends-on #{}})
97 |
98 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
99 | ;;;
100 | ;;; Stuff to name choice points
101 | ;;;
102 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
103 |
104 | (def ^:dynamic *call-stack* (list))
105 |
106 | (defn current-caller
107 | "Returns the name of the choice point which is currently active or nil if no caller is active."
108 | []
109 | (when (seq *call-stack*)
110 | (first *call-stack*)))
111 |
112 | ;;; TODO: change this s.t. addr can be generated automatically [(with-tag ...) for local name change]
113 |
114 | (def ^:dynamic *addr* (list))
115 |
116 | (defn make-addr [tag]
117 | (cons tag *addr*))
118 |
119 | (defmacro within [name & body]
120 | `(binding [*addr* ~name
121 | *call-stack* (cons ~name *call-stack*)]
122 | ~@body))
123 |
124 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
125 | ;;;
126 | ;;; Tracking dependencies between choice points
127 | ;;;
128 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
129 |
130 | (defn update-dependencies
131 | "Registers a new dependency between the choice point with the given name and the current caller."
132 | [cp-name]
133 | (let [caller-name (current-caller)]
134 | (when caller-name
135 | (update-in-store! [:choice-points caller-name :depends-on]
136 | conj cp-name)
137 | (update-in-store! [:choice-points cp-name :dependents]
138 | conj caller-name))))
139 |
140 | (defn retract-dependent
141 | "Register that the choice point cp-name no longer depends on dependent-name.
142 | If cp-name has no dependents left afterwards it is tagged for possible removal."
143 | [cp-name dependent-name]
144 | (assert (contains? (fetch-store :choice-points (get cp-name) :dependents) dependent-name))
145 | (update-in-store! [:choice-points cp-name :dependents]
146 | disj dependent-name)
147 | (when (empty? (fetch-store :choice-points (get cp-name) :dependents))
148 | (update-in-store! [:possibly-removed]
149 | conj cp-name)))
150 |
151 | (defn recompute-value
152 | "Recompute the value of the given choice point. Updates the dependencies for the new
153 | value and registers the choice point as recomputed."
154 | [cp]
155 | (let [name (:name cp)]
156 | (update-in-store! [:recomputed] conj name)
157 | (within name
158 | (let [depended-on (fetch-store :choice-points (get name) :depends-on)]
159 | (assoc-in-store! [:choice-points name :depends-on] #{})
160 | (let [val ((:body cp))]
161 | (doseq [used (difference depended-on
162 | (fetch-store :choice-points (get name) :depends-on))]
163 | (retract-dependent used name))
164 | (assoc-in-store! [:choice-points name :recomputed] val)
165 | val)))))
166 |
167 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
168 | ;;;
169 | ;;; Deterministic choice points
170 | ;;;
171 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
172 |
173 | (defn make-det-cp
174 | "Create a new determinstic choice point."
175 | [name whole body]
176 | (make-choice-point name ::deterministic whole body))
177 |
178 | (defn det-cp-fn
179 | "This function gets called if a determinstic choice point is evaluated.
180 | When the choice point is not already in the global store it is initialized,
181 | its value is computed and the new choice point is returned.
182 | Otherwise it is simply fetched from the store.
183 | This function should not be called directly, but only in the context of det-cp."
184 | [name whole-fn body-fn]
185 | (if (contains? (fetch-store :choice-points) name)
186 | ((fetch-store :choice-points) name)
187 | (let [det-cp (make-det-cp name whole-fn body-fn)]
188 | (update-in-store! [:newly-created]
189 | conj name)
190 | (assoc-in-store! [:choice-points name]
191 | det-cp)
192 | (recompute-value det-cp)
193 | (fetch-store :choice-points (get name)))))
194 |
195 | (defmacro det-cp
196 | "Establishes a deterministic choice point with the given name tag for the code in the body."
197 | [tag & body]
198 | `(let [addr# *addr*
199 | name# (make-addr ~tag)
200 | body-fn# (fn [] ~@body)
201 | whole-fn# (atom nil)]
202 | (swap! whole-fn#
203 | (constantly
204 | (fn []
205 | (det-cp-fn name# @whole-fn# body-fn#))))
206 | (det-cp-fn name# @whole-fn# body-fn#)))
207 |
208 | (defmulti gv
209 | "Accesses the value of a choice point. When used in the body of another choice
210 | point this creates a dependency between those choice points."
211 | :type)
212 |
213 | (defmethod gv ::deterministic
214 | ;; Accesses the value of a deterministic choice point.
215 | ;; Takes care of dependencies and creates the choice point if necessary.
216 | [det-cp]
217 | (let [name (:name det-cp)]
218 | (if (contains? (fetch-store :choice-points) name)
219 | (let [val (fetch-store :choice-points (get name) :recomputed)]
220 | (update-dependencies name)
221 | val)
222 | ;; the choice point is not in the trace, thus we have to recreate it first
223 | (gv ((:whole det-cp))))))
224 |
225 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
226 | ;;;
227 | ;;; Probabilistic choice points
228 | ;;;
229 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
230 |
231 | (defn sample
232 | "Sample a new value for prob-cp."
233 | [prob-cp]
234 | (apply (:sampler prob-cp) (:recomputed prob-cp)))
235 |
236 | (defn calc-log-lik
237 | "Calculate the probability of x given the current parameters of prob-cp."
238 | [prob-cp x]
239 | (apply (:calc-log-lik prob-cp) x (:recomputed prob-cp)))
240 |
241 | (defn propose
242 | "Propose a new value new-x for prob-cp given that the current value is old-x.
243 | Returns three values [new-x q(new-x | old-x) q(old-x | new-x)] where q(.|.) denotes the
244 | proposal distribution."
245 | [prob-cp old-x]
246 | (apply (:proposer prob-cp) old-x (:recomputed prob-cp)))
247 |
248 | (defn make-prob-cp
249 | "Creates a new probabilistic choice point."
250 | [name whole body sampler calc-log-lik proposer]
251 | (merge (make-choice-point name ::probabilistic whole body)
252 | {:value no-value :log-lik 0 :sampler sampler :calc-log-lik calc-log-lik
253 | :proposer proposer :conditioned? false}))
254 |
255 | (defn update-log-lik
256 | "Update the probability for the given probabilistic choice point."
257 | [prob-cp-name]
258 | (let [prob-cp (fetch-store :choice-points (get prob-cp-name))]
259 | (assoc-in-store!
260 | [:choice-points prob-cp-name :log-lik]
261 | (calc-log-lik prob-cp (:value prob-cp)))))
262 |
263 | (defn prob-cp-fn
264 | "As det-cp-fn, but for probabilistic choice points."
265 | [name whole-fn body-fn dist]
266 | (if (contains? (fetch-store :choice-points) name)
267 | ((fetch-store :choice-points) name)
268 | (let [prob-cp (make-prob-cp name whole-fn body-fn
269 | (:sampler dist)
270 | (:calc-log-lik dist)
271 | (:proposer dist))]
272 | (update-in-store! [:newly-created]
273 | conj name)
274 | (assoc-in-store! [:choice-points name]
275 | prob-cp)
276 | (recompute-value prob-cp)
277 | (let [params (fetch-store :choice-points (get name) :recomputed)]
278 | (assoc-in-store! [:choice-points name :value]
279 | (sample (fetch-store :choice-points (get name))))
280 | (update-log-lik name)
281 | (fetch-store :choice-points (get name))))))
282 |
283 | (defn create-dist-map
284 | "Helper functions for def-prob-cp."
285 | [params dist-spec]
286 | (when-not (vector? params)
287 | (error "Provided parameters " params " are not a vector."))
288 | (let [keys #{:sampler :calc-log-lik :proposer}
289 | find-spec-for (fn [key]
290 | (let [spec-form (rest (drop-while #(not (= % key)) dist-spec))]
291 | (when (empty? spec-form)
292 | (error "You must provide an implementation for " key))
293 | (take-while (complement keys) spec-form)))]
294 | (-> {}
295 | (assoc :sampler
296 | (let [[args & body] (find-spec-for :sampler)]
297 | (when-not (vector? args)
298 | (error args " is not a parameter vector as required by ::sampler option"))
299 | `(fn ~(vec (concat args params)) ~@body)))
300 | (assoc :calc-log-lik
301 | (let [[args & body] (find-spec-for :calc-log-lik)]
302 | (when-not (vector? args)
303 | (error args " is not a parameter vector as required by ::calc-log-lik option"))
304 | `(fn ~(vec (concat args params)) ~@body)))
305 | (assoc :proposer
306 | (let [[args & body] (find-spec-for :proposer)]
307 | (when-not (vector? args)
308 | (error args " is not a parameter vector as required by ::proposer option"))
309 | `(fn ~(vec (concat args params)) ~@body))))))
310 |
311 | (defmacro def-prob-cp
312 | "Macro to define probabilistic choice points.
313 | Each choice point has a name and parameters. Furthermore, it must specify
314 | functions :sampler, :calc-log-lik and :proposer. See the source of flip-cp
315 | for an example."
316 | [name [& params] & dist-spec]
317 | (let [dist-map (create-dist-map (vec params) dist-spec)
318 | tag (gensym "tag")]
319 | `(defmacro ~name [~tag ~@params]
320 | `(let [~'addr# *addr*
321 | ~'tag-name# (make-addr ~~tag)
322 | ~'body-fn# (fn [] (list ~~@params))
323 | ~'whole-fn# (atom nil)]
324 | (swap! ~'whole-fn#
325 | (constantly
326 | (fn []
327 | (prob-cp-fn ~'tag-name# @~'whole-fn# ~'body-fn# ~'~dist-map))))
328 | (prob-cp-fn ~'tag-name# @~'whole-fn# ~'body-fn# ~'~dist-map)))))
329 |
330 | (defmethod gv ::probabilistic
331 | ;; Accesses the value of a probabilistic choice point
332 | [prob-cp]
333 | (let [name (:name prob-cp)]
334 | (if (contains? (fetch-store :choice-points) name)
335 | (let [val (fetch-store :choice-points (get name) :value)]
336 | (update-dependencies name)
337 | val)
338 | ;; the choice point is not in the trace, thus we have to recreate it first
339 | (gv ((:whole prob-cp))))))
340 |
341 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
342 | ;;;
343 | ;;; Metropolis Hastings sampling
344 | ;;;
345 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
346 |
347 | ;;; Traces failures
348 |
349 | (defn trace-failure
350 | "Tags the current trace as failed. Used to implement rejection sampling."
351 | []
352 | (assoc-in-store! [:failed?] true))
353 |
354 | (defn trace-failed? []
355 | (fetch-store :failed?))
356 |
357 | ;;; Sampling routines
358 |
359 | (defn find-valid-trace
360 | "Returns a valid trace for the probabilistic program given as a no-arg function prob-chunk."
361 | [prob-chunk]
362 | (let [result (with-fresh-store {}
363 | (let [cp (prob-chunk)]
364 | (when-not (trace-failed?)
365 | [cp (fetch-store :choice-points)])))]
366 | (if result
367 | result
368 | (recur prob-chunk))))
369 |
370 | (defn cp-value
371 | "Returns the value of the choice point cp within the trace choice points."
372 | [cp choice-points]
373 | (if (= (:type cp) ::deterministic)
374 | (:recomputed (get choice-points (:name cp)))
375 | (:value (get choice-points (:name cp)))))
376 |
377 | (defn monte-carlo-sampling
378 | "Simple Monte-Carlo sampling scheme which runs the whole probabilistic program
379 | over and over again. Returns a lazy sequence of the obtained outcomes.
380 | Rejections are not included in the output, so it may take a long time if the
381 | rejection rate is high."
382 | [prob-chunk]
383 | (repeatedly (fn [] (let [[cp choice-points] (find-valid-trace prob-chunk)]
384 | (cp-value cp choice-points)))))
385 |
386 | ;;; utility functions for sampling
387 |
388 | (defn total-log-lik
389 | "Returns the total sum of the log. probabilities of all requested choice points
390 | in the given trace.
391 | Choice points not in the trace are allowed and contribute zero log. probability."
392 | [cp-names choice-points]
393 | (reduce + 0 (map (fn [cp-name]
394 | (let [cp (choice-points cp-name)]
395 | (case (:type cp)
396 | ::probabilistic (:log-lik cp)
397 | ::deterministic 0
398 | 0)))
399 | cp-names)))
400 |
401 | (defn remove-uncalled-choices
402 | "Remove all choice points from the global store which have not been called.
403 | Starts from the choice points registered for possible removal and recursively
404 | retracts further dependents.
405 | Returns a set of the names of the removed choice points."
406 | []
407 | (loop [candidate-names (seq (fetch-store :possibly-removed))
408 | result []]
409 | (if (empty? candidate-names)
410 | (set result)
411 | (let [candidate (fetch-store :choice-points (get (first candidate-names)))]
412 | (if (empty? (:dependents candidate))
413 | (let [candidate-name (:name candidate)]
414 | (update-in-store! [:choice-points]
415 | dissoc candidate-name)
416 | (doseq [cp-name (:depends-on candidate)]
417 | (retract-dependent cp-name candidate-name))
418 | (recur (concat (rest candidate-names)
419 | (:depends-on candidate))
420 | (conj result candidate-name)))
421 | (recur (rest candidate-names) result))))))
422 |
423 | ;; THIS DOES NOT WORK ... replaced by straight forward propagation
424 | ;; with potential duplicate recomputations!
425 |
426 | ;; ;; Version using depth-first traversal to obtain topological ordering
427 | ;; ;; of all choice points which have to updated if cp-name is changed
428 | ;; (defn ordered-dependencies
429 | ;; "Return all direct and indirect dependents of cp-name in an order suitable for updating, i.e.
430 | ;; each choice point occurs before any of its dependents in this sequence (topologically sorted)."
431 | ;; [cp-name choice-points]
432 | ;; (let [visited (atom #{})
433 | ;; ordered-deps (atom [])
434 | ;; dfs-path (atom #{})
435 | ;; back-edge? (fn [cp-name] (@dfs-path cp-name))]
436 | ;; (letfn [(dfs-traverse [current-cp-name propagate?]
437 | ;; (swap! visited conj current-cp-name)
438 | ;; (swap! dfs-path conj current-cp-name)
439 | ;; (let [current-cp (choice-points current-cp-name)
440 | ;; direct-deps (if (or propagate? (= (:type current-cp) ::deterministic))
441 | ;; (:dependents current-cp)
442 | ;; #{})]
443 | ;; (doseq [dep-cp-name direct-deps]
444 | ;; (when (back-edge? dep-cp-name)
445 | ;; (error "Cyclic dependencies between " current-cp-name
446 | ;; " and " dep-cp-name " detected!"))
447 | ;; (when-not (@visited dep-cp-name)
448 | ;; (dfs-traverse dep-cp-name false)))
449 | ;; (swap! dfs-path disj current-cp-name)
450 | ;; (swap! ordered-deps (fn [deps] (cons current-cp-name deps)))))]
451 | ;; (dfs-traverse cp-name true)
452 | ;; @ordered-deps)))
453 |
454 | (defn propagate-change-to
455 | "Propagate a change, starting with the given choice points."
456 | [cp-names]
457 | (loop [cpns (into clojure.lang.PersistentQueue/EMPTY cp-names) ; (seq cp-names)
458 | update-count 0]
459 | (if-not (empty? cpns)
460 | (let [cp-name (peek cpns) ; (first cpns)
461 | more-cps (pop cpns) ; (rest cpns) ;
462 | cp (fetch-store :choice-points (get cp-name))
463 | old-val (:recomputed cp)]
464 | ;; (println cp-name ": " (count cp-names)) (Thread/sleep 10)
465 | (recompute-value cp)
466 | (when (= (:type cp) ::probabilistic)
467 | (update-log-lik (:name cp)))
468 | (let [cp (fetch-store :choice-points (get cp-name)) ; re-read to see changes
469 | direct-deps (if (or (= (:type cp) ::probabilistic)
470 | (= old-val (:recomputed cp)))
471 | ;; no propagation beyond prob. and unchanged choice points
472 | []
473 | (:dependents cp))]
474 | ;; this implements (depth-first) breadth-first (with PersistentQueue)
475 | ;; traversal and potentially re-registers cp for update ...
476 | ;; ensures valid data after the propagation completes
477 | ;; (recur (concat direct-deps more-cps) (inc update-count))))
478 | (recur (into more-cps direct-deps) (inc update-count))))
479 | update-count)))
480 |
481 | ;; (defn propagate-change-to
482 | ;; "Propagate a change by recomputing all the given choice points in order."
483 | ;; [cp-names]
484 | ;; (doseq [dep-cp-name cp-names]
485 | ;; (let [dep-cp (fetch-store :choice-points (get dep-cp-name))]
486 | ;; (recompute-value dep-cp)
487 | ;; (when (= (:type dep-cp) ::probabilistic)
488 | ;; (update-log-lik (:name dep-cp))))))
489 |
490 | ;;; Conditioning and memoization
491 |
492 | (defn cond-data [prob-cp cond-val]
493 | (let [name (:name prob-cp)
494 | val (gv prob-cp)]
495 | (if (fetch-store :choice-points (get name) :conditioned?)
496 | (do (when-not (= cond-val val)
497 | (error name " is already conditioned on value " val
498 | " and cannot be changed to " cond-val))
499 | cond-val)
500 | (do
501 | (assoc-in-store! [:choice-points name :value]
502 | cond-val)
503 | (assoc-in-store! [:choice-points name :conditioned?]
504 | true)
505 | (update-log-lik name)
506 | (propagate-change-to (:dependents prob-cp))
507 | cond-val))))
508 |
509 | (defmacro memo [tag cp-form & memo-args]
510 | `(det-cp ~tag
511 | (binding [*addr* (list ~@(rest cp-form) ~@memo-args)]
512 | (gv ~cp-form))))
513 |
514 | ;;; Finally the Metropolis Hastings sampling
515 | ;;; This combines the previous attempts for changing and fixed topologies.
516 | ;;; In case the topology remains unchanged the more efficient method is used.
517 |
518 | ;; Does not work so easily since for log. lik. computations we still need to track which
519 | ;; choice points are active and which are not!!!
520 | ;; (def ^:dynamic *remove-uncalled*
521 | ;; "Should uncalled choices be removed?"
522 | ;; true)
523 |
524 | ;; Idea for speedup: Use un-normalized selection distribution and do not recompute it
525 | ;; completely, but just update the changed choice points
526 |
527 | (defrecord UDist [weights total])
528 |
529 | (defn prob-choice?
530 | "Returns true if cp is an un-conditioned probabilistic choice point."
531 | [cp]
532 | (and (= (:type cp) ::probabilistic)
533 | (not (:conditioned? cp))))
534 |
535 | (defn count-all-dependents
536 | "Returns the number of all direct and indirect dependents of the given choice point."
537 | [cp-name choice-points]
538 | (let [visited (atom #{})
539 | counter (atom 0)]
540 | (letfn [(dfs-traverse [current-cp-name]
541 | (swap! visited conj current-cp-name)
542 | (swap! counter inc)
543 | (let [current-cp (choice-points current-cp-name)
544 | direct-deps (:dependents current-cp)]
545 | (doseq [dep-cp-name direct-deps]
546 | (when-not (@visited dep-cp-name)
547 | (dfs-traverse dep-cp-name)))))]
548 | (dfs-traverse cp-name)
549 | @counter)))
550 |
551 | (defn cp-weight [cp-name choice-points]
552 | (Math/sqrt (count-all-dependents cp-name choice-points)))
553 |
554 | (defn prob-choice-dist
555 | "Return an un-normalized distribution for randomly choosing a choice point from the given trace.
556 | Implements the heuristic to prefer choice points with many dependents."
557 | [choice-points]
558 | (let [weights (into {}
559 | (for [[name cp] choice-points
560 | :when (prob-choice? cp)]
561 | [name (cp-weight name choice-points)]))]
562 | (UDist. weights (reduce + (vals weights)))))
563 |
564 | (defn add-to-prob-choice-dist [dist cp-names choice-points]
565 | (let [[new-weights new-total]
566 | (reduce (fn [[weights total] cp-name]
567 | (let [cp (choice-points cp-name)]
568 | (if (prob-choice? cp)
569 | (let [w (cp-weight cp-name choice-points)]
570 | (assert (not (contains? cp-name weights)))
571 | [(merge weights {cp-name w}) (+ total w)])
572 | [weights total])))
573 | [(:weights dist) (:total dist)]
574 | cp-names)]
575 | (UDist. new-weights new-total)))
576 |
577 | (defn remove-from-prob-choice-dist [dist cp-names]
578 | (let [[new-weights new-total]
579 | (reduce (fn [[weights total] cp-name]
580 | (if (contains? weights cp-name) ;; fails for non prob-choices
581 | (let [w (weights cp-name)]
582 | [(dissoc weights cp-name) (- total w)])
583 | [weights total]))
584 | [(:weights dist) (:total dist)]
585 | cp-names)]
586 | (UDist. new-weights new-total)))
587 |
588 | (defn prob [dist cp-name]
589 | (/ ((:weights dist) cp-name) (:total dist)))
590 |
591 | (defn set-proposed-val! [cp-name prop-val]
592 | (assoc-in-store! [:choice-points cp-name :value]
593 | prop-val)
594 | (update-in-store! [:recomputed] conj cp-name)
595 | (update-log-lik cp-name))
596 |
597 | (defn metropolis-hastings-step [choice-points selected selection-dist]
598 | (with-fresh-store choice-points
599 | (let [selected-cp (choice-points selected)
600 |
601 | [prop-val fwd-log-lik bwd-log-lik]
602 | (propose selected-cp (:value selected-cp))]
603 | ;; Propose a new value for the selected choice point and propagate change to dependents
604 | (set-proposed-val! (:name selected-cp) prop-val)
605 | (let [updates (propagate-change-to (:dependents selected-cp))]
606 | ;; (println "Proposed " (:name selected-cp) " for " updates " updates ("
607 | ;; (count-all-dependents (:name selected-cp) choice-points) " dependents)"))
608 | )
609 |
610 | (if (trace-failed?)
611 | [choice-points ::rejected true selection-dist]
612 | (let [removed-cps (remove-uncalled-choices)
613 | same-topology (and (empty? (fetch-store :newly-created))
614 | (empty? removed-cps))
615 | ;; Here we have the following invariants:
616 | ;; * (assert (empty? (clojure.set/intersection removed-cps (fetch-store :newly-created))))
617 | ;; * (let [new (set (keys (fetch-store :choice-points)))
618 | ;; old (set (keys choice-points))]
619 | ;; (assert (and (= new (difference (union old (fetch-store :newly-created))
620 | ;; removed-cps))
621 | ;; (= old (difference (union new removed-cps) (fetch-store :newly-created))))))
622 |
623 | ;; Overall the recomputed and removed-cps were touched during the update
624 | ;; Thus, we have to calculate the total probability contributed to the old
625 | ;; as well as the new traces.
626 | touched-cps (union (fetch-store :recomputed) removed-cps)
627 | trace-log-lik (total-log-lik touched-cps choice-points)
628 | prop-trace-log-lik (total-log-lik touched-cps (fetch-store :choice-points))
629 |
630 | ;; The forward and backward probabilities now account for the newly-created
631 | ;; and removed choice points
632 | fwd-trace-log-lik (total-log-lik (fetch-store :newly-created) (fetch-store :choice-points))
633 | bwd-trace-log-lik (total-log-lik removed-cps choice-points)
634 |
635 | prop-selection-dist (if same-topology
636 | selection-dist
637 | ;; (prob-choice-dist (fetch-store :choice-points)))]
638 | (-> selection-dist
639 | (add-to-prob-choice-dist (fetch-store :newly-created)
640 | (fetch-store :choice-points))
641 | (remove-from-prob-choice-dist removed-cps)))]
642 | ;; Randomly accept the new proposal according to the Metropolis Hastings formula
643 | (if (< (Math/log (rand))
644 | (+ (- prop-trace-log-lik trace-log-lik)
645 | (- (Math/log (prob prop-selection-dist (:name selected-cp)))
646 | (Math/log (prob selection-dist (:name selected-cp))))
647 | (- bwd-trace-log-lik fwd-trace-log-lik)
648 | (- bwd-log-lik fwd-log-lik)))
649 | [(fetch-store :choice-points) ::accepted same-topology prop-selection-dist]
650 | [choice-points ::rejected true selection-dist]))))))
651 |
652 | (def ^:dynamic *info-steps*
653 | "Display some status information every *info-steps* many samples"
654 | 500)
655 |
656 | (def ^:dynamic *selection-dist-steps*
657 | "Force a refresh of the selection distribution after that many steps.
658 | Anytime the topology has changed it is recomputed anyways."
659 | 25000)
660 |
661 | (def ^:dynamic *alias-sampling* true)
662 |
663 | (defn new-update-sequence [dist]
664 | (let [total (:total dist)
665 | pdist (into {} (for [[name weight] (:weights dist)]
666 | [name (/ weight total)]))]
667 | (if *alias-sampling*
668 | (random-selection-alias *selection-dist-steps* pdist)
669 | (random-selection *selection-dist-steps* pdist))))
670 |
671 | (defn metropolis-hastings-sampling [prob-chunk]
672 | (println "Trying to find a valid trace ...")
673 | (let [[cp choice-points] (find-valid-trace prob-chunk)]
674 | (println "Started sampling")
675 | (letfn [(samples [choice-points idx num-accepted num-top-changed update-seq selection-dist]
676 | (lazy-seq
677 | (let [update-seq (or (seq update-seq)
678 | (new-update-sequence (prob-choice-dist choice-points)))
679 | val (cp-value cp choice-points)
680 |
681 | [next-choice-points status same-topology next-selection-dist]
682 | (metropolis-hastings-step choice-points (first update-seq) selection-dist)
683 |
684 | output-info (= (mod idx *info-steps*) 0)]
685 | (when output-info
686 | (println idx ": " val)
687 | (println "Log. lik.: " (total-log-lik (keys choice-points) choice-points))
688 | (println "Accepted " num-accepted " out of last " *info-steps* " samples.")
689 | (println "Topology changed on " num-top-changed " samples."))
690 | (cons val
691 | (samples next-choice-points
692 | (inc idx)
693 | (cond output-info 0
694 | (= status ::accepted) (inc num-accepted)
695 | :else num-accepted)
696 | (cond output-info 0
697 | (not same-topology) (inc num-top-changed)
698 | :else num-top-changed)
699 | (if same-topology
700 | (rest update-seq)
701 | (new-update-sequence next-selection-dist))
702 | next-selection-dist)))))]
703 | (let [selection-dist (prob-choice-dist choice-points)]
704 | (samples choice-points 0 0 0 (new-update-sequence selection-dist) selection-dist)))))
705 |
--------------------------------------------------------------------------------
/src/probabilistic_clojure/embedded/choice_points.clj:
--------------------------------------------------------------------------------
1 | ;;; Copyright (C) 2011 Nils Bertschinger
2 |
3 | ;;; This file is part of Probabilistic-Clojure
4 |
5 | ;;; Probabilistic-Clojure is free software: you can redistribute it and/or modify
6 | ;;; it under the terms of the GNU Lesser General Public License as published by
7 | ;;; the Free Software Foundation, either version 3 of the License, or
8 | ;;; (at your option) any later version.
9 |
10 | ;;; Probabilistic-Clojure is distributed in the hope that it will be useful,
11 | ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | ;;; GNU Lesser General Public License for more details.
14 |
15 | ;;; You should have received a copy of the GNU Lesser General Public License
16 | ;;; along with Probabilistic-Clojure. If not, see .
17 |
18 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
19 | ;;;; Probabilistic programming using constraint propagation
20 | ;;;; to efficiently track dependencies between choice points
21 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
22 |
23 | (ns
24 | ^{:author "Nils Bertschinger"
25 | :doc "Part of probabilistic-clojure.embedded which implements a couple
26 | of probabilistic choice points."}
27 | probabilistic-clojure.embedded.choice-points
28 | (:use [probabilistic-clojure.embedded.api :only (def-prob-cp det-cp gv memo)]
29 | [probabilistic-clojure.utils.stuff :only (ensure-list error)])
30 | ;; (:require [incanter.stats :as stat]) ; This does not work inside macros!!!
31 | (:import org.apache.commons.math.special.Gamma))
32 | ;; (:import cern.jet.stat.tdouble.Gamma))
33 |
34 | (in-ns 'probabilistic-clojure.embedded.choice-points)
35 |
36 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
37 | ;;;
38 | ;;; Bernoulli distribution
39 | ;;;
40 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
41 |
42 | (def-prob-cp flip-cp [p]
43 | :sampler [] (< (rand) p)
44 | :calc-log-lik [bool] (Math/log (if bool p (- 1 p)))
45 | ;; proposer returns a vector of [new-value forward-log-prob backward-log-prob]
46 | :proposer [bool] [(not bool) 0 0])
47 |
48 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
49 | ;;;
50 | ;;; Discrete distribution
51 | ;;;
52 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
53 |
54 | (defn log-pdf-discrete [x dist]
55 | (if (contains? dist x)
56 | (Math/log (dist x))
57 | (Math/log 0)))
58 |
59 | (def-prob-cp discrete-cp [dist]
60 | :sampler [] (probabilistic-clojure.utils.sampling/sample-from dist)
61 | :calc-log-lik [x] (probabilistic-clojure.embedded.choice-points/log-pdf-discrete x dist)
62 | :proposer [old-x] (let [prop-dist (probabilistic-clojure.utils.sampling/normalize (assoc dist old-x 0))
63 | new-x (probabilistic-clojure.utils.sampling/sample-from prop-dist)]
64 | [new-x
65 | (probabilistic-clojure.embedded.choice-points/log-pdf-discrete new-x prop-dist)
66 | (probabilistic-clojure.embedded.choice-points/log-pdf-discrete
67 | old-x (probabilistic-clojure.utils.sampling/normalize (assoc dist new-x 0)))]))
68 |
69 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
70 | ;;;
71 | ;;; Gaussian distribution
72 | ;;;
73 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
74 |
75 | (def ^:dynamic *gaussian-proposal-sdev* 0.7)
76 |
77 | (def-prob-cp gaussian-cp [mu sdev]
78 | :sampler [] (incanter.stats/sample-normal 1 :mean mu :sd sdev)
79 | :calc-log-lik [x] (Math/log (incanter.stats/pdf-normal x :mean mu :sd sdev))
80 | :proposer [old-x] (let [proposal-sd probabilistic-clojure.embedded.choice-points/*gaussian-proposal-sdev*
81 | new-x (incanter.stats/sample-normal 1 :mean old-x :sd proposal-sd)]
82 | [new-x
83 | (Math/log (incanter.stats/pdf-normal new-x :mean old-x :sd proposal-sd))
84 | (Math/log (incanter.stats/pdf-normal old-x :mean new-x :sd proposal-sd))]))
85 |
86 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
87 | ;;;
88 | ;;; Dirichlet distribution
89 | ;;;
90 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
91 |
92 | (defn log-pdf-dirichlet [ps alphas]
93 | (assert (= (count ps) (count alphas))
94 | "Dimension mismatch in log-pdf-dirichlet!")
95 | (let [log-gamma (fn [x] (Gamma/logGamma x))
96 | norm (- (reduce + (map log-gamma alphas))
97 | (log-gamma (reduce + alphas)))]
98 | (- (reduce + (map (fn [p a] (* (- a 1) (Math/log p))) ps alphas))
99 | norm)))
100 |
101 | (def ^:dynamic *dirichlet-proposal-factor* 42)
102 | (def ^:dynamic *dirichlet-proposal-shift* 0.001) ; found a paper claiming that this is good
103 | (def ^:dynamic *dirichlet-initial-factor* 1)
104 |
105 | (def-prob-cp dirichlet-cp [alphas]
106 | :sampler [] (first
107 | (incanter.stats/sample-dirichlet
108 | 2
109 | (map (partial * probabilistic-clojure.embedded.choice-points/*dirichlet-initial-factor*)
110 | alphas)))
111 | :calc-log-lik [ps] (probabilistic-clojure.embedded.choice-points/log-pdf-dirichlet ps alphas)
112 | :proposer [old-ps] (letfn [(proposal-alphas [alphas]
113 | (for [a alphas]
114 | (+ (* probabilistic-clojure.embedded.choice-points/*dirichlet-proposal-factor* a)
115 | probabilistic-clojure.embedded.choice-points/*dirichlet-proposal-shift*)))]
116 | (let [new-ps (first (incanter.stats/sample-dirichlet 2 (proposal-alphas old-ps)))]
117 | [new-ps
118 | (probabilistic-clojure.embedded.choice-points/log-pdf-dirichlet new-ps (proposal-alphas old-ps))
119 | (probabilistic-clojure.embedded.choice-points/log-pdf-dirichlet old-ps (proposal-alphas new-ps))])))
120 |
121 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
122 | ;;;
123 | ;;; Beta distribution
124 | ;;;
125 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
126 |
127 | (def-prob-cp beta-cp [alpha beta]
128 | :sampler [] (incanter.stats/sample-beta 1 :alpha alpha :beta beta)
129 | :calc-log-lik [x] (Math/log (incanter.stats/pdf-beta x :alpha alpha :beta beta))
130 | :proposer [old-x] (let [new-x (incanter.stats/sample-beta 1 :alpha alpha :beta beta)]
131 | [new-x
132 | (Math/log (incanter.stats/pdf-beta new-x :alpha alpha :beta beta))
133 | (Math/log (incanter.stats/pdf-beta old-x :alpha alpha :beta beta))]))
134 |
135 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
136 | ;;;
137 | ;;; Dirichlet process
138 | ;;;
139 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
140 |
141 | (defn pick-a-stick [alpha idx]
142 | (let [stick (beta-cp [:pick :stick idx] 1 alpha)
143 | stop (flip-cp [:pick :stop idx] (gv stick))]
144 | (det-cp [:pick idx]
145 | (if (gv stop)
146 | idx
147 | (gv (pick-a-stick alpha (inc idx)))))))
148 |
149 | (defmacro dirichlet-process [tag alpha base]
150 | `(memo [~tag ~alpha]
151 | ~base
152 | (gv (pick-a-stick ~alpha 1))))
153 |
--------------------------------------------------------------------------------
/src/probabilistic_clojure/embedded/demos.clj:
--------------------------------------------------------------------------------
1 | ;;; Copyright (C) 2011 Nils Bertschinger
2 |
3 | ;;; This file is part of Probabilistic-Clojure
4 |
5 | ;;; Probabilistic-Clojure is free software: you can redistribute it and/or modify
6 | ;;; it under the terms of the GNU Lesser General Public License as published by
7 | ;;; the Free Software Foundation, either version 3 of the License, or
8 | ;;; (at your option) any later version.
9 |
10 | ;;; Probabilistic-Clojure is distributed in the hope that it will be useful,
11 | ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | ;;; GNU Lesser General Public License for more details.
14 |
15 | ;;; You should have received a copy of the GNU Lesser General Public License
16 | ;;; along with Probabilistic-Clojure. If not, see .
17 |
18 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
19 | ;;;; Probabilistic programming using constraint propagation
20 | ;;;; to efficiently track dependencies between choice points
21 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
22 |
23 | (ns
24 | ^{:author "Nils Bertschinger"
25 | :doc "Part of probabilistic-clojure.embedded. Collection of demo programs."}
26 | probabilistic-clojure.embedded.demos
27 | (:use [probabilistic-clojure.embedded.api :only (det-cp gv trace-failure cond-data memo metropolis-hastings-sampling def-prob-cp)]
28 | [probabilistic-clojure.utils.stuff :only (indexed)]
29 | [probabilistic-clojure.utils.sampling :only (sample-from density)]
30 | [probabilistic-clojure.embedded.choice-points
31 | :only (flip-cp gaussian-cp dirichlet-cp discrete-cp dirichlet-process)]
32 |
33 | [incanter.core :only (view)]
34 | [incanter.charts :only (histogram add-lines xy-plot)]
35 | [incanter.stats :only (mean sample-normal pdf-normal)]))
36 |
37 | (in-ns 'probabilistic-clojure.embedded.demos)
38 |
39 | ;;; Simple Bayes net as a first example
40 |
41 | (defn noisy-or [x y]
42 | (det-cp :noisy-or
43 | (or (and (gv x) (gv (flip-cp :flip9 0.9)))
44 | (and (gv y) (gv (flip-cp :flip8 0.8)))
45 | (gv (flip-cp :flip1 0.1)))))
46 |
47 | (defn grass-bayes-net []
48 | (det-cp :grass-bayes-net
49 | (let [rain (flip-cp :rain 0.3)
50 | sprinkler (flip-cp :sprinkler 0.5)
51 | grass-is-wet (gv (noisy-or rain sprinkler))]
52 | (when-not grass-is-wet
53 | (trace-failure))
54 | (gv rain))))
55 |
56 | (defn grass-bayes-net-fixed []
57 | (det-cp :grass-bayes-net-fixed
58 | (let [rain (gv (flip-cp :rain 0.3))
59 | sprinkler (gv (flip-cp :sprinkler 0.5))
60 | noise-x (gv (flip-cp :noise-x 0.9))
61 | noise-y (gv (flip-cp :noise-y 0.8))
62 | noise-z (gv (flip-cp :noise-z 0.1))]
63 | (if (or (and rain noise-x)
64 | (and sprinkler noise-y)
65 | noise-z)
66 | rain
67 | (trace-failure)))))
68 |
69 | (defn run-bayes-net [model]
70 | (density
71 | (take 7500 (drop 500 (metropolis-hastings-sampling model)))))
72 |
73 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
74 | ;;;
75 | ;;; Gaussian mixture models
76 | ;;;
77 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
78 |
79 | (defn generate-data []
80 | (let [mu (fn [] (sample-from {-5 0.2, 0 0.7, 8 0.1}))]
81 | (lazy-seq (cons (sample-normal 1 :mean (mu))
82 | (generate-data)))))
83 |
84 | (def data (take 42 (generate-data)))
85 |
86 | (defn mixture [comp-labels data]
87 | (let [comp-weights (dirichlet-cp :weights (for [_ comp-labels] 10.0))
88 | comp-mus (zipmap comp-labels
89 | (for [label comp-labels] (gaussian-cp [:mu label] 0.0 10.0)))]
90 | (doseq [[idx point] (indexed data)]
91 | (let [comp (discrete-cp [:comp idx] (zipmap comp-labels (gv comp-weights)))]
92 | ;; mu-comp (det-cp [:mu-comp idx] (gv (get comp-mus (gv comp))))]
93 | ;; (cond-data (gaussian-cp [:obs idx] (gv mu-comp) 1.0) point)
94 | (cond-data (gaussian-cp [:obs idx] (gv (get comp-mus (gv comp))) 1.0) point)))
95 | (det-cp :mixture
96 | [(into {} (for [[comp mu] comp-mus] [comp (gv mu)]))
97 | (gv comp-weights)])))
98 |
99 | (defn mixture-memo [comp-labels data]
100 | (let [comp-weights (dirichlet-cp :weights (for [_ comp-labels] 10.0))]
101 | (doseq [[idx point] (indexed data)]
102 | (let [comp (discrete-cp [:comp idx] (zipmap comp-labels (gv comp-weights)))
103 | comp-mu (memo [:mu idx] (gaussian-cp :mu 0.0 10.0) (gv comp))]
104 | (cond-data (gaussian-cp [:obs idx] (gv comp-mu) 1.0) point)))
105 | (det-cp :mixture
106 | [(into {} (for [comp comp-labels]
107 | [comp (gv (memo [:mu comp] (gaussian-cp :mu 0.0 10.0) comp))]))
108 | (gv comp-weights)])))
109 |
110 | (defn test-mixture [comp-labels model]
111 | (let [data-plot (histogram data :title "Dataset" :nbins 50 :density true)
112 | num-comp (count comp-labels)
113 | [comp-mus weights] (last (take 7500 (metropolis-hastings-sampling (fn [] (model comp-labels data)))))
114 | mus (for [label comp-labels] (get comp-mus label))
115 |
116 | xs (range -10 10 0.01)
117 |
118 | comp-pdf (fn [i x]
119 | (* (nth weights i) (pdf-normal x :mean (nth mus i) :sd 1)))
120 | mix-pdf (fn [x] (reduce + (for [i (range num-comp)] (comp-pdf i x))))]
121 | ;; add the pdf of the fitted mixture
122 | (add-lines data-plot xs (map mix-pdf xs))
123 | ;; and all individual components to the plot
124 | (doseq [i (range num-comp)]
125 | (add-lines data-plot xs (map (partial comp-pdf i) xs)))
126 | (view data-plot)
127 | [weights mus]))
128 |
129 | ;;; now we collapse out the component assignments
130 |
131 | (def-prob-cp collapsed-mixture-cp [comp-probs comp-models]
132 | :sampler [] [] ; just a dummy initialization ... no data drawn from model
133 | :calc-log-lik [xs]
134 | (let [sum (partial reduce +)]
135 | (sum (for [x xs]
136 | (Math/log ; switch to log-probabilities
137 | (sum (for [[p cm] (zipmap comp-probs comp-models)]
138 | ;; component model is a function that calculates the
139 | ;; probability for a given datapoint
140 | (* p (cm x))))))))
141 | :proposer [_] (probabilistic-clojure.utils.stuff/error
142 | "collapsed-mixture-cp does not implement a proposer!"))
143 |
144 | (defn gaussian-comp-model [mu sdev]
145 | (fn [x] (pdf-normal x :mean mu :sd sdev)))
146 |
147 | (defn mixture-collapsed [comp-labels data]
148 | (let [comp-weights (dirichlet-cp :weights (repeat (count comp-labels) 10.0))
149 | comp-mus (for [label comp-labels]
150 | (gaussian-cp [:mu label] 0.0 10.0))
151 | comp-models (det-cp :models
152 | (doall (for [mu-cp comp-mus]
153 | (gaussian-comp-model (gv mu-cp) 1.0))))]
154 | (cond-data (collapsed-mixture-cp :data (gv comp-weights) (gv comp-models))
155 | data)
156 | (det-cp :mixture
157 | [(zipmap comp-labels (map gv comp-mus))
158 | (gv comp-weights)])))
159 |
160 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
161 | ;;;
162 | ;;; Dirichlet process mixture model
163 | ;;;
164 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
165 |
166 | (defn mixture-DP [alpha data]
167 | (loop [points data
168 | idx 0
169 | comps (det-cp [:res 0] [0 {}])]
170 | (if (seq points)
171 | (let [mu-comp (dirichlet-process [::DP idx] alpha (gaussian-cp ::DP 0 15))]
172 | (cond-data (gaussian-cp [:mu idx] (gv mu-comp) 1.0) (first points))
173 | (recur (rest points) (inc idx)
174 | (det-cp [:res (inc idx)]
175 | (let [[num-comp comp-mus] (gv comps)
176 | mu (gv mu-comp)
177 | mu-count (get comp-mus mu 0)
178 | comp-mus (assoc comp-mus mu (inc mu-count))]
179 | [(count comp-mus) comp-mus]))))
180 | comps)))
181 |
182 | (defn test-DP [alpha n]
183 | (let [res (metropolis-hastings-sampling (fn [] (mixture-DP alpha data)))]
184 | (loop [x res, i 0]
185 | (when-not (> i n)
186 | (recur (rest x) (inc i))))))
187 |
188 |
--------------------------------------------------------------------------------
/src/probabilistic_clojure/embedded/fit_poly.clj:
--------------------------------------------------------------------------------
1 | ;;; Copyright (C) 2012 Nils Bertschinger
2 |
3 | ;;; This file is part of Probabilistic-Clojure
4 |
5 | ;;; Probabilistic-Clojure is free software: you can redistribute it and/or modify
6 | ;;; it under the terms of the GNU Lesser General Public License as published by
7 | ;;; the Free Software Foundation, either version 3 of the License, or
8 | ;;; (at your option) any later version.
9 |
10 | ;;; Probabilistic-Clojure is distributed in the hope that it will be useful,
11 | ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | ;;; GNU Lesser General Public License for more details.
14 |
15 | ;;; You should have received a copy of the GNU Lesser General Public License
16 | ;;; along with Probabilistic-Clojure. If not, see .
17 |
18 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
19 | ;;;; Probabilistic programming using constraint propagation
20 | ;;;; to efficiently track dependencies between choice points
21 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
22 |
23 | (ns
24 | ^{:author "Nils Bertschinger"
25 | :doc "Part of probabilistic-clojure.embedded. Demo of fitting polynomials."}
26 | probabilistic-clojure.embedded.fit-poly
27 | (:use [probabilistic-clojure.embedded.api :only (det-cp gv cond-data metropolis-hastings-sampling def-prob-cp)]
28 | [probabilistic-clojure.utils.stuff :only (indexed)]
29 | [probabilistic-clojure.utils.sampling :only (density)]
30 | [probabilistic-clojure.embedded.choice-points
31 | :only (gaussian-cp discrete-cp *gaussian-proposal-sdev*)]
32 |
33 | [incanter.core :only (view)]
34 | [incanter.charts :only (histogram add-lines xy-plot scatter-plot)]
35 | [incanter.stats :only (sample-normal pdf-normal)]))
36 |
37 | (in-ns 'probabilistic-clojure.embedded.fit-poly)
38 |
39 | (defn poly-ranked
40 | "Evaluate the polynomial with the given coefficients at x:
41 | f(x) = coeffs[0] + coeffs[1]*x + ... + coeffs[k]*x^(k-1)"
42 | [x coeffs]
43 |
44 | (reduce + (map * coeffs (iterate (partial * x) 1))))
45 |
46 | (defn poly-horner
47 | "Evaluate the polynomial with the given coefficients at x.
48 | Evaluation follows the Horner scheme:
49 | f(x) = coeffs[0] + x*(coeffs[1] + ... + x*(coeffs[k])...)"
50 | [x coeffs]
51 |
52 | (reduce (fn [y c]
53 | (+ c (* x y)))
54 | (reverse coeffs)))
55 |
56 | (defn poly-roots
57 | [x [scale & roots]]
58 | (* scale
59 | (reduce * (map #(- x %) roots))))
60 |
61 | (defn ^:dynamic legendre-basis [n x]
62 | (cond (= n 0) 1
63 | (= n 1) x
64 | :else (let [n- (dec n)]
65 | (/ (- (* (+ (* 2 n-) 1) x (legendre-basis n- x))
66 | (* n- (legendre-basis (dec n-) x)))
67 | n))))
68 |
69 | (defn poly-legendre [x coeffs]
70 | (binding [legendre-basis (memoize legendre-basis)]
71 | (let [x (/ x 4)]
72 | (reduce +
73 | (for [[i c] (indexed coeffs)]
74 | (* c (legendre-basis i x)))))))
75 |
76 | (def poly poly-legendre)
77 |
78 | (def test-poly [-1 1 -0.7 0.3])
79 |
80 | (defn uni-rand [low high]
81 | (+ low (rand (- high low))))
82 |
83 | (def demo-data
84 | (repeatedly 17
85 | (fn []
86 | (let [x (uni-rand -5 5)
87 | y (poly-ranked x test-poly)]
88 | [x (sample-normal 1 :mean y :sd 2)]))))
89 |
90 | ;; special gaussian-cp which initially returns mu
91 | (def-prob-cp gaussian0-cp [mu sdev]
92 | :sampler [] (sample-normal 1 :mean 0 :sd 0.1) ;; mu
93 | :calc-log-lik [x] (Math/log (pdf-normal x :mean mu :sd sdev))
94 | :proposer [old-x] (let [proposal-sd *gaussian-proposal-sdev*
95 | new-x (sample-normal 1 :mean old-x :sd proposal-sd)]
96 | [new-x
97 | (Math/log (pdf-normal new-x :mean old-x :sd proposal-sd))
98 | (Math/log (pdf-normal old-x :mean new-x :sd proposal-sd))]))
99 |
100 | (defn poly-fit-fixed
101 | [rank data]
102 | (let [coeffs (det-cp :coeffs
103 | (doall
104 | (for [r (range (inc rank))]
105 | (gv (gaussian-cp [:coeff r]
106 | 0.0 5.0)))))]
107 | (doseq [[i [x y]] (indexed data)]
108 | (let [mu (det-cp [:mu i] (poly x (gv coeffs)))]
109 | (cond-data (gaussian-cp [:obs i]
110 | (gv mu)
111 | 1.0)
112 | y)))
113 | (det-cp :fit
114 | (gv coeffs))))
115 |
116 | (defn poly-fit
117 | ([data] (poly-fit [1] data))
118 | ([rank-range data]
119 | (let [n (count rank-range)
120 | rank (if (= n 1)
121 | (det-cp :rank (first rank-range))
122 | (discrete-cp :rank (zipmap rank-range (repeat (/ 1 n)))))
123 | coeffs (det-cp :coeffs
124 | (into {}
125 | (for [rank rank-range]
126 | [rank (doall
127 | (for [r (range (inc rank))]
128 | (gv (gaussian0-cp [:coeff rank r]
129 | 0.0 5.0))))])))
130 | obs-noise (det-cp :noise
131 | (into {} (for [rank rank-range]
132 | [rank (Math/abs (gv (gaussian-cp [:noise rank]
133 | 0.0 5.0)))])))]
134 | (doseq [[i [x y]] (indexed data)]
135 | (cond-data (gaussian-cp [:obs i]
136 | (poly x (get (gv coeffs) (gv rank)))
137 | (get (gv obs-noise) (gv rank)))
138 | y))
139 | (det-cp :fit
140 | [(gv rank) (gv coeffs) (gv obs-noise)]))))
141 |
142 | (defn poly-demo [ranks data]
143 | (let [xs (range -5 5 0.05)
144 |
145 | fitted (last (take 7500 (metropolis-hastings-sampling
146 | (fn [] (poly-fit ranks demo-data)))))
147 | graph (scatter-plot (map first demo-data) (map second demo-data))]
148 | (doseq [r ranks]
149 | (add-lines graph xs (map #(poly % (get (second fitted) r)) xs)))
150 | (view graph)))
151 |
152 | (defn poly-fit-shared
153 | ([data] (poly-fit-shared [1] data))
154 | ([rank-range data]
155 | (let [n (count rank-range)
156 | rank (if (= n 1)
157 | (det-cp :rank (first rank-range))
158 | (discrete-cp :rank (zipmap rank-range (repeat (/ 1 n)))))
159 | coeffs (det-cp :coeffs
160 | ;; one set of coeffs which are shared by all models
161 | ;; and removed if unused
162 | (doall
163 | (for [r (range (inc (gv rank)))]
164 | (gv (gaussian0-cp [:coeff r]
165 | 0.0 5.0)))))
166 | obs-noise (det-cp :noise
167 | (Math/abs (gv (gaussian-cp [:noise rank]
168 | 0.0 5.0))))]
169 | (doseq [[i [x y]] (indexed data)]
170 | (cond-data (gaussian-cp [:obs i]
171 | (poly x (gv coeffs))
172 | (gv obs-noise))
173 | y))
174 | (det-cp :fit
175 | [(gv rank) (gv coeffs) (gv obs-noise)]))))
176 |
177 | (defn poly-demo-shared [ranks data]
178 | (let [xs (range -5 5 0.05)
179 |
180 | samples (take 75000 (metropolis-hastings-sampling
181 | (fn [] (poly-fit-shared ranks demo-data))))
182 | fitted (last samples)
183 | graph (scatter-plot (map first demo-data) (map second demo-data))]
184 | (println (density (map first samples)))
185 | (doseq [r ranks]
186 | (add-lines graph xs (map #(poly % (take r (second fitted))) xs)))
187 | (view graph)))
188 |
--------------------------------------------------------------------------------
/src/probabilistic_clojure/embedded/lda_demo.clj:
--------------------------------------------------------------------------------
1 | ;;; Copyright (C) 2012 Nils Bertschinger
2 |
3 | ;;; This file is part of Probabilistic-Clojure
4 |
5 | ;;; Probabilistic-Clojure is free software: you can redistribute it and/or modify
6 | ;;; it under the terms of the GNU Lesser General Public License as published by
7 | ;;; the Free Software Foundation, either version 3 of the License, or
8 | ;;; (at your option) any later version.
9 |
10 | ;;; Probabilistic-Clojure is distributed in the hope that it will be useful,
11 | ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | ;;; GNU Lesser General Public License for more details.
14 |
15 | ;;; You should have received a copy of the GNU Lesser General Public License
16 | ;;; along with Probabilistic-Clojure. If not, see .
17 |
18 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
19 | ;;;; Probabilistic programming using constraint propagation
20 | ;;;; to efficiently track dependencies between choice points
21 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
22 |
23 | (ns
24 | ^{:author "Nils Bertschinger"
25 | :doc "Part of probabilistic-clojure.embedded. Demo of Latent Dirichlet Allocation."}
26 | probabilistic-clojure.embedded.lda-demo
27 | (:use [probabilistic-clojure.embedded.api :only (det-cp gv cond-data memo metropolis-hastings-sampling def-prob-cp trace-failure)]
28 | [probabilistic-clojure.utils.stuff :only (indexed)]
29 | [probabilistic-clojure.embedded.choice-points
30 | :only (dirichlet-cp log-pdf-dirichlet *dirichlet-initial-factor* discrete-cp)]
31 |
32 | [incanter.core :only (view sqrt)]
33 | [incanter.stats :only (sample-dirichlet sample-multinomial sample-uniform sample-gamma pdf-gamma sample-normal pdf-normal)])
34 | (:import [java.awt Color Graphics Dimension]
35 | [java.awt.image BufferedImage]
36 | [javax.swing JPanel JFrame]
37 | [org.apache.commons.math.special Gamma]))
38 |
39 | (in-ns 'probabilistic-clojure.embedded.lda-demo)
40 |
41 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
42 | ;;;
43 | ;;; Here we want to show the picture example from the LDA paper
44 | ;;; "Finding scientific topics" by D. Blei et al.
45 | ;;;
46 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
47 |
48 | ;;; Basic definitions and the LDA model as a probabilistic program
49 |
50 | (def alpha 1)
51 | (def beta 1)
52 |
53 | (defn lda [topic-labels documents]
54 | (let [words (distinct (apply concat documents))
55 | num-topics (count topic-labels)
56 | alphas (repeat (count words) alpha)
57 | betas (repeat num-topics beta)]
58 | (doseq [[i doc] (indexed documents)]
59 | (let [topic-weights (dirichlet-cp [:weights i] betas)]
60 | ;; now for each word draw a topic and condition on the observed word
61 | (doseq [[j word] (indexed doc)]
62 | (let [assigned (discrete-cp [:assign i j]
63 | (zipmap topic-labels (gv topic-weights)))
64 | topic-dist (memo [:topic i j] (dirichlet-cp :weights alphas) (gv assigned))]
65 | (cond-data (discrete-cp [:word i j]
66 | (zipmap words (gv topic-dist)))
67 | word)))))
68 | (det-cp :lda
69 | (doall
70 | (into {}
71 | (for [tl topic-labels]
72 | [tl
73 | (zipmap words
74 | (gv (memo [:topic tl]
75 | (dirichlet-cp :weights alphas) tl)))]))))))
76 |
77 |
78 | ;;; Collapsing out the topic assignments should be faster
79 |
80 | ;; A collapsed mixture choice point that takes contigency counts as
81 | ;; data (usually much faster than the one in demo.clj)
82 | (def-prob-cp collapsed-mixture-cp [comp-probs comp-models]
83 | :sampler [] [] ; just a dummy initialization ... no data drawn from model
84 | :calc-log-lik [counts]
85 | (let [sum (partial reduce +)]
86 | (sum (for [[x c] counts]
87 | (* c
88 | (Math/log ; switch to log-probabilities
89 | (sum (for [[p cm] (zipmap comp-probs comp-models)]
90 | ;; component model is a function that calculates the
91 | ;; probability for a given datapoint
92 | (* p (cm x)))))))))
93 | :proposer [_] (probabilistic-clojure.utils.stuff/error
94 | "collapsed-mixture-cp does not implement a proposer!"))
95 |
96 | (defn lda-collapsed [topic-labels documents]
97 | (let [words (distinct (apply concat documents))
98 | num-topics (count topic-labels)
99 | alphas (repeat (count words) alpha)
100 | betas (repeat num-topics beta)
101 |
102 | topic-dists (for [tl topic-labels]
103 | (dirichlet-cp [:topic tl] alphas))]
104 | (doseq [[i doc] (indexed documents)]
105 | (let [topic-weights (dirichlet-cp [:weights i] betas)
106 | topic-models (det-cp [:models i]
107 | (doall (for [w-probs topic-dists]
108 | (let [w-dist (zipmap words (gv w-probs))]
109 | (fn [word] (get w-dist word))))))]
110 | (cond-data (collapsed-mixture-cp [:doc i]
111 | (gv topic-weights) (gv topic-models))
112 | (frequencies doc))))
113 | (det-cp :lda-collapsed
114 | (into {}
115 | (for [[tl top] (zipmap topic-labels topic-dists)]
116 | [tl (zipmap words (gv top))])))))
117 |
118 | ;;; Now generate example documents with the bar-like topics from the paper
119 |
120 | (def xy-dim 3)
121 |
122 | (def num-topics (* 2 xy-dim))
123 | (def num-words (* xy-dim xy-dim))
124 |
125 | (defn row-or-col-topic [row-or-col]
126 | (let [row (:row row-or-col), col (:col row-or-col)]
127 | (for [x (range xy-dim), y (range xy-dim)
128 | :when (or (and row (= row x)) (and col (= col y)))]
129 | [x y])))
130 |
131 | (defn topics []
132 | "Create topics corresponding to horizontal and vertical images.
133 | Each topic is a sequence of words that can appear in this topic."
134 | (concat (for [row (range xy-dim)] (row-or-col-topic {:row row}))
135 | (for [col (range xy-dim)] (row-or-col-topic {:col col}))))
136 |
137 | (defn sample-document [nwords theta topics]
138 | (let [assigned (sample-multinomial nwords :probs theta)
139 | wprobs (for [_ (range xy-dim)] (/ 1 xy-dim))]
140 | (map (fn [z wi] (nth (nth topics z) wi))
141 | assigned (sample-multinomial nwords :probs wprobs))))
142 |
143 | (defn train-data [n topics]
144 | (for [theta (sample-dirichlet n (repeat (count topics) beta))]
145 | ;; (sample-document (sample-uniform 1 :min 33 :max 44 :integers true) theta topics)))
146 | (sample-document 250 theta topics)))
147 |
148 | ;; (def demo-docs (train-data 55 (topics)))
149 | (def demo-docs (train-data 120 (topics)))
150 |
151 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; UI ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
152 |
153 | ;pixels per world cell
154 | (def scale 25)
155 |
156 | (def topic-labels (doall (map (partial str "T") (range num-topics))))
157 | (def topic-samples (into {} (for [tl topic-labels] [tl (ref {})])))
158 |
159 | (defn fill-cell [#^Graphics g x y c]
160 | (doto g
161 | (.setColor c)
162 | (.fillRect (* x scale) (* y scale) scale scale)))
163 |
164 | (defn render [g]
165 | (let [v (dosync (doall
166 | (for [z topic-labels]
167 | (apply vector (for [x (range xy-dim) y (range xy-dim)]
168 | (get @(get topic-samples z) [x y] 0))))))
169 | img (new BufferedImage (* (+ num-topics 2) scale xy-dim) (* scale xy-dim)
170 | (. BufferedImage TYPE_INT_ARGB))
171 | bg (. img (getGraphics))]
172 | (doto bg
173 | (.setColor (. Color blue))
174 | (.fillRect 0 0 (. img (getWidth)) (. img (getHeight))))
175 | (dorun
176 | (for [z (range num-topics) x (range xy-dim) y (range xy-dim)]
177 | (let [rgb (max 0 (- 255 (int (* xy-dim 255 ((nth v z) (+ (* x xy-dim) y))))))]
178 | (fill-cell bg (+ x (* z (inc xy-dim))) y (Color. rgb rgb rgb)))))
179 | (. g (drawImage img 0 0 nil))
180 | (. bg (dispose))))
181 |
182 | (def panel (doto (proxy [JPanel] []
183 | (paint [g] (render g)))
184 | (.setPreferredSize (new Dimension
185 | (* (+ num-topics 2) scale xy-dim)
186 | (* scale xy-dim)))))
187 |
188 | (def frame (doto (new JFrame) (.add panel) .pack .show))
189 |
190 | (defn run [num skip lda-model]
191 | (binding [*dirichlet-initial-factor* 50]
192 | (doseq [[i tops] (indexed
193 | (take num
194 | (metropolis-hastings-sampling
195 | (fn []
196 | (lda-model topic-labels demo-docs)))))]
197 | (when (= (mod i skip) 0)
198 | (dosync
199 | (doseq [tl topic-labels]
200 | (ref-set (get topic-samples tl)
201 | (get tops tl))))
202 | (. panel (repaint))))))
203 |
204 | ;;; Dirichlet choice point based on Gamma samples => more local
205 | ;;; proposal distribution
206 |
207 | (defn diri-probs [gammas]
208 | (let [total (reduce + gammas)]
209 | (vec (map #(/ % total) gammas))))
210 |
211 | (defn propose-gamma-prior [old-x shape rate]
212 | ;; propose new value from Gamma prior
213 | (let [new-x (sample-gamma 1 :shape shape :rate rate)]
214 | [new-x
215 | (Math/log (pdf-gamma new-x :shape shape :rate rate))
216 | (Math/log (pdf-gamma old-x :shape shape :rate rate))]))
217 |
218 | (defn propose-gamma-normal [old-x shape sdev-factor]
219 | (let [sdev (* shape sdev-factor)
220 | new-x (sample-normal 1 :mean old-x :sd sdev)]
221 | (when (< new-x 0)
222 | (trace-failure))
223 | [new-x
224 | (Math/log (pdf-normal new-x :mean old-x :sd sdev))
225 | (Math/log (pdf-normal old-x :mean new-x :sd sdev))]))
226 |
227 | (defn propose-gamma-log-normal [old-x sdev]
228 | (let [log-old-x (Math/log old-x)
229 | log-new-x (sample-normal 1 :mean log-old-x :sd sdev)]
230 | [(Math/exp log-new-x)
231 | (Math/log (pdf-normal log-new-x :mean log-old-x :sd sdev))
232 | (Math/log (pdf-normal log-old-x :mean log-new-x :sd sdev))]))
233 |
234 | ;; un-normalized Dirichlet distribution
235 | (def-prob-cp dirichlet-cp-gamma [alphas]
236 | :sampler [] (vec (for [a alphas] (sample-gamma 1 :shape a :rate 1)))
237 | :calc-log-lik [gs] (log-pdf-dirichlet (diri-probs gs) alphas)
238 | :proposer [old-gs] (let [idx (rand-int (count old-gs))
239 | [new-g fwd bwd]
240 | ;; (propose-gamma-prior (nth old-gs idx) (nth alphas idx) 1)]
241 | (propose-gamma-normal (nth old-gs idx) (nth alphas idx) 1)]
242 | ;; (propose-gamma-log-normal (nth old-gs idx) 1)]
243 | [(assoc old-gs idx new-g) fwd bwd]))
244 |
245 | (defn lda-collapsed-gamma [topic-labels documents]
246 | (let [words (distinct (apply concat documents))
247 | num-topics (count topic-labels)
248 | alphas (repeat (count words) alpha)
249 | betas (repeat num-topics beta)
250 |
251 | topic-dists (for [tl topic-labels]
252 | (dirichlet-cp-gamma [:topic tl] alphas))]
253 | (doseq [[i doc] (indexed documents)]
254 | (let [topic-weights (dirichlet-cp-gamma [:weights i] betas)
255 | topic-models (det-cp [:models i]
256 | (doall (for [w-probs topic-dists]
257 | (let [w-dist (zipmap words (diri-probs (gv w-probs)))]
258 | (fn [word] (get w-dist word))))))]
259 | (cond-data (collapsed-mixture-cp [:doc i]
260 | (diri-probs (gv topic-weights)) (gv topic-models))
261 | (frequencies doc))))
262 | (det-cp :lda-collapsed
263 | (into {}
264 | (for [[tl top] (zipmap topic-labels topic-dists)]
265 | [tl (zipmap words (diri-probs (gv top)))])))))
266 |
267 | (def-prob-cp gamma-cp [shape rate]
268 | :sampler [] (sample-gamma 1 :shape shape :rate rate)
269 | :calc-log-lik [x]
270 | (Math/log (pdf-gamma x :shape shape :rate rate))
271 | :proposer [old-x]
272 | (propose-gamma-log-normal old-x 1))
--------------------------------------------------------------------------------
/src/probabilistic_clojure/embedded/sampling.clj:
--------------------------------------------------------------------------------
1 | ;;; Copyright (C) 2012 Nils Bertschinger
2 |
3 | ;;; This file is part of Probabilistic-Clojure
4 |
5 | ;;; Probabilistic-Clojure is free software: you can redistribute it and/or modify
6 | ;;; it under the terms of the GNU Lesser General Public License as published by
7 | ;;; the Free Software Foundation, either version 3 of the License, or
8 | ;;; (at your option) any later version.
9 |
10 | ;;; Probabilistic-Clojure is distributed in the hope that it will be useful,
11 | ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | ;;; GNU Lesser General Public License for more details.
14 |
15 | ;;; You should have received a copy of the GNU Lesser General Public License
16 | ;;; along with Probabilistic-Clojure. If not, see .
17 |
18 | (ns
19 | ^{:author "Nils Bertschinger"
20 | :doc "Part of probabilistic programming for Clojure.
21 |
22 | Experimental support for simulated annealing as well as annealed
23 | importance sampling. Basically, refactors the core sampling routine to
24 | get a handle on the acceptance condition and allow for interrupting
25 | and restarting sampling."}
26 | probabilistic-clojure.embedded.sampling
27 | (:use [clojure.set :only (union)])
28 | (:use probabilistic-clojure.embedded.api))
29 |
30 | (in-ns 'probabilistic-clojure.embedded.sampling)
31 |
32 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
33 | ;;;
34 | ;;; New interface to the sampler
35 | ;;;
36 | ;;; More flexible, easy to support different sampling strategies
37 | ;;;
38 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
39 |
40 | (defn split-log-lik
41 | "Like total-log-lik, but returns two separate sums for the unconditioned
42 | and conditioned choice points. This allows to distinguish the prior (unconditioned)
43 | and likelihood contributions (conditioned) to the total log-likelihood
44 | of the trace.
45 | Choice points not in the trace are allowed and don't effect the result."
46 |
47 | [cp-names choice-points]
48 | (reduce (fn [[uncond-sum cond-sum :as sums] cp-name]
49 | (let [cp (choice-points cp-name)]
50 | (case (:type cp)
51 | :probabilistic-clojure.embedded.api/probabilistic
52 | (if (:conditioned? cp)
53 | [uncond-sum (+ cond-sum (:log-lik cp))]
54 | [(+ uncond-sum (:log-lik cp)) cond-sum])
55 | :probabilistic-clojure.embedded.api/deterministic
56 | sums
57 | ;; else
58 | sums)))
59 | [0 0] cp-names))
60 |
61 | (defn metropolis-hastings-stepper [choice-points selected selection-dist acceptor]
62 | (with-fresh-store choice-points
63 | (let [selected-cp (choice-points selected)
64 |
65 | [prop-val fwd-log-lik bwd-log-lik]
66 | (propose selected-cp (:value selected-cp))]
67 | ;; Propose a new value for the selected choice point and propagate change to dependents
68 | (set-proposed-val! (:name selected-cp) prop-val)
69 | (let [updates (propagate-change-to (:dependents selected-cp))]
70 | ;; (println "Proposed " (:name selected-cp) " for " updates " updates ("
71 | ;; (count-all-dependents (:name selected-cp) choice-points) " dependents)"))
72 | )
73 |
74 | (if (trace-failed?)
75 | [choice-points ::rejected true selection-dist]
76 | (let [removed-cps (remove-uncalled-choices)
77 | same-topology (and (empty? (fetch-store :newly-created))
78 | (empty? removed-cps))
79 | ;; Here we have the following invariants:
80 | ;; * (assert (empty? (clojure.set/intersection removed-cps (fetch-store :newly-created))))
81 | ;; * (let [new (set (keys (fetch-store :choice-points)))
82 | ;; old (set (keys choice-points))]
83 | ;; (assert (and (= new (difference (union old (fetch-store :newly-created))
84 | ;; removed-cps))
85 | ;; (= old (difference (union new removed-cps) (fetch-store :newly-created))))))
86 |
87 | ;; Overall the recomputed and removed-cps were touched during the update
88 | ;; Thus, we have to calculate the total probability contributed to the old
89 | ;; as well as the new traces.
90 | touched-cps (union (fetch-store :recomputed) removed-cps)
91 | [uncond-trace-log-lik cond-trace-log-lik] (split-log-lik touched-cps choice-points)
92 | [uncond-prop-trace-log-lik cond-prop-trace-log-lik] (split-log-lik touched-cps (fetch-store :choice-points))
93 |
94 | ;; The forward and backward probabilities now account for the newly-created
95 | ;; and removed choice points
96 | fwd-trace-log-lik (total-log-lik (fetch-store :newly-created) (fetch-store :choice-points))
97 | bwd-trace-log-lik (total-log-lik removed-cps choice-points)
98 |
99 | prop-selection-dist (if same-topology
100 | selection-dist
101 | ;; (prob-choice-dist (fetch-store :choice-points)))]
102 | (-> selection-dist
103 | (add-to-prob-choice-dist (fetch-store :newly-created)
104 | (fetch-store :choice-points))
105 | (remove-from-prob-choice-dist removed-cps)))]
106 | ;; Randomly accept the new proposal according to the Metropolis Hastings formula
107 | (if (acceptor uncond-prop-trace-log-lik cond-prop-trace-log-lik
108 | uncond-trace-log-lik cond-trace-log-lik
109 | ;; the total forward proposal probability
110 | (+ (Math/log (prob selection-dist (:name selected-cp)))
111 | fwd-trace-log-lik
112 | fwd-log-lik)
113 | ;; and the backward probability
114 | (+ (Math/log (prob prop-selection-dist (:name selected-cp)))
115 | bwd-trace-log-lik
116 | bwd-log-lik))
117 | ;; (< (Math/log (rand))
118 | ;; (+ (- prop-trace-log-lik trace-log-lik)
119 | ;; (- (Math/log (prob prop-selection-dist (:name selected-cp)))
120 | ;; (Math/log (prob selection-dist (:name selected-cp))))
121 | ;; (- bwd-trace-log-lik fwd-trace-log-lik)
122 | ;; (- bwd-log-lik fwd-log-lik)))
123 | [(fetch-store :choice-points) ::accepted same-topology prop-selection-dist]
124 | [choice-points ::rejected true selection-dist]))))))
125 |
126 | ;; The sampler core has to change as well:
127 | ;; * The acceptor can be specified from the outside
128 |
129 | ;; * To allow for interrupting and restarting of sampling the
130 | ;; choice-points are passed in from the outside and returned
131 | ;; alongside each sample which is now of the form
132 | ;; {:value val :choice-points choice-points}
133 | (defn metropolis-hastings-sampling-core [[cp choice-points] acceptor]
134 | (letfn [(samples [choice-points idx num-accepted num-top-changed update-seq selection-dist]
135 | (lazy-seq
136 | (let [update-seq (or (seq update-seq)
137 | (new-update-sequence (prob-choice-dist choice-points)))
138 | val (cp-value cp choice-points)
139 |
140 | [next-choice-points status same-topology next-selection-dist]
141 | (metropolis-hastings-stepper choice-points (first update-seq) selection-dist acceptor)
142 |
143 | output-info (and *info-steps* (= (mod idx *info-steps*) 0))
144 | num-accepted (if (= status ::accepted)
145 | (inc num-accepted) num-accepted)
146 | num-top-changed (if same-topology
147 | num-top-changed (inc num-top-changed))]
148 | (when output-info
149 | (println idx ": " val)
150 | (println "Log. lik.: " (total-log-lik (keys choice-points) choice-points))
151 | (println "Accepted " num-accepted " out of last " *info-steps* " samples.")
152 | (println "Topology changed on " num-top-changed " samples."))
153 | (cons {:value val :choice-points choice-points}
154 | (samples next-choice-points
155 | (inc idx)
156 | (if output-info 0 num-accepted)
157 | (if output-info 0 num-top-changed)
158 | (if same-topology
159 | (rest update-seq)
160 | (new-update-sequence next-selection-dist))
161 | next-selection-dist)))))]
162 | (let [selection-dist (prob-choice-dist choice-points)]
163 | (samples choice-points 0 0 0 (new-update-sequence selection-dist) selection-dist))))
164 |
165 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
166 | ;;;
167 | ;;; This shows how the standard sampling procedure can be obtained
168 | ;;; using the new interface to the sampler
169 | ;;;
170 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
171 |
172 | (defn metropolis-hastings-acceptor
173 | [uncond-prop-trace-log-lik cond-prop-trace-log-lik
174 | uncond-trace-log-lik cond-trace-log-lik
175 | total-fwd-log-lik total-bwd-log-lik]
176 | (< (Math/log (rand))
177 | (+ (- (+ uncond-prop-trace-log-lik cond-prop-trace-log-lik)
178 | (+ uncond-trace-log-lik cond-trace-log-lik))
179 | (- total-bwd-log-lik
180 | total-fwd-log-lik))))
181 |
182 | (defn standard-metropolis-hastings-sampling
183 | ([prob-thunk]
184 | (standard-metropolis-hastings-sampling prob-thunk
185 | metropolis-hastings-acceptor))
186 | ([prob-thunk acceptor]
187 | (println "Trying to find a valid trace ...")
188 | (let [cp-and-choice-points (find-valid-trace prob-thunk)]
189 | (println "Started sampling")
190 | (map :value
191 | (metropolis-hastings-sampling-core cp-and-choice-points
192 | acceptor)))))
193 |
194 | ;; test this on the demo code
195 |
196 | (comment
197 | (probabilistic-clojure.utils.sampling/density
198 | (take 7500
199 | (drop 500
200 | (standard-metropolis-hastings-sampling
201 | probabilistic-clojure.embedded.demos/grass-bayes-net))))
202 |
203 | (last
204 | (take 7500
205 | (standard-metropolis-hastings-sampling
206 | (fn [] (probabilistic-clojure.embedded.demos/mixture-memo
207 | [:a :b :c]
208 | probabilistic-clojure.embedded.demos/data))))))
209 |
210 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
211 | ;;;
212 | ;;; Simulated annealing ... simple plug in a different acceptor
213 | ;;;
214 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
215 |
216 | (defn simulated-annealing-acceptor [inv-temperature]
217 | (fn [uncond-prop-trace-log-lik cond-prop-trace-log-lik
218 | uncond-trace-log-lik cond-trace-log-lik
219 | total-fwd-log-lik total-bwd-log-lik]
220 | ;; ignores the forward-backward probability and accepts according
221 | ;; to the scaled (with the inverse temperature) total log-probability
222 | ;; difference
223 | (< (Math/log (rand))
224 | (* inv-temperature
225 | (- (+ uncond-prop-trace-log-lik cond-prop-trace-log-lik)
226 | (+ uncond-trace-log-lik cond-trace-log-lik))))))
227 |
228 | (defn simulated-annealing-acceptor-prior [inv-temperature]
229 | (fn [uncond-prop-trace-log-lik cond-prop-trace-log-lik
230 | uncond-trace-log-lik cond-trace-log-lik
231 | total-fwd-log-lik total-bwd-log-lik]
232 | ;; ignores the forward-backward probability and accepts according
233 | ;; to the (unscaled) prior and scaled (with the inverse temperature)
234 | ;; log-likelihood difference
235 | (< (Math/log (rand))
236 | (+ (- uncond-prop-trace-log-lik uncond-trace-log-lik)
237 | (* inv-temperature
238 | (- cond-prop-trace-log-lik cond-trace-log-lik))))))
239 |
240 | (defn simulated-annealing
241 | "Implements simulated annealing. The temperature schedule is a
242 | sequence containing [inv-temperature number-of-steps] pairs.
243 |
244 | Usually one wants to start with a rather low inverse temperature and
245 | increase it over time."
246 | ([prob-thunk inv-temperature-schedule]
247 | (simulated-annealing prob-thunk inv-temperature-schedule simulated-annealing-acceptor))
248 | ([prob-thunk inv-temperature-schedule acceptor]
249 | (println "Trying to find a valid trace ...")
250 | (let [[cp choice-points] (find-valid-trace prob-thunk)]
251 | (println "Started sampling")
252 | (reduce concat
253 | (first
254 | (reduce (fn [[samples choice-points] [inv-temperature steps]]
255 | (let [more-samples
256 | (take steps (metropolis-hastings-sampling-core
257 | [cp choice-points]
258 | (acceptor inv-temperature)))]
259 | [(conj samples (map :value more-samples))
260 | (:choice-points (last more-samples))]))
261 | [[] choice-points]
262 | inv-temperature-schedule))))))
263 |
264 | ;; This nicely optimizes the Gaussian mixture model
265 | (comment
266 | (last
267 | (simulated-annealing
268 | (fn [] (probabilistic-clojure.embedded.demos/mixture-memo
269 | [:a :b :c] probabilistic-clojure.embedded.demos/data))
270 | [[0.01 2500] [0.1 2500] [1 2500] [10 2500] [100 2500]])))
271 |
272 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
273 | ;;;
274 | ;;; Annealed importance sampling
275 | ;;;
276 | ;;; TODO: Distinguish between conditioned and unconditioned choice
277 | ;;; points to handle prior and likelihood weights differently!
278 | ;;;
279 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
280 |
281 | (defn annealed-importance-acceptor
282 | "One way to obtain a sequence of chains for annealed importance
283 | sampling. Uses the Metropolis-Hastings acceptance condition, but
284 | mixes for the distribution p(x) p(y|x)^beta instead of p(x,y)."
285 | [beta]
286 | (fn
287 | [uncond-prop-trace-log-lik cond-prop-trace-log-lik
288 | uncond-trace-log-lik cond-trace-log-lik
289 | total-fwd-log-lik total-bwd-log-lik]
290 | (< (Math/log (rand))
291 | (+ (- uncond-prop-trace-log-lik uncond-trace-log-lik)
292 | (* beta (- cond-prop-trace-log-lik cond-trace-log-lik))
293 | (- total-bwd-log-lik total-fwd-log-lik)))))
294 |
295 | (defn annealed-importance-sample
296 | "Implements annealed importance sampling to draw ONE sample with its
297 | corresponding importance weight. For the sample a sequence of
298 | Markov-chains according to the given annealing schedule (sequence of
299 | [beta num-steps] pairs) is run and used to calculate its importance
300 | weight. Beta should start close to zero and then slowly increase
301 | towards 1.
302 |
303 | Running this function repeatedly produces independent, weighted
304 | samples from the distribution specified by the probabilistic
305 | function prob-thunk. The variance of the importance weights can be
306 | used as diagnostic for the quality of the obtained samples which
307 | depends on how well the Markov chains are mixing."
308 | [prob-thunk annealing-schedule]
309 |
310 | (let [[cp choice-points] (find-valid-trace prob-thunk)]
311 | (print "Sampling ... ")
312 | (let [chain-log-lik (fn [beta choice-points]
313 | (let [[uncond-log-lik cond-log-lik]
314 | (split-log-lik (keys choice-points) choice-points)]
315 | (+ uncond-log-lik (* beta cond-log-lik))))
316 |
317 | [x-0 log-weights choice-points]
318 | (reduce (fn [[x-n-1 log-ws choice-points] [beta-n-1 steps-T-n-1]]
319 | (let [prob-x-n-1 (chain-log-lik beta-n-1 choice-points)
320 | {x-n-2 :value new-choice-points :choice-points}
321 | (last (take steps-T-n-1
322 | (metropolis-hastings-sampling-core
323 | [cp choice-points]
324 | (annealed-importance-acceptor beta-n-1))))
325 | prob-x-n-2 (chain-log-lik beta-n-1 new-choice-points)]
326 | ;; (println "Chain moved " x-n-1 " to " x-n-2)
327 | ;; (println "Log. weight difference: " (- prob-x-n-1 prob-x-n-2))
328 | [x-n-2
329 | (conj log-ws (- prob-x-n-1 prob-x-n-2))
330 | new-choice-points]))
331 | [(cp-value cp choice-points)
332 | (let [[prior-log-lik _] (split-log-lik (keys choice-points) choice-points)]
333 | [(- prior-log-lik)])
334 | choice-points]
335 | annealing-schedule)
336 | prob-x-0 (total-log-lik (keys choice-points) choice-points)]
337 | (println "value: " x-0 " with weight: " (+ prob-x-0 (reduce + log-weights)))
338 | {:value x-0
339 | :log-importance-weight (+ prob-x-0 (reduce + log-weights))
340 | :debug (conj log-weights prob-x-0)})))
341 |
342 | ;; Try this on a very simple model, i.e. fitting the mean of a
343 | ;; standard Gaussian with a Gaussian prior
344 |
345 | (use '[probabilistic-clojure.embedded.choice-points :only (gaussian-cp)])
346 | (use '[probabilistic-clojure.utils.stuff :only (indexed)])
347 | (use '[incanter.stats :only (sample-normal pdf-normal)])
348 |
349 | (defn gauss-fit [mu-prior sd-prior sd-likelihood data]
350 | (let [mu (gaussian-cp :mu mu-prior sd-prior)]
351 | (doseq [[i x] (indexed data)]
352 | (cond-data (gaussian-cp [:obs i] (gv mu) sd-likelihood)
353 | x))
354 | (det-cp :fit (gv mu))))
355 |
356 | (def xs (sample-normal 10 :mean 2.5 :sd 1))
357 |
358 | ;; The theoretical posterior and marginal likelihood for the Gaussian
359 | ;; mean fit Formulas are from notes by Kevin Murphy ... simplify by
360 | ;; using precision (lambda) instead of variance
361 |
362 | (defn posterior [mu-0 lambda-0 lambda xs]
363 | (let [lambda-n (+ lambda-0 (* (count xs) lambda))
364 | mu-n (/ (+ (* lambda (reduce + xs))
365 | (* lambda-0 mu-0))
366 | lambda-n)]
367 | {:mu mu-n :sdev (Math/sqrt (/ 1 lambda-n))}))
368 |
369 | (defn log-marginal-likelihood [mu-0 lambda-0 lambda xs]
370 | ;; formula (42) from the notes
371 | (let [sig (Math/sqrt (/ 1 lambda))
372 | n-*-x-mean (reduce + xs)
373 | n (count xs)]
374 | (+ (Math/log (/ sig (* (Math/pow (* (Math/sqrt (* 2 Math/PI)) sig) n)
375 | (Math/sqrt (+ (* n (/ 1 lambda-0)) (/ 1 lambda))))))
376 | (- (+ (/ (reduce + (map * xs xs)) (* 2 (/ 1 lambda)))
377 | (/ (* mu-0 mu-0) (* 2 (/ 1 lambda-0)))))
378 | (/ (+ (/ (* (/ 1 lambda-0) n-*-x-mean n-*-x-mean)
379 | (/ 1 lambda))
380 | (/ (* (/ 1 lambda) mu-0 mu-0)
381 | (/ 1 lambda-0))
382 | (* 2 n-*-x-mean mu-0))
383 | (* 2 (+ (* n (/ 1 lambda-0)) (/ 1 lambda)))))))
384 |
385 | ;; TODO: check this formula ... seems to use improper flat prior!!!
386 |
387 | ;; The empirical average of the importance weights should be close to that!
388 |
389 | (use '[incanter.core :only (view)])
390 | (use '[incanter.charts :only (histogram add-lines)])
391 |
392 | (use '[probabilistic-clojure.utils.sampling :only (sample-from normalize density)])
393 |
394 | (defn resampling-distribution [importance-samples]
395 | (let [max-log-weight (reduce max (map :log-importance-weight importance-samples))]
396 | (normalize
397 | (into {} (for [sample importance-samples]
398 | [(:value sample)
399 | (Math/exp (- (:log-importance-weight sample) max-log-weight))])))))
400 |
401 | (defn log-sum-exp
402 | "Evaluates \\log \\sum_i e^{x_i}."
403 | [xs]
404 | (let [x-max (apply max xs)]
405 | (+ x-max
406 | (Math/log (reduce + (map #(Math/exp (- % x-max)) xs))))))
407 |
408 | (defn effective-size
409 | "Calculates the effective sample size for the given importance weights:
410 | N_{eff} = \\frac{(\\sum_i w_i)^2}{\\sum w_i^2}
411 | "
412 | [importance-weights]
413 | (Math/exp (- (* 2 (log-sum-exp importance-weights))
414 | (log-sum-exp (map (partial * 2) importance-weights)))))
415 |
416 | (defn test-ais [xs num-samples]
417 | (let [mu-prior 0
418 | sd-prior 10
419 | sd-likelihood 1
420 | lambda-0 (/ 1 (* sd-prior sd-prior))
421 | lambda (/ 1 (* sd-likelihood sd-likelihood))
422 |
423 | {mu-n :mu sd-n :sdev} (posterior mu-prior lambda-0 lambda xs)
424 |
425 | ;; a-schedule (for [beta (range 0.05 0.95 0.05)]
426 | ;; [beta 100])
427 | a-schedule (for [beta (range 0.01 1 0.01)]
428 | [beta 10])
429 | samples
430 | (repeatedly num-samples
431 | (fn [] (annealed-importance-sample (fn [] (gauss-fit mu-prior sd-prior sd-likelihood xs)) a-schedule)))]
432 | (println "Posterior: mu = " mu-n ", sdev = " sd-n)
433 | (println "Log. marginal likelihood of data: " (log-marginal-likelihood mu-prior lambda-0 lambda xs))
434 | (println "Log. average importance weights: "
435 | (- (log-sum-exp (map :log-importance-weight samples))
436 | (Math/log (count samples))))
437 | ;; How to calculate the variance of those weights to access sample quality????
438 | ;; (let [N-eff (effective-size (map :log-importance-weight samples))]
439 | ;; (println (map :log-importance-weight samples))
440 | ;; (println "Variance of importance weights: "
441 | ;; (- (/ (count samples) N-eff)
442 | ;; 1)
443 | ;; " "
444 | ;; (reduce + (map #(* % %) (vals (resampling-distribution samples))))))
445 | (println "Effective sample size: " (effective-size (map :log-importance-weight samples)))
446 | (let [dist (resampling-distribution samples)
447 | hist (histogram (repeatedly 250 (fn [] (sample-from dist)))
448 | :nbins 50 :density true)
449 | x-range (range -5 5 0.01)]
450 | (doto hist
451 | (add-lines x-range (map (fn [x] (pdf-normal x :mean mu-n :sd sd-n)) x-range))
452 | view))))
453 |
454 | (defn test-MH [xs num-samples]
455 | (let [mu-prior 0
456 | sd-prior 10
457 | sd-likelihood 1
458 | lambda-0 (/ 1 (* sd-prior sd-prior))
459 | lambda (/ 1 (* sd-likelihood sd-likelihood))
460 |
461 | {mu-n :mu sd-n :sdev} (posterior mu-prior lambda-0 lambda xs)
462 |
463 | samples (take num-samples
464 | (drop 2500
465 | (standard-metropolis-hastings-sampling
466 | (fn [] (gauss-fit mu-prior sd-prior sd-likelihood xs)))))
467 |
468 | hist (histogram (repeatedly 250 (fn [] (sample-from (density samples))))
469 | :nbins 50 :density true)
470 | x-range (range -5 5 0.01)]
471 | (doto hist
472 | (add-lines x-range (map (fn [x] (pdf-normal x :mean mu-n :sd sd-n)) x-range))
473 | view)))
474 |
--------------------------------------------------------------------------------
/src/probabilistic_clojure/embedded/test_deps.clj:
--------------------------------------------------------------------------------
1 | ;;; Copyright (C) 2011 Nils Bertschinger
2 |
3 | ;;; This file is part of Probabilistic-Clojure
4 |
5 | ;;; Probabilistic-Clojure is free software: you can redistribute it and/or modify
6 | ;;; it under the terms of the GNU Lesser General Public License as published by
7 | ;;; the Free Software Foundation, either version 3 of the License, or
8 | ;;; (at your option) any later version.
9 |
10 | ;;; Probabilistic-Clojure is distributed in the hope that it will be useful,
11 | ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | ;;; GNU Lesser General Public License for more details.
14 |
15 | ;;; You should have received a copy of the GNU Lesser General Public License
16 | ;;; along with Probabilistic-Clojure. If not, see .
17 |
18 | (ns
19 | ^{:author "Nils Bertschinger"
20 | :doc "Tests for probabilistic-clojure.embedded.
21 | Checks dependency tracking between choice points"}
22 | probabilistic-clojure.embedded.test-deps
23 | (:use clojure.test)
24 | (:use probabilistic-clojure.embedded.api
25 | [probabilistic-clojure.embedded.choice-points :only (flip-cp)]))
26 |
27 | (in-ns 'probabilistic-clojure.embedded.test-deps)
28 |
29 | ;;; TODO: use testing framework and write real unit tests!!!
30 |
31 | (defn deps-fixture [dep-test-func]
32 | (with-fresh-store {}
33 | (dep-test-func)))
34 |
35 | (use-fixtures :each deps-fixture)
36 |
37 | (defn check-store
38 | "Pass sets of cp-names for the corresponding entries in the global-store.
39 | Those are then tested against the current store, i.e. (is (= ))."
40 | [{:keys [recomputed newly-created possibly-removed]}]
41 | (are [store-key val] (= (fetch-store store-key) val)
42 | :recomputed recomputed
43 | :newly-created newly-created
44 | :possibly-removed possibly-removed))
45 |
46 | (defn check-cps [tag & cp-data]
47 | (doseq [[cp-name v dependents depends-on] cp-data]
48 | (let [cp (fetch-store :choice-points (get cp-name))
49 | msg (str tag ": checking choice point " cp-name)]
50 | (is (= (:recomputed cp) v) msg)
51 | (is (= (:dependents cp) dependents) msg)
52 | (is (= (:depends-on cp) depends-on) msg))))
53 |
54 | (defn set-value! [cp val]
55 | (assoc-in-store! [:choice-points (:name cp) :recomputed] val))
56 |
57 | (defn refresh []
58 | (reset! *global-store*
59 | (fresh-state (fetch-store :choice-points))))
60 |
61 | (deftest dynamic-dependencies
62 | (let [a (det-cp :a true)
63 | b (det-cp :b (list :hello (gv a)))
64 | c (det-cp :c (if (gv a)
65 | (list (gv b) :c)
66 | :nope))
67 |
68 | [na nb nc] (map :name [a b c])]
69 | ;; check initial values
70 | (check-cps :initial
71 | [na true #{nb nc} #{}]
72 | [nb (list :hello true) #{nc} #{na}]
73 | [nc (list (list :hello true) :c) #{} #{na nb}])
74 | (check-store {:recomputed #{na nb nc}
75 | :newly-created #{na nb nc}
76 | :possibly-removed #{}})
77 | ;; now update b and recompute
78 | (refresh)
79 | (set-value! b :huhu)
80 | (recompute-value c)
81 | (check-cps :huhu
82 | [na true #{nb nc} #{}]
83 | [nb :huhu #{nc} #{na}]
84 | [nc (list :huhu :c) #{} #{na nb}])
85 | (check-store {:recomputed #{nc}
86 | :newly-created #{}
87 | :possibly-removed #{}})
88 | ;; setting a to false changes dependencies
89 | (refresh)
90 | (set-value! a false)
91 | (recompute-value c)
92 | (check-cps :a-false
93 | [na false #{nb nc} #{}]
94 | [nb :huhu #{} #{na}]
95 | [nc :nope #{} #{na}])
96 | (check-store {:recomputed #{nc}
97 | :newly-created #{}
98 | :possibly-removed #{nb}})
99 | ;; now changing b has not much effect
100 | (refresh)
101 | (set-value! b :nowhere)
102 | (recompute-value c)
103 | (check-cps :nowhere
104 | [na false #{nb nc} #{}]
105 | [nb :nowhere #{} #{na}]
106 | [nc :nope #{} #{na}])
107 | (check-store {:recomputed #{nc}
108 | :newly-created #{}
109 | :possibly-removed #{}})
110 | ;; now remove b from the store and set a back to true
111 | ;; dependencies change again and b is re-created
112 | (refresh)
113 | (update-in-store! [:choice-points] dissoc nb)
114 | (set-value! a true)
115 | (recompute-value c)
116 | (check-cps :init-again
117 | [na true #{nb nc} #{}]
118 | [nb (list :hello true) #{nc} #{na}]
119 | [nc (list (list :hello true) :c) #{} #{na nb}])
120 | (check-store {:recomputed #{nb nc}
121 | :newly-created #{nb}
122 | :possibly-removed #{}})))
123 |
124 | (deftest propagation-consistency-1
125 | (let [a (det-cp :a :a)
126 | b (det-cp :b (list :b (gv a)))
127 | c (det-cp :c (list :c (gv b) (gv a)))
128 | p (flip-cp :p (if (gv a) 0.0 1.0))
129 | d (det-cp :d (list :d (gv p) (gv c)))
130 | e (det-cp :e (list :e (gv p)))
131 |
132 | [na nb nc np nd ne] (map :name [a b c p d e])]
133 | (check-cps :initial
134 | [na :a #{nb nc np} #{}]
135 | [nb '(:b :a) #{nc} #{na}]
136 | [nc '(:c (:b :a) :a) #{nd} #{na nb}]
137 | [np '(0.0) #{nd ne} #{na}]
138 | [nd '(:d false (:c (:b :a) :a)) #{} #{nc np}]
139 | [ne '(:e false) #{} #{np}])
140 | (set-value! a nil)
141 | (propagate-change-to
142 | (fetch-store :choice-points (get na) :dependents))
143 | (check-cps :initial
144 | [na nil #{nb nc np} #{}]
145 | [nb '(:b nil) #{nc} #{na}]
146 | [nc '(:c (:b nil) nil) #{nd} #{na nb}]
147 | [np '(1.0) #{nd ne} #{na}] ;; the value false is not changed, even though it has prob. zero now!
148 | [nd '(:d false (:c (:b nil) nil)) #{} #{nc np}]
149 | [ne '(:e false) #{} #{np}])))
150 |
151 | (deftest propagation-consistency-2
152 | (let [c (atom 0)
153 | a (det-cp :a true)
154 | b (det-cp :b (if (gv a)
155 | :b-true
156 | (list :a-false (gv @c))))]
157 | (reset! c (det-cp :c (if (gv a)
158 | (list :a-true (gv b))
159 | :c-false)))
160 | (let [[na nb nc] (map :name [a b @c])]
161 | (check-cps :initial
162 | [na true #{nb nc} #{}]
163 | [nb :b-true #{nc} #{na}]
164 | [nc '(:a-true :b-true) #{} #{na nb}])
165 | (refresh)
166 | (set-value! a false)
167 | (propagate-change-to
168 | (fetch-store :choice-points (get na) :dependents))
169 | (check-cps :flip
170 | [na false #{nb nc} #{}]
171 | [nb '(:a-false :c-false) #{} #{na nc}]
172 | [nc :c-false #{nb} #{na}])
173 | (refresh)
174 | (set-value! a true)
175 | (propagate-change-to
176 | (fetch-store :choice-points (get na) :dependents))
177 | (check-cps :flip-flip
178 | [na true #{nb nc} #{}]
179 | [nb :b-true #{nc} #{na}]
180 | [nc '(:a-true :b-true) #{} #{na nb}]))))
--------------------------------------------------------------------------------
/src/probabilistic_clojure/embedded/test_sampling.clj:
--------------------------------------------------------------------------------
1 | (ns
2 | ^{:author "Nils Bertschinger"
3 | :doc "Tests for probabilistic-clojure.embedded.
4 | Approximate tests for the sampling related stuff"}
5 | probabilistic-clojure.embedded.test-sampling
6 | (:use clojure.test)
7 | (:use probabilistic-clojure.embedded.api
8 | probabilistic-clojure.embedded.choice-points
9 | probabilistic-clojure.embedded.demos
10 | probabilistic-clojure.utils.sampling))
11 |
12 | (in-ns 'probabilistic-clojure.embedded.test-sampling)
13 |
14 | (defn info-fixture [tests]
15 | (binding [*info-steps* 2500]
16 | (tests)))
17 |
18 | (use-fixtures :once info-fixture)
19 |
20 | (defn sample-bayes-net [steps bayes-net sampler]
21 | (->> (sampler bayes-net)
22 | (drop (/ steps 4))
23 | (take steps)
24 | density))
25 |
26 | (defn retracts-net
27 | "Example of a changing topology -- choice points are removed and re-created --
28 | to test dependency tracking and sampling."
29 | []
30 | (let [root (flip-cp :root 0.5)
31 | path-left (flip-cp :left (do (gv root) 0.5))
32 | path-right (flip-cp :right (do (gv root) 0.5))]
33 | (det-cp :result
34 | (if (gv root)
35 | [:left (gv path-left)]
36 | [:right (gv path-right)]))))
37 |
38 | (defn prob= [x y]
39 | (let [eps 0.01
40 | diff (- x y)]
41 | (< (- eps) diff eps)))
42 |
43 | (deftest retracts-sampling
44 | (is (prob= (get (sample-bayes-net 10000 retracts-net monte-carlo-sampling)
45 | [:left false])
46 | 0.25))
47 | (is (prob= (get (sample-bayes-net 10000 retracts-net metropolis-hastings-sampling)
48 | [:left false])
49 | 0.25)))
50 |
51 | (deftest grass-demos
52 | (let [true-prob (float 1419/3029)]
53 | ;; The exact prob. of the grass net being true was calculated with the prob. monad
54 | (are [sampler bayes-net]
55 | (prob= (get (sample-bayes-net 10000 bayes-net sampler) true) true-prob)
56 |
57 | monte-carlo-sampling grass-bayes-net
58 | metropolis-hastings-sampling grass-bayes-net
59 | monte-carlo-sampling grass-bayes-net-fixed
60 | metropolis-hastings-sampling grass-bayes-net-fixed)))
--------------------------------------------------------------------------------
/src/probabilistic_clojure/embedded/tests.clj:
--------------------------------------------------------------------------------
1 | ;;; Copyright (C) 2011 Nils Bertschinger
2 |
3 | ;;; This file is part of Probabilistic-Clojure
4 |
5 | ;;; Probabilistic-Clojure is free software: you can redistribute it and/or modify
6 | ;;; it under the terms of the GNU Lesser General Public License as published by
7 | ;;; the Free Software Foundation, either version 3 of the License, or
8 | ;;; (at your option) any later version.
9 |
10 | ;;; Probabilistic-Clojure is distributed in the hope that it will be useful,
11 | ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | ;;; GNU Lesser General Public License for more details.
14 |
15 | ;;; You should have received a copy of the GNU Lesser General Public License
16 | ;;; along with Probabilistic-Clojure. If not, see .
17 |
18 | (ns
19 | ^{:author "Nils Bertschinger"
20 | :doc "Tests for probabilistic-clojure.embedded"}
21 | probabilistic-clojure.embedded.tests
22 | (:use probabilistic-clojure.embedded.api
23 | probabilistic-clojure.embedded.choice-points
24 | probabilistic-clojure.utils.sampling
25 | probabilistic-clojure.embedded.demos))
26 |
27 | (in-ns 'probabilistic-clojure.embedded.tests)
28 |
29 | ;;; TODO: use testing framework and write real unit tests!!!
30 |
31 | (defn cp-str [cp]
32 | (str (:name cp) ": "
33 | (:recomputed cp)
34 | " dependents " (:dependents cp)
35 | " depends on " (:depends-on cp)))
36 |
37 | (defn test-dynamic-dependencies []
38 | (with-fresh-store {}
39 | (let [a (det-cp :a true)
40 | b (det-cp :b (list :hello (gv a)))
41 | c (det-cp :c
42 | (do (println "Here")
43 | (if (gv a) (list (gv b) :c) :nope)))
44 | show-cps (fn []
45 | (println "Recomputed: " (:recomputed @*global-store*))
46 | (println "Newly created: " (:newly-created @*global-store*))
47 | (println "Possibly removed: " (:possibly-removed @*global-store*))
48 | (doseq [[name cp] (:choice-points @*global-store*)]
49 | (println (cp-str cp))))
50 | set-value! (fn [cp val]
51 | (assoc-in-store! [:choice-points (:name cp) :recomputed] val))
52 | refresh (fn [] (swap! *global-store* (constantly
53 | (fresh-state (:choice-points @*global-store*)))))]
54 | (show-cps)
55 | (refresh)
56 | (set-value! b :huhu)
57 | (recompute-value c)
58 | (show-cps)
59 | (refresh)
60 | (set-value! a false)
61 | (recompute-value c)
62 | (show-cps)
63 | (refresh)
64 | (set-value! b :nowhere)
65 | (recompute-value c)
66 | (show-cps)
67 | (refresh)
68 | (swap! *global-store* update-in [:choice-points] dissoc (:name b))
69 | (set-value! a true)
70 | (recompute-value c)
71 | (show-cps))))
72 |
73 | (defn test-bayes-net [bayes-net]
74 | (density (take 25000 (monte-carlo-sampling bayes-net))))
75 |
76 | (defn test-topsort []
77 | (with-fresh-store {}
78 | (let [a (det-cp :a :a)
79 | b (det-cp :b (list :b (gv a)))
80 | c (det-cp :c (list :c (gv b) (gv a)))
81 | p (flip-cp :p (if (gv a) 0.2 0.8))
82 | d (det-cp :d (list :d (gv p) (gv c)))
83 | e (det-cp :e (list :e (gv p)))
84 |
85 | show-cps (fn []
86 | (doseq [[name cp] (fetch-store :choice-points)]
87 | (println (cp-str cp))))]
88 | ;; Not using topological sort any more, but all choice points up-to data after propagation
89 | (show-cps)
90 | (assoc-in-store! [:choice-points (:name a) :recomputed] :aa)
91 | (println "Updated "
92 | (propagate-change-to
93 | (fetch-store :choice-points (get (:name a)) :dependents))
94 | " choice points")
95 | (show-cps))))
96 |
97 |
98 | (defn topsort-bug []
99 | ;; Illustrates a bug resulting from update in topological order if order changes
100 | ;; during the re-evaluation!!!
101 | ;; DONE: Should be fixed now ... but unnecessary recomputations triggered
102 | (with-fresh-store {}
103 | (let [c (atom 0)
104 | a (det-cp :a true)
105 | b (det-cp :b (if (gv a)
106 | :b-true
107 | (list :a-false (gv @c))))
108 | show-cps (fn []
109 | (doseq [[name cp] (:choice-points @*global-store*)]
110 | (println (cp-str cp))))
111 | set-value! (fn [cp val]
112 | (assoc-in-store! [:choice-points (:name cp) :recomputed] val))
113 | refresh (fn [] (swap! *global-store* (constantly
114 | (fresh-state (:choice-points @*global-store*)))))]
115 | ;; examples requires cyclic dependency ... so maybe cannot arise otherwise???
116 | (swap! c (fn [_] (det-cp :c (if (gv a)
117 | (list :a-true (gv b))
118 | :c-false))))
119 |
120 | (show-cps)
121 | (refresh)
122 | (set-value! a false)
123 | (println "Updated "
124 | (propagate-change-to
125 | (fetch-store :choice-points (get (:name a)) :dependents))
126 | " choice points")
127 | ;; this works nicely now
128 | (show-cps)
129 | ;; so flip a back again
130 | (set-value! a true)
131 | (println "Updated "
132 | (propagate-change-to
133 | (fetch-store :choice-points (get (:name a)) :dependents))
134 | " choice points")
135 | (show-cps))))
136 |
137 | (defn test-retracts-net
138 | "Somewhat involved example of a changing topology, to test dependency tracking and sampling."
139 | []
140 | (let [root (flip-cp :root 0.5)
141 | path-left (flip-cp :left (do (gv root) 0.5))
142 | path-right (flip-cp :right (do (gv root) 0.5))]
143 | (det-cp :result
144 | (if (gv root)
145 | [:left (gv path-left)]
146 | [:right (gv path-right)]))))
147 |
--------------------------------------------------------------------------------
/src/probabilistic_clojure/monadic/api.clj:
--------------------------------------------------------------------------------
1 | ;;; Copyright (C) 2011 Nils Bertschinger
2 |
3 | ;;; This file is part of Probabilistic-Clojure
4 |
5 | ;;; Probabilistic-Clojure is free software: you can redistribute it and/or modify
6 | ;;; it under the terms of the GNU Lesser General Public License as published by
7 | ;;; the Free Software Foundation, either version 3 of the License, or
8 | ;;; (at your option) any later version.
9 |
10 | ;;; Probabilistic-Clojure is distributed in the hope that it will be useful,
11 | ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | ;;; GNU Lesser General Public License for more details.
14 |
15 | ;;; You should have received a copy of the GNU Lesser General Public License
16 | ;;; along with Probabilistic-Clojure. If not, see .
17 |
18 | (ns
19 | ^{:author "Nils Bertschinger"
20 | :doc "This library implements a version of the probability monad
21 | which uses Metropolis Hastings sampling.
22 | The system allows to condition and memoize probabilistic choice points and
23 | can be extended by user defined distributions."}
24 | probabilistic-clojure.monadic.api
25 | (:use [clojure.algo.monads :only (defmonad)]
26 | [probabilistic-clojure.utils.sampling :only (sample-from normalize)]
27 | [probabilistic-clojure.utils.stuff :only (ensure-list error)]))
28 |
29 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
30 | ;;;
31 | ;;; Basic data structures
32 | ;;;
33 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
34 |
35 | (defrecord ^{:doc "Basic data structure for random choice points"}
36 | ChoicePoint
37 | [sampler get-log-prob proposer get-log-proposal-prob])
38 |
39 | (defrecord ^{:doc "Entry holding information about random choices encountered
40 | during a run of probabilistic programs"}
41 | DBentry
42 | [value log-lik status type params choice-point])
43 |
44 | (defn- activate [database addr]
45 | (assoc-in database [addr :status] :active))
46 |
47 | (defn- inactivate-all [database]
48 | (into {} (for [[addr entry] database]
49 | [addr (assoc entry :status :inactive)])))
50 |
51 | (defn- clean-db-back
52 | "Runs through the database to remove all inactive choice points. Returns the cleaned
53 | database as well as the log-likelihood of the removed choice points which is needed to
54 | calculate the backward probability"
55 | [database]
56 | (reduce (fn [[db log-bwd-prob] [addr entry]]
57 | (if (= (:status entry) :active)
58 | [(assoc db addr entry) log-bwd-prob]
59 | [db (+ log-bwd-prob (apply (:get-log-prob (:choice-point entry))
60 | (:value entry) (:params entry)))]))
61 | [{} 0] (seq database)))
62 |
63 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
64 | ;;;
65 | ;;; The monadic interface
66 | ;;;
67 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
68 |
69 | (def log-prob-zero (Math/log 0))
70 |
71 | (defn- m-result-MH [v]
72 | (fn [addr database log-fwd-prob log-lik mems]
73 | ;; there is no choice here, so just return everything directly
74 | [v log-lik database log-fwd-prob mems]))
75 |
76 | (def m-zero-MH
77 | (fn [addr database log-fwd-prob log-lik mems]
78 | ;; invalidate this trace
79 | [::invalid log-prob-zero database log-fwd-prob mems]))
80 |
81 | (defn invalid? [v]
82 | (= v ::invalid))
83 |
84 | (defn- m-bind-MH [m f]
85 | (fn [addr database log-fwd-prob log-lik mems]
86 | ;; here we first run the monad m and then
87 | ;; plug the values into the continuation f
88 | ;; (compare the state monad)
89 | (let [[v log-lik database log-fwd-prob mems]
90 | (m (cons "BIND-M" addr) database log-fwd-prob log-lik mems)]
91 | (if (invalid? v)
92 | (m-zero-MH (cons "BIND-F" addr) database log-fwd-prob log-lik mems)
93 | ((f v) (cons "BIND-F" addr) database log-fwd-prob log-lik mems)))))
94 |
95 | ;; Definition of our monad (note that no implementation of m-plus is provided!)
96 | (defmonad probabilistic-sampling-m
97 | [m-result m-result-MH
98 | m-bind m-bind-MH
99 | m-zero m-zero-MH])
100 |
101 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
102 | ;;;
103 | ;;; User functions for defining choice points and running probabilistic programs
104 | ;;;
105 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
106 |
107 | (defn make-choice-point
108 | "Allows to define a new probabilistic choice point by providing a function
109 | for sampling and calculating the log-likelihood.
110 | See the source code of flip for an example."
111 | ([name params sampler get-log-prob]
112 | (make-choice-point name params
113 | sampler get-log-prob
114 | ;; provide a default proposer that simply samples from the distribution
115 | (fn [val & args] (apply sampler args))
116 | (fn [new-val old-val & args] (apply get-log-prob new-val args))))
117 | ([name params sampler get-log-prob proposer get-log-proposal-prob]
118 | (fn [addr database log-fwd-prob log-lik mems]
119 | ;; this function runs the choice-point with entries from the database and updates the trace
120 | (let [addr (cons name addr)
121 | create-new-randomness
122 | (fn []
123 | (let [val (apply sampler params)
124 | ll (apply get-log-prob val params)]
125 | [val
126 | (+ log-lik ll)
127 | (assoc database addr
128 | (DBentry. val ll :active name params
129 | (ChoicePoint. sampler get-log-prob proposer get-log-proposal-prob)))
130 | (+ log-fwd-prob ll) mems]))]
131 | (if (contains? database addr)
132 | (let [entry (database addr)]
133 | (if (= (:params entry) params)
134 | ;; we found an exact match, so just lookup the value
135 | (let [val (:value entry)
136 | ll (apply (:get-log-prob (:choice-point entry)) val params)]
137 | [val (+ log-lik ll) (activate database addr) log-fwd-prob mems])
138 | ;; no exact match, we have to reweight the trace
139 | (let [val (:value entry)
140 | ll (apply (:get-log-prob (:choice-point entry)) val params)]
141 | (if (= ll log-prob-zero)
142 | (create-new-randomness)
143 | [val (+ log-lik ll)
144 | (-> database
145 | (activate addr)
146 | (assoc-in [addr :log-lik] ll)
147 | (assoc-in [addr :params] params))
148 | log-fwd-prob mems]))))
149 | ;; not in database, create new randomness
150 | (create-new-randomness))))))
151 |
152 | (defn- get-trace [m-MH database]
153 | (m-MH (list "TOP") database 0 0 {}))
154 |
155 | (defn cond-data
156 | "Condition a choice point on the specified value.
157 | This function must be applied to an elementary random choice point, e.g. (flip 0.6).
158 | A trace running through this value is then weighted according to the likelihood of the data value."
159 | [choice val]
160 | (fn [addr database log-fwd-prob log-lik mems]
161 | (let [[[_ choice-entry] & more] (seq (get (get-trace choice {}) 2))
162 | choice-point (:choice-point choice-entry)
163 | ll (apply (:get-log-prob choice-point) val (:params choice-entry))]
164 | (when more ; ensure that its was called on an elementary choice point
165 | (error "Cond-data can only be called on an elementary choice point!"))
166 | [val (+ log-lik ll) database log-fwd-prob mems])))
167 |
168 | (defmacro mem
169 | "Memoize a MH monadic value on some given arguments, i.e. if the same arguments
170 | are encountered again it refers back to the original choice
171 | point which was established for these arguments in the trace, i.e.
172 | no new randomness is created in this case."
173 | [m-MH-form & add-args]
174 | `(fn [addr# database# log-fwd-prob# log-lik# mems#]
175 | (let [mem-addr# (list "MEMO" (str '~(first (ensure-list m-MH-form))) ~@(rest (ensure-list m-MH-form)) ~@add-args)
176 | ;; now just redirect the choice point to the new address
177 | ;; which identifies it according to its arguments
178 | [val# ll# db# lfp# ms#] (~m-MH-form mem-addr# database# log-fwd-prob# log-lik# mems#)]
179 | (if (contains? mems# mem-addr#)
180 | [val# log-lik# database# log-fwd-prob# (update-in ms# [mem-addr#] inc)]
181 | [val# ll# db# lfp# (assoc ms# mem-addr# 1)]))))
182 |
183 | ;; These two functions are used to select the next choice point to be proposed
184 | ;; They implement the heuristics that memoized choices should be tried more often
185 | ;; since they got reused several times
186 | (defn- select-prob-choice-dist [database mems]
187 | (normalize
188 | (into {} (for [[addr entry] database]
189 | [[addr entry] (if (contains? mems (rest addr))
190 | (mems (rest addr))
191 | 1)]))))
192 |
193 | (defn- calc-select-prob [addr database mems]
194 | (let [total (+ (count database) ; each entry gets weight one
195 | (reduce + (vals mems)) ; weight of mem-entries
196 | (- (count mems)))] ; but got double counted
197 | (if (contains? mems (rest addr))
198 | (/ (mems (rest addr)) total)
199 | (/ 1 total))))
200 |
201 | (def ^{:doc "Every *trace-verbose* steps sample-traces ouputs some status information.
202 | Can be set to false for no output."
203 | :dynamic true}
204 | *trace-verbose*
205 | 500)
206 |
207 | (defn- output? [idx]
208 | (and (number? *trace-verbose*)
209 | (= (mod idx *trace-verbose*) 0)))
210 |
211 | (defn sample-traces
212 | "The main routine implementing Metropolis Hastings sampling. Returns a lazy
213 | sequence of samples when called on a monadic value from this library.
214 | Burn-in and thinning can be obtained using for example drop and keep-indexed respectively."
215 | ([m-MH]
216 | (println "Trying to find valid trace ...")
217 | (loop [[val log-lik database _fwd-ll_ mems] (get-trace m-MH {})]
218 | (if (or (invalid? val) (= log-lik log-prob-zero))
219 | (recur (get-trace m-MH {}))
220 | (do (println "Starting MH-sampling.")
221 | (sample-traces m-MH database mems log-lik val 1 1)))))
222 | ([m-MH database mems log-lik val idx num-acc]
223 | (when (output? idx)
224 | (println (str idx ": value " val " with log. likelihood " log-lik))
225 | (println (str "Accepted " num-acc " out of last " *trace-verbose* " proposals")))
226 | (let [num-acc (if (output? idx) 0 num-acc)
227 | [addr entry] (sample-from (select-prob-choice-dist database mems))
228 | prop-val (apply (:proposer (:choice-point entry)) (:value entry) (:params entry))
229 | ll-prop-val (apply (:get-log-proposal-prob (:choice-point entry))
230 | prop-val (:value entry) (:params entry))
231 | ll-val (apply (:get-log-proposal-prob (:choice-point entry))
232 | (:value entry) prop-val (:params entry))
233 | [next-val next-log-lik next-database log-fwd-prob next-mems]
234 | (get-trace m-MH
235 | (-> (inactivate-all database)
236 | (assoc-in [addr :value] prop-val)
237 | (assoc-in [addr :log-lik]
238 | (apply (:get-log-prob (:choice-point entry))
239 | prop-val (:params entry)))))]
240 | (if (invalid? next-val) ; trace was rejected => retry
241 | (lazy-seq (cons val (sample-traces m-MH database mems log-lik val (inc idx) num-acc)))
242 | (let [[next-database log-bwd-prob] (clean-db-back next-database)]
243 | (if (< (Math/log (rand))
244 | (+ (- next-log-lik log-lik)
245 | (- (Math/log (calc-select-prob addr next-database next-mems))
246 | (Math/log (calc-select-prob addr database mems)))
247 | (- ll-val ll-prop-val)
248 | (- log-bwd-prob log-fwd-prob)))
249 | (lazy-seq (cons next-val (sample-traces m-MH next-database next-mems
250 | next-log-lik next-val
251 | (inc idx) (inc num-acc))))
252 | (lazy-seq (cons val (sample-traces m-MH database mems log-lik val (inc idx) num-acc)))))))))
253 |
254 | (defn monte-carlo-samples
255 | "Run the probabilistic program repeatedly to obtain samples. Note that this is more like
256 | rejection sampling and usually less efficient than sample-traces."
257 | [m-MH]
258 | (lazy-seq
259 | (cons (first (get-trace m-MH {}))
260 | (monte-carlo-samples m-MH))))
261 |
262 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
263 | ;;;
264 | ;;; Basic example of how to define a probabilistic choice point
265 | ;;;
266 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
267 |
268 | (defn flip
269 | "A binary random choice which is true with probability p.
270 | Provides a good example of how user-defined choice points look like."
271 | [p]
272 | (make-choice-point "FLIP" [p]
273 | (fn [p] (< (rand) p)) ; the sampling function
274 | (fn [b p] (Math/log (if b p (- 1 p)))) ; calculates the log-likelihood of outcome b
275 | ;; The proposer (consisting of theses two functions) is optional
276 | (fn [b p] (not b))
277 | (fn [new-b old-b p] (Math/log 1))))
278 |
--------------------------------------------------------------------------------
/src/probabilistic_clojure/monadic/demos.clj:
--------------------------------------------------------------------------------
1 | ;;; Copyright (C) 2011 Nils Bertschinger
2 |
3 | ;;; This file is part of Probabilistic-Clojure
4 |
5 | ;;; Probabilistic-Clojure is free software: you can redistribute it and/or modify
6 | ;;; it under the terms of the GNU Lesser General Public License as published by
7 | ;;; the Free Software Foundation, either version 3 of the License, or
8 | ;;; (at your option) any later version.
9 |
10 | ;;; Probabilistic-Clojure is distributed in the hope that it will be useful,
11 | ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | ;;; GNU Lesser General Public License for more details.
14 |
15 | ;;; You should have received a copy of the GNU Lesser General Public License
16 | ;;; along with Probabilistic-Clojure. If not, see .
17 |
18 | (ns
19 | ^{:author "Nils Bertschinger"
20 | :doc "Demo of how the probability monad can be used.
21 | Also defines several useful probabilistic choice points and
22 | requires incanter for different distributions as well as the
23 | graphical output."}
24 | probabilistic-clojure.monadic.demos
25 | (:use [probabilistic-clojure.monadic.api
26 | :only (probabilistic-sampling-m make-choice-point cond-data mem sample-traces flip log-prob-zero)]
27 | [probabilistic-clojure.utils.sampling :only (density sample-from)]
28 | [probabilistic-clojure.utils.stuff :only (transpose)]
29 | [probabilistic-clojure.utils.finite-distributions :only (cond-dist-m normalize-cond choose)])
30 | (:use [clojure.algo.monads :only (domonad defmonadfn m-bind m-result with-monad)])
31 | (:use [incanter.core :only (gamma view)]
32 | [incanter.stats :only (sample-normal pdf-normal sample-dirichlet sample-beta pdf-beta mean)]
33 | [incanter.charts :only (histogram xy-plot add-lines)]))
34 |
35 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
36 | ;;;
37 | ;;; First a simple Bayes net as found in many introductory texts
38 | ;;;
39 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
40 |
41 | (defmonadfn noisy-or [x y]
42 | (domonad
43 | [noise-x (flip 0.9)
44 | noise-y (flip 0.8)
45 | noise-z (flip 0.1)]
46 | (or (and x noise-x)
47 | (and y noise-y)
48 | noise-z)))
49 |
50 | (defmonadfn grass-bayes-net []
51 | (domonad
52 | [rain (flip 0.3)
53 | sprinkler (flip 0.5)
54 | grass-is-wet (noisy-or rain sprinkler)
55 | :when grass-is-wet]
56 | rain))
57 |
58 | (defn run-grass-example [num-samples]
59 | (with-monad probabilistic-sampling-m
60 | (let [rain (density (take num-samples (sample-traces (grass-bayes-net))))]
61 | (println "Given grass-is-wet the probability for rain is " (get rain true))
62 | rain)))
63 |
64 | (defn solve-grass-example []
65 | (with-redefs [flip (fn [p] (choose p true (- 1 p) false))]
66 | (with-monad cond-dist-m
67 | (normalize-cond (grass-bayes-net)))))
68 |
69 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
70 | ;;;
71 | ;;; Some more probabilistic choice points as required by the mixture example
72 | ;;;
73 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
74 |
75 | (defn discrete [dist]
76 | (make-choice-point "DISCRETE" [dist]
77 | (fn [dist] (sample-from dist))
78 | (fn [x dist]
79 | (if (contains? dist x)
80 | (Math/log (dist x))
81 | log-prob-zero))))
82 |
83 | (defn gaussian [mu sdev]
84 | (let [proposal-sd 0.7]
85 | (make-choice-point "GAUSSIAN" [mu sdev]
86 | (fn [mu sdev] (sample-normal 1 :mean mu :sd sdev))
87 | (fn [x mu sdev] (Math/log (pdf-normal x :mean mu :sd sdev)))
88 | (fn [x mu sdev] (sample-normal 1 :mean x :sd proposal-sd))
89 | (fn [new-x old-x mu sdev]
90 | (Math/log (pdf-normal new-x :mean old-x :sd proposal-sd))))))
91 |
92 | (defn pdf-dirichlet [ps alphas]
93 | (let [norm (/ (reduce * (map gamma alphas))
94 | (gamma (reduce + alphas)))]
95 | (/ (reduce * (map (fn [p a] (Math/pow p (- a 1))) ps alphas))
96 | norm)))
97 |
98 | (defn dirichlet [alphas]
99 | (let [proposal-alphas (fn [alphas]
100 | (for [a alphas] (* 18 a)))]
101 | (make-choice-point "DIRICHLET" [alphas]
102 | (fn [alphas] (first (sample-dirichlet 2 alphas)))
103 | (fn [ps alphas] (Math/log (pdf-dirichlet ps alphas)))
104 | (fn [ps alphas] (first (sample-dirichlet 2 (proposal-alphas ps))))
105 | (fn [new-ps old-ps alphas]
106 | (Math/log (pdf-dirichlet new-ps (proposal-alphas old-ps)))))))
107 |
108 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
109 | ;;;
110 | ;;; Fitting of a mixture model to illustrate how mem can be used to share randomness
111 | ;;;
112 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
113 |
114 | (defn generate-data []
115 | (let [mu (fn [] (sample-from {-5 0.2, 0 0.7, 8 0.1}))]
116 | (lazy-seq (cons (sample-normal 1 :mean (mu))
117 | (generate-data)))))
118 |
119 | (def data (take 42 (generate-data)))
120 |
121 | (defn fit-components [data comp-weights mu-comps]
122 | (with-monad probabilistic-sampling-m
123 | (if (empty? data) ; are we done yet?
124 | (m-result ())
125 | (domonad
126 | [comp (discrete {:a (nth comp-weights 0), :b (nth comp-weights 1), :c (nth comp-weights 2)})
127 | ;; first draw a component for this data point
128 | :let [mu-comp (mu-comps comp)]
129 | ;; then condition a Gaussian for this component on the observed data point
130 | obs (cond-data (gaussian mu-comp 1) (first data))
131 | assignment (fit-components (rest data) comp-weights mu-comps)]
132 | (cons comp assignment)))))
133 |
134 | (defn mixture
135 | "Basic example of a mixture model."
136 | [data]
137 | (domonad probabilistic-sampling-m
138 | [ca (gaussian 0 15) ; draw means of three components from a Gaussian prior
139 | cb (gaussian 0 15)
140 | cc (gaussian 0 15)
141 | comp-weights (dirichlet [1 1 1]) ; draw component proportions from a Dirichlet prior
142 | :let [mu-comps {:a ca :b cb :c cc}]
143 | assignment (fit-components data comp-weights mu-comps)] ; assign each data point to these components
144 | [mu-comps comp-weights assignment]))
145 |
146 | (defn mixture-mem
147 | "The same model as in mixture, but simplified using mem to reuse random choices."
148 | [data]
149 | (with-monad probabilistic-sampling-m
150 | (if (empty? data)
151 | (m-result [{} [] ()])
152 | (domonad
153 | [comp-weights (mem (dirichlet [10 10 10])) ; mem ensures that the component proportions
154 | ; are the same for each data point
155 | comp (discrete {:a (nth comp-weights 0), :b (nth comp-weights 1), :c (nth comp-weights 2)})
156 | mu-comp (mem (gaussian 0 15) comp) ; similarly the means of the same component are shared
157 | obs (cond-data (gaussian mu-comp 1) (first data)) ; condition on the observed data
158 | [other-mus cws assignment] (mixture-mem (rest data))]
159 | [(assoc other-mus comp mu-comp) comp-weights (cons comp assignment)]))))
160 |
161 | (defn test-mixture [model]
162 | (let [data-plot (histogram data :title "Dataset" :nbins 50 :density true)
163 | samples (take 200 (drop 8000 (sample-traces (model data)))) ; burn-in of 8000 samples
164 | comp-mus (map first samples)
165 | comp-weights (map second samples)]
166 | (let [xs (range -10 10 0.01)
167 | ;; average over the last samples ... even though this should not be done!!!
168 | weights (map mean (transpose comp-weights))
169 | mus (map mean (transpose (for [mus comp-mus] [(:a mus) (:b mus) (:c mus)])))]
170 | (doto data-plot
171 | (add-lines xs (map (fn [x] (* (nth weights 0) (pdf-normal x :mean (nth mus 0)))) xs))
172 | (add-lines xs (map (fn [x] (* (nth weights 1) (pdf-normal x :mean (nth mus 1)))) xs))
173 | (add-lines xs (map (fn [x] (* (nth weights 2) (pdf-normal x :mean (nth mus 2)))) xs))
174 | view)
175 | [weights mus])))
176 |
177 | (comment
178 | (test-mixture mixture)
179 | (test-mixture mixture-mem))
180 |
181 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
182 | ;;;
183 | ;;; Finally, extend this to a Dirichlet process such that also the number of
184 | ;;; components is learned
185 | ;;;
186 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
187 |
188 | ;; first a Beta distributed choice point is needed
189 | (defn beta [alpha beta]
190 | (make-choice-point "BETA" [alpha beta]
191 | (fn [alpha beta] (sample-beta 1 :alpha alpha :beta beta))
192 | (fn [x alpha beta] (Math/log (pdf-beta x :alpha alpha :beta beta)))))
193 |
194 | ;; this implements the stick breaking construction
195 | ;; note the use of mem to reuse randomness
196 | (defn pick-a-stick [alpha idx]
197 | (domonad probabilistic-sampling-m
198 | [stick (mem (beta 1 alpha) idx)
199 | stop (flip stick)
200 | num (if stop
201 | (m-result idx)
202 | (pick-a-stick alpha (inc idx)))]
203 | num))
204 |
205 | (defn dirichlet-process
206 | "A Dirichlet process with parameter alpha and base measure base."
207 | [alpha base]
208 | (domonad probabilistic-sampling-m
209 | [idx (pick-a-stick alpha 1)
210 | val (mem base idx)]
211 | val))
212 |
213 | (defn mixture-DP
214 | "A Gaussian Dirichlet process mixture model."
215 | [alpha data]
216 | (with-monad probabilistic-sampling-m
217 | (if (empty? data)
218 | (m-result [0 {} ()])
219 | (domonad
220 | [mu-comp (dirichlet-process alpha (gaussian 0 15))
221 | obs (cond-data (gaussian mu-comp 1) (first data))
222 | [num-comp comp-mus assignment] (mixture-DP alpha (rest data))]
223 | (let [comp-idx (if (contains? comp-mus mu-comp)
224 | (comp-mus mu-comp)
225 | (inc num-comp))
226 | comp-mus (assoc comp-mus mu-comp comp-idx)]
227 | [(count comp-mus) comp-mus (cons comp-idx assignment)])))))
228 |
229 | (defn plot-DP-fit [data res]
230 | (let [data-plot (histogram data :nbins 50 :density true)
231 | [num-comp mus assignment] res
232 | weights (density assignment)
233 | xs (range -15 15 0.01)]
234 | (doseq [[mu idx] (seq mus)]
235 | (add-lines data-plot xs (map (fn [x] (* (weights idx) (pdf-normal x :mean mu))) xs)))
236 | (add-lines data-plot xs (map (fn [x] (reduce + (for [[mu idx] (seq mus)]
237 | (* (weights idx) (pdf-normal x :mean mu)))))
238 | xs))
239 | (view data-plot)))
240 |
241 | (defn test-DP [alpha n]
242 | (let [res (sample-traces (mixture-DP alpha data))]
243 | (loop [x res, i 0]
244 | (when (not (> i n))
245 | (when (= (mod i 2500) 0)
246 | (plot-DP-fit data (first x)))
247 | (recur (rest x) (inc i))))))
248 |
249 | (comment
250 | (test-DP 1.0 7500))
251 |
--------------------------------------------------------------------------------
/src/probabilistic_clojure/original/demos.clj:
--------------------------------------------------------------------------------
1 | ;;; Copyright (C) 2011 Nils Bertschinger
2 |
3 | ;;; This file is part of Probabilistic-Clojure
4 |
5 | ;;; Probabilistic-Clojure is free software: you can redistribute it and/or modify
6 | ;;; it under the terms of the GNU Lesser General Public License as published by
7 | ;;; the Free Software Foundation, either version 3 of the License, or
8 | ;;; (at your option) any later version.
9 |
10 | ;;; Probabilistic-Clojure is distributed in the hope that it will be useful,
11 | ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | ;;; GNU Lesser General Public License for more details.
14 |
15 | ;;; You should have received a copy of the GNU Lesser General Public License
16 | ;;; along with Probabilistic-Clojure. If not, see .
17 |
18 | (ns probabilistic.demos
19 | (:use probabilistic.metropolis-hastings)
20 | (:use [clojure.contrib.monads :only (domonad m-bind m-result with-monad)])
21 | (:use [incanter.core :only (view)]
22 | [incanter.stats :only (sample-normal pdf-normal mean sample-beta pdf-beta)]
23 | [incanter.charts :only (histogram xy-plot add-lines)]))
24 |
25 | (in-ns 'probabilistic.demos)
26 |
27 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
28 | ;;;
29 | ;;; First a simple Bayes net as found in many introductory texts
30 | ;;;
31 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
32 |
33 | (defn noisy-or [x y]
34 | (domonad probabilistic-sampling-m
35 | [noise-x (flip 0.9)
36 | noise-y (flip 0.8)
37 | noise-z (flip 0.1)]
38 | (or (and x noise-x)
39 | (and y noise-y)
40 | noise-z)))
41 |
42 | (defn grass-bayes-net []
43 | (domonad probabilistic-sampling-m
44 | [rain (flip 0.3)
45 | sprinkler (flip 0.5)
46 | grass-is-wet (noisy-or rain sprinkler)
47 | :when grass-is-wet]
48 | rain))
49 |
50 | (defn density [samples]
51 | (let [freqs (frequencies samples)
52 | total (reduce + (vals freqs))]
53 | (into {} (for [[k v] freqs] [k (float (/ v total))]))))
54 |
55 | (density (take 10000 (sample-traces (grass-bayes-net))))
56 |
57 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
58 | ;;;
59 | ;;; Fitting of a mixture model to illustrate how mem can be used to share randomness
60 | ;;;
61 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
62 |
63 | (defn generate-data []
64 | (let [mu (fn [] (sample-from {-5 0.2, 0 0.7, 8 0.1}))]
65 | (lazy-seq (cons (sample-normal 1 :mean (mu))
66 | (generate-data)))))
67 |
68 | (def data (take 42 (generate-data)))
69 |
70 | (defn fit-components [data comp-weights mu-comps]
71 | (with-monad probabilistic-sampling-m
72 | (if (empty? data)
73 | (m-result ())
74 | (domonad
75 | [comp (discrete {:a (nth comp-weights 0), :b (nth comp-weights 1), :c (nth comp-weights 2)})
76 | :let [mu-comp (mu-comps comp)]
77 | obs (cond-data (gaussian mu-comp 1) (first data))
78 | assignment (fit-components (rest data) comp-weights mu-comps)]
79 | (cons comp assignment)))))
80 |
81 | (defn mixture [data]
82 | (domonad probabilistic-sampling-m
83 | [ca (gaussian 0 15)
84 | cb (gaussian 0 15)
85 | cc (gaussian 0 15)
86 | comp-weights (dirichlet [1 1 1])
87 | :let [mu-comps {:a ca :b cb :c cc}]
88 | assignment (fit-components data comp-weights mu-comps)]
89 | [mu-comps comp-weights assignment]))
90 |
91 | (defn mixture-mem [data]
92 | (with-monad probabilistic-sampling-m
93 | (if (empty? data)
94 | (m-result [{} [] ()])
95 | (domonad
96 | [comp-weights (mem (dirichlet [10 10 10]))
97 | comp (discrete {:a (nth comp-weights 0), :b (nth comp-weights 1), :c (nth comp-weights 2)})
98 | mu-comp (mem (gaussian 0 15) comp)
99 | obs (cond-data (gaussian mu-comp 1) (first data))
100 | [other-mus cws assignment] (mixture-mem (rest data))]
101 | [(assoc other-mus comp mu-comp) comp-weights (cons comp assignment)]))))
102 |
103 | (defn transpose
104 | "Transpose a list of lists, i.e. (transpose [[1 2] [3 4] [5 6]]) = ((1 3 5) (2 4 6))"
105 | [lls]
106 | (apply map list lls))
107 |
108 | (defn test-mixture [model]
109 | (let [data-plot (histogram data :title "Dataset" :nbins 50 :density true)
110 | samples (take 2000 (drop 8000 (sample-traces (model data))))
111 | comp-mus (map first samples)
112 | comp-weights (map second samples)]
113 | (let [xs (range -10 10 0.01)
114 | weights (map mean (transpose comp-weights))
115 | mus (map mean (transpose (for [mus comp-mus] [(:a mus) (:b mus) (:c mus)])))]
116 | (doto data-plot
117 | (add-lines xs (map (fn [x] (* (nth weights 0) (pdf-normal x :mean (nth mus 0)))) xs))
118 | (add-lines xs (map (fn [x] (* (nth weights 1) (pdf-normal x :mean (nth mus 1)))) xs))
119 | (add-lines xs (map (fn [x] (* (nth weights 2) (pdf-normal x :mean (nth mus 2)))) xs))
120 | view)
121 | [weights mus])))
122 |
123 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
124 | ;;;
125 | ;;; Finally, extend this to a Dirichlet process such that also the number of
126 | ;;; components is learned
127 | ;;;
128 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
129 |
130 | (defn beta [alpha beta]
131 | (make-choice-point "BETA" [alpha beta]
132 | (fn [alpha beta] (sample-beta 1 :alpha alpha :beta beta))
133 | (fn [x alpha beta] (Math/log (pdf-beta x :alpha alpha :beta beta)))))
134 |
135 | (defn pick-a-stick [alpha idx]
136 | (domonad probabilistic-sampling-m
137 | [stick (mem (beta 1 alpha) idx)
138 | stop (flip stick)
139 | num (if stop
140 | (m-result idx)
141 | (pick-a-stick alpha (inc idx)))]
142 | num))
143 |
144 | (defn dirichlet-process [alpha base]
145 | (domonad probabilistic-sampling-m
146 | [idx (pick-a-stick alpha 1)
147 | val (mem base idx)]
148 | val))
149 |
150 | (defn mixture-DP [alpha data]
151 | (with-monad probabilistic-sampling-m
152 | (if (empty? data)
153 | (m-result [0 {} ()])
154 | (domonad
155 | [mu-comp (dirichlet-process alpha (gaussian 0 15))
156 | obs (cond-data (gaussian mu-comp 1) (first data))
157 | [num-comp comp-mus assignment] (mixture-DP alpha (rest data))]
158 | (let [comp-idx (if (contains? comp-mus mu-comp)
159 | (comp-mus mu-comp)
160 | (inc num-comp))
161 | comp-mus (assoc comp-mus mu-comp comp-idx)]
162 | [(count comp-mus) comp-mus (cons comp-idx assignment)])))))
163 |
164 | (defn plot-DP-fit [data res]
165 | (let [data-plot (histogram data :nbins 50 :density true)
166 | [num-comp mus assignment] res
167 | weights (density assignment)
168 | xs (range -15 15 0.01)]
169 | (doseq [[mu idx] (seq mus)]
170 | (add-lines data-plot xs (map (fn [x] (* (weights idx) (pdf-normal x :mean mu))) xs)))
171 | (add-lines data-plot xs (map (fn [x] (reduce + (for [[mu idx] (seq mus)]
172 | (* (weights idx) (pdf-normal x :mean mu)))))
173 | xs))
174 | (view data-plot)))
175 |
176 | (defn test-DP [alpha n]
177 | (let [res (sample-traces (mixture-DP alpha data))]
178 | (loop [x res, i 0]
179 | (when (not (> i n))
180 | (when (= (mod i 2500) 0)
181 | (plot-DP-fit data (first x)))
182 | (recur (rest x) (inc i))))))
--------------------------------------------------------------------------------
/src/probabilistic_clojure/original/metropolis_hastings.clj:
--------------------------------------------------------------------------------
1 | ;;; Copyright (C) 2011 Nils Bertschinger
2 |
3 | ;;; This file is part of Probabilistic-Clojure
4 |
5 | ;;; Probabilistic-Clojure is free software: you can redistribute it and/or modify
6 | ;;; it under the terms of the GNU Lesser General Public License as published by
7 | ;;; the Free Software Foundation, either version 3 of the License, or
8 | ;;; (at your option) any later version.
9 |
10 | ;;; Probabilistic-Clojure is distributed in the hope that it will be useful,
11 | ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | ;;; GNU Lesser General Public License for more details.
14 |
15 | ;;; You should have received a copy of the GNU Lesser General Public License
16 | ;;; along with Probabilistic-Clojure. If not, see .
17 |
18 | (ns
19 | ^{:author "Nils Bertschinger"
20 | :doc "This library implements Metropolis-Hastings sampling for
21 | the probability monad. The system allows to condition and memoize
22 | choice points and can be extended by user defined probabilistic choices."}
23 | probabilistic.metropolis-hastings
24 | (:use [clojure.contrib.monads :only (defmonad)])
25 | (:use [incanter.core :only (gamma)]
26 | [incanter.stats :only (sample-normal pdf-normal sample-dirichlet sample-beta pdf-beta)]))
27 |
28 | (in-ns 'probabilistic.metropolis-hastings)
29 |
30 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
31 | ;;;
32 | ;;; Basic data structures and utilities
33 | ;;;
34 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
35 |
36 | (defrecord ChoicePoint
37 | [sampler get-log-prob proposer get-log-proposal-prob])
38 |
39 | (defrecord DBentry
40 | [value log-lik status type params choice-point])
41 |
42 | (defn- activate [database addr]
43 | (assoc-in database [addr :status] :active))
44 |
45 | (defn- inactivate-all [database]
46 | (into {} (for [[addr entry] database]
47 | [addr (assoc entry :status :inactive)])))
48 |
49 | (defn- clean-db-back [database]
50 | (reduce (fn [[db log-bwd-prob] [addr entry]]
51 | (if (= (:status entry) :active)
52 | [(assoc db addr entry) log-bwd-prob]
53 | [db (+ log-bwd-prob (apply (:get-log-prob (:choice-point entry))
54 | (:value entry) (:params entry)))]))
55 | [{} 0] (seq database)))
56 |
57 | (defn- ensure-list [x]
58 | (if (seq? x) x (list x)))
59 |
60 | (defn sample-from
61 | "Sample from a discrete distribution implemented as a hash-map from
62 | values to probabilities."
63 | [dist]
64 | (when (seq dist)
65 | (let [total (reduce + (vals dist))
66 | threshold (rand)]
67 | (loop [cum-p 0
68 | [[v p] & more] (seq dist)]
69 | (if (< threshold (+ cum-p p))
70 | v
71 | (recur (+ cum-p p) more))))))
72 |
73 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
74 | ;;;
75 | ;;; The monadic interface
76 | ;;;
77 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
78 |
79 | (def log-prob-zero (Math/log 0))
80 |
81 | (defn- m-result-MH [v]
82 | (fn [addr database log-fwd-prob log-lik mems]
83 | ;; there is no choice here, so just return everything directly
84 | [v log-lik database log-fwd-prob mems]))
85 |
86 | (def m-zero-MH
87 | (fn [addr database log-fwd-prob log-lik mems]
88 | ;; invalidate this trace
89 | [:invalid log-prob-zero database log-fwd-prob mems]))
90 |
91 | (defn- m-bind-MH [m f]
92 | (fn [addr database log-fwd-prob log-lik mems]
93 | ;; here we first run the monad m and then
94 | ;; plug the values into the continuation f
95 | (let [[v log-lik database log-fwd-prob mems]
96 | (m (cons "BIND-M" addr) database log-fwd-prob log-lik mems)]
97 | (if (= v :invalid)
98 | (m-zero-MH (cons "BIND-F" addr) database log-fwd-prob log-lik mems)
99 | ((f v) (cons "BIND-F" addr) database log-fwd-prob log-lik mems)))))
100 |
101 | ;; Definition of our monad (note that no implementation of m-plus is provided!)
102 | (defmonad probabilistic-sampling-m
103 | [m-result m-result-MH
104 | m-bind m-bind-MH
105 | m-zero m-zero-MH])
106 |
107 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
108 | ;;;
109 | ;;; User functions for defining choice points and running probabilistic programs
110 | ;;;
111 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
112 |
113 | (defn make-choice-point
114 | "Allows to define a new probabilistic choice point by providing a function
115 | for sampling and calculating the log-likelihood.
116 | See the source code of flip for an example."
117 | ([name params sampler get-log-prob]
118 | (make-choice-point name params
119 | sampler get-log-prob
120 | (fn [val & args] (apply sampler args))
121 | (fn [new-val old-val & args] (apply get-log-prob new-val args))))
122 | ([name params sampler get-log-prob proposer get-log-proposal-prob]
123 | (fn [addr database log-fwd-prob log-lik mems]
124 | ;; this function runs the choice-point with entries from the database and updates the trace
125 | (let [addr (cons name addr)
126 | create-new-randomness
127 | (fn []
128 | (let [val (apply sampler params)
129 | ll (apply get-log-prob val params)]
130 | [val
131 | (+ log-lik ll)
132 | (assoc database addr
133 | (DBentry. val ll :active name params
134 | (ChoicePoint. sampler get-log-prob proposer get-log-proposal-prob)))
135 | (+ log-fwd-prob ll) mems]))]
136 | (if (contains? database addr)
137 | (let [entry (database addr)]
138 | (if (= (:params entry) params)
139 | ;; we found an exact match, so just lookup the value
140 | (let [val (:value entry)
141 | ll (apply (:get-log-prob (:choice-point entry)) val params)]
142 | [val (+ log-lik ll) (activate database addr) log-fwd-prob mems])
143 | ;; no exact match, we have to reweight the trace
144 | (let [val (:value entry)
145 | ll (apply (:get-log-prob (:choice-point entry)) val params)]
146 | (if (= ll log-prob-zero)
147 | (create-new-randomness)
148 | [val (+ log-lik ll)
149 | (-> database
150 | (activate addr)
151 | (assoc-in [addr :log-lik] ll)
152 | (assoc-in [addr :params] params))
153 | log-fwd-prob mems]))))
154 | ;; not in database, create new randomness
155 | (create-new-randomness))))))
156 |
157 | (defn- get-trace [m-MH database]
158 | (m-MH (list "TOP") database 0 0 {}))
159 |
160 | (defn cond-data
161 | "Condition on a specific value of data.
162 | This function must be applied to an elementary random choice point, e.g. (flip 0.6).
163 | A trace running through this value is then weighted according to the likelihood of the data value."
164 | [choice val]
165 | (fn [addr database log-fwd-prob log-lik mems]
166 | (let [[[_ choice-entry] & more] (seq (get (get-trace choice {}) 2))
167 | choice-point (:choice-point choice-entry)
168 | ll (apply (:get-log-prob choice-point) val (:params choice-entry))]
169 | (assert (nil? more)) ; ensure that its was called on an elementary choice point
170 | [val (+ log-lik ll) database log-fwd-prob mems])))
171 |
172 | (defmacro mem
173 | "Memoize a MH monadic value on some given arguments, i.e. if the same arguments
174 | are encountered again it refers back to the original choice
175 | point which was established for these arguments in the trace."
176 | [m-MH-form & add-args]
177 | `(fn [addr# database# log-fwd-prob# log-lik# mems#]
178 | (let [mem-addr# (list "MEMO" (str '~(first (ensure-list m-MH-form))) ~@(rest (ensure-list m-MH-form)) ~@add-args)
179 | ;; now just redirect the choice point to the new address
180 | ;; which identifies it according to its arguments
181 | [val# ll# db# lfp# ms#] (~m-MH-form mem-addr# database# log-fwd-prob# log-lik# mems#)]
182 | (if (contains? mems# mem-addr#)
183 | (do ;; (assert (= database# db#))
184 | [val# log-lik# database# log-fwd-prob# (update-in ms# [mem-addr#] inc)])
185 | [val# ll# db# lfp# (assoc ms# mem-addr# 1)]))))
186 |
187 | (defn sample-traces
188 | ([m-MH]
189 | (println "Trying to find valid trace ...")
190 | (loop [[val log-lik database mems] (get-trace m-MH {})]
191 | (if (or (= val :invalid) (= log-lik log-prob-zero))
192 | (recur (get-trace m-MH {}))
193 | (do (println "Starting MH-sampling.")
194 | (sample-traces m-MH database mems log-lik val 1 1)))))
195 | ([m-MH database mems log-lik val idx num-acc]
196 | (when (= (mod idx 500) 0)
197 | (println (str idx ": value " val " with log. likelihood " log-lik))
198 | (println (str "Accepted " num-acc " out of last 500 proposals")))
199 | (let [num-acc (if (= (mod idx 500) 0) 0 num-acc)
200 | [addr entry] (rand-nth (for [[addr entry] database,
201 | en (repeat (if (contains? mems (rest addr))
202 | (mems (rest addr))
203 | 1)
204 | entry)]
205 | [addr en]))
206 | prop-val (apply (:proposer (:choice-point entry)) (:value entry) (:params entry))
207 | ll-prop-val (apply (:get-log-proposal-prob (:choice-point entry))
208 | prop-val (:value entry) (:params entry))
209 | ll-val (apply (:get-log-proposal-prob (:choice-point entry))
210 | (:value entry) prop-val (:params entry))
211 | [next-val next-log-lik next-database log-fwd-prob next-mems]
212 | (get-trace m-MH
213 | (-> (inactivate-all database)
214 | (assoc-in [addr :value] prop-val)
215 | (assoc-in [addr :log-lik]
216 | (apply (:get-log-prob (:choice-point entry)) prop-val (:params entry)))))]
217 | (if (= next-val :invalid) ; trace was rejected => retry
218 | (lazy-seq (cons val (sample-traces m-MH database mems log-lik val (inc idx) num-acc)))
219 | ; (recur m-MH database log-lik val)
220 | (let [[next-database log-bwd-prob] (clean-db-back next-database)]
221 | (if (< (Math/log (rand))
222 | (+ (- next-log-lik log-lik)
223 | (Math/log (/ (count database) (count next-database)))
224 | (- ll-val ll-prop-val)
225 | (- log-bwd-prob log-fwd-prob)))
226 | (lazy-seq (cons next-val (sample-traces m-MH next-database next-mems
227 | next-log-lik next-val
228 | (inc idx) (inc num-acc))))
229 | (lazy-seq (cons val (sample-traces m-MH database mems log-lik val (inc idx) num-acc)))))))))
230 |
231 | (defn monte-carlo-sample [m-MH]
232 | (first (get-trace m-MH {})))
233 |
234 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
235 | ;;;
236 | ;;; Definitions of useful basic choice points
237 | ;;;
238 | ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
239 |
240 | (defn flip [p]
241 | (make-choice-point "FLIP" [p]
242 | (fn [p] (< (rand) p))
243 | (fn [b p] (Math/log (if b p (- 1 p))))
244 | (fn [b p] (not b))
245 | (fn [new-b old-b p] (Math/log 1))))
246 |
247 | (defn discrete [dist]
248 | (make-choice-point "DISCRETE" [dist]
249 | (fn [dist] (sample-from dist))
250 | (fn [x dist]
251 | (if (contains? dist x)
252 | (Math/log (dist x))
253 | log-prob-zero))))
254 |
255 | (defn gaussian [mu sdev]
256 | (let [proposal-sd 0.7]
257 | (make-choice-point "GAUSSIAN" [mu sdev]
258 | (fn [mu sdev] (sample-normal 1 :mean mu :sd sdev))
259 | (fn [x mu sdev] (Math/log (pdf-normal x :mean mu :sd sdev)))
260 | (fn [x mu sdev] (sample-normal 1 :mean x :sd proposal-sd))
261 | (fn [new-x old-x mu sdev]
262 | (Math/log (pdf-normal new-x :mean old-x :sd proposal-sd 0.7))))))
263 |
264 | (defn pdf-dirichlet [ps alphas]
265 | (let [norm (/ (reduce * (map gamma alphas))
266 | (gamma (reduce + alphas)))]
267 | (/ (reduce * (map (fn [p a] (Math/pow p (- a 1))) ps alphas))
268 | norm)))
269 |
270 | (defn dirichlet [alphas]
271 | (let [proposal-alphas (fn [alphas]
272 | (for [a alphas] (* 18 a)))]
273 | (make-choice-point "DIRICHLET" [alphas]
274 | (fn [alphas] (first (sample-dirichlet 2 alphas)))
275 | (fn [ps alphas] (pdf-dirichlet ps alphas))
276 | (fn [ps alphas] (first (sample-dirichlet 2 (proposal-alphas ps))))
277 | (fn [new-ps old-ps alphas]
278 | (Math/log (pdf-dirichlet new-ps (proposal-alphas old-ps)))))))
279 |
--------------------------------------------------------------------------------
/src/probabilistic_clojure/original/scratch.clj:
--------------------------------------------------------------------------------
1 | ;;; These old sampling routines are now replaced by metropolis-hastings-sampling
2 |
3 | ;;; The actual Metropolis Hastings sampling
4 |
5 | (defn sampling-step [choice-points]
6 | (with-fresh-store choice-points
7 | (let [prob-choices (prob-choice-dist choice-points)
8 | selected-cp (choice-points (sample-from prob-choices))
9 | change-set (ordered-dependencies (:name selected-cp) choice-points)
10 | trace-log-lik (total-log-lik change-set choice-points)
11 |
12 | [prop-val fwd-log-lik bwd-log-lik]
13 | (propose selected-cp (:value selected-cp))]
14 | ;; (println "Proposing: " (:name selected-cp) ": " change-set)
15 | ;; (do (println :OLD) (doseq [cp (vals choice-points)] (println (probabilistic-clojure.embedded.tests/cp-str cp))))
16 | (assoc-in-store! [:choice-points (:name selected-cp) :value]
17 | prop-val)
18 | (propagate-change-to change-set)
19 | (if (trace-failed?)
20 | choice-points
21 | (let [;; _ (do (println :NEW) (doseq [cp (vals (fetch-store :choice-points))] (println (probabilistic-clojure.embedded.tests/cp-str cp))))
22 | _ (assert (clojure.set/subset? (set change-set) (fetch-store :recomputed)))
23 | _ (assert (= (fetch-store :recomputed) (union (set change-set) (fetch-store :newly-created)))
24 | (println "Aha " (str [(fetch-store :recomputed) (set change-set) (fetch-store :newly-created)])))
25 | removed-cps (remove-uncalled-choices)
26 | ;; _ (do (println :CLEAN) (doseq [cp (vals (fetch-store :choice-points))] (println (probabilistic-clojure.embedded.tests/cp-str cp))))
27 | _ (assert (empty? (clojure.set/intersection removed-cps (fetch-store :newly-created))))
28 | _ (let [new (set (keys (fetch-store :choice-points)))
29 | old (set (keys choice-points))]
30 | (assert (and (= new (difference (union old (fetch-store :newly-created))
31 | removed-cps))
32 | (= old (difference (union new removed-cps) (fetch-store :newly-created))))
33 | [old (fetch-store :newly-created) removed-cps new]))
34 |
35 | trace-log-lik (total-log-lik (union (set change-set) removed-cps)
36 | ;; (keys choice-points)
37 | ;; (difference (fetch-store :recomputed) (fetch-store :newly-created))
38 | choice-points)
39 | prop-trace-log-lik (total-log-lik ;; (keys (fetch-store :choice-points))
40 | (difference (fetch-store :recomputed) removed-cps)
41 | (fetch-store :choice-points))
42 |
43 | fwd-trace-log-lik (total-log-lik (fetch-store :newly-created) (fetch-store :choice-points))
44 | bwd-trace-log-lik (total-log-lik removed-cps choice-points)
45 | ;; prop-trace-log-lik (total-log-lik (difference
46 | ;; ;; TODO: What about reweighting of reused choice-points???
47 | ;; ;; (union (set change-set) (-> @*global-store* :newly-created))
48 | ;; (fetch-store :recomputed))
49 | ;; ;; removed-cps
50 | ;; (fetch-store :choice-points))
51 | prop-prob-choices (prob-choice-dist (fetch-store :choice-points))]
52 | ;; (when-not (empty? (clojure.set/intersection (fetch-store :recomputed) removed-cps))
53 | ;; (print "."))
54 | ;; (when-let [it (seq removed-cps)] (println "Removed: " (pr-str (map :name it)) " (" (count it) ")"))
55 | ;; (when-let [it (seq (fetch-store :newly-created))] (println "Created: " it " (" (count it) ")"))
56 | (if (< (Math/log (rand))
57 | (+ (- prop-trace-log-lik trace-log-lik)
58 | (- (Math/log (prop-prob-choices (:name selected-cp)))
59 | (Math/log (prob-choices (:name selected-cp))))
60 | (- bwd-trace-log-lik fwd-trace-log-lik)
61 | (- bwd-log-lik fwd-log-lik)))
62 | (fetch-store :choice-points)
63 | choice-points))))))
64 |
65 | (defn sample-traces [prob-chunk]
66 | (println "Trying to find a valid trace ...")
67 | (let [[cp choice-points] (find-valid-trace prob-chunk)]
68 | (println "Started sampling")
69 | (letfn [(samples [choice-points idx accepted]
70 | (lazy-seq
71 | (let [val (cp-value cp choice-points)
72 | next-choices (sampling-step choice-points)
73 | output? (= (mod idx 500) 0)
74 | accepted (if (= choice-points next-choices)
75 | accepted
76 | (inc accepted))]
77 | (when output?
78 | (println idx ": " val)
79 | (println "Log. lik.: " (total-log-lik (keys choice-points) choice-points))
80 | (println "Accepted " accepted " out of last 500 samples"))
81 | (cons val
82 | (samples next-choices (inc idx)
83 | (if output? 0 accepted))))))]
84 | (samples choice-points 0 0))))
85 |
86 | ;;; faster sampling for fixed topology ==> TODO: combine for general sampling routine!!!
87 |
88 | (defn sampling-step-fixed [choice-points selected all-dependencies]
89 | (with-fresh-store choice-points
90 | (let [selected-cp (choice-points selected)
91 | change-set (ordered-dependencies (:name selected-cp) choice-points)
92 | trace-log-lik (total-log-lik change-set choice-points)
93 |
94 | [prop-val fwd-log-lik bwd-log-lik]
95 | (propose selected-cp (:value selected-cp))]
96 | (assoc-in-store! [:choice-points (:name selected-cp) :value]
97 | prop-val)
98 | (propagate-change-to change-set)
99 |
100 | (if (trace-failed?)
101 | [choice-points false]
102 | (do (let [removed-cps (remove-uncalled-choices)]
103 | (when-not (empty? (fetch-store :newly-created))
104 | (error "New choice points created during fixed sampling: "
105 | (pr-str (fetch-store :newly-created))))
106 | (when-not (empty? removed-cps)
107 | (error "Choice points deleted during fixed sampling: "
108 | (pr-str removed-cps))))
109 | (let [prop-trace-log-lik (total-log-lik (fetch-store :recomputed)
110 | (fetch-store :choice-points))]
111 | (if (< (Math/log (rand))
112 | (+ (- prop-trace-log-lik trace-log-lik)
113 | (- bwd-log-lik fwd-log-lik)))
114 | [(fetch-store :choice-points) true]
115 | [choice-points false])))))))
116 |
117 | (defn sample-traces-fixed [prob-chunk select-update]
118 | (println "Trying to find a valid trace ...")
119 | (let [[cp choice-points] (find-valid-trace prob-chunk)]
120 | (println "Generating update sequence ...")
121 | (let [update-seq (select-update (prob-choice-dist choice-points))]
122 | (println "Started sampling")
123 | (letfn [(samples [choice-points idx accepted update-seq all-dependencies]
124 | (if (seq update-seq)
125 | (lazy-seq
126 | (let [val (cp-value cp choice-points)
127 | [next-choices accepted?]
128 | (sampling-step-fixed choice-points
129 | (first update-seq)
130 | all-dependencies)
131 | output? (= (mod idx 500) 0)
132 | accepted (if accepted? (inc accepted) accepted)]
133 | (when output?
134 | (println idx ": " val)
135 | (println "Log. lik.: " (total-log-lik (keys choice-points) choice-points))
136 | (println "Accepted " accepted " out of last 500 samples"))
137 | (cons val
138 | (samples next-choices (inc idx)
139 | (if output? 0 accepted)
140 | (rest update-seq)
141 | all-dependencies))))
142 | ()))]
143 | (samples choice-points 0 0 update-seq
144 | (do (println "Caching dependencies ...")
145 | (time
146 | (into {} (for [cp-name (keys choice-points)]
147 | [cp-name (ordered-dependencies cp-name choice-points)])))))))))
148 |
149 |
--------------------------------------------------------------------------------
/src/probabilistic_clojure/utils/finite_distributions.clj:
--------------------------------------------------------------------------------
1 | ;; Finite probability distributions
2 |
3 | ;; by Konrad Hinsen
4 | ;; last updated January 8, 2010
5 |
6 | ;; Copyright (c) Konrad Hinsen, 2009-2010. All rights reserved. The use
7 | ;; and distribution terms for this software are covered by the Eclipse
8 | ;; Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
9 | ;; which can be found in the file epl-v10.html at the root of this
10 | ;; distribution. By using this software in any fashion, you are
11 | ;; agreeing to be bound by the terms of this license. You must not
12 | ;; remove this notice, or any other, from this software.
13 |
14 | ;; Modified to work with Clojure 1.3
15 |
16 | (ns
17 | ^{:author "Konrad Hinsen"
18 | :doc "Finite probability distributions
19 | This library defines a monad for combining finite probability
20 | distributions."}
21 | probabilistic-clojure.utils.finite-distributions
22 | (:use [clojure.algo.monads
23 | :only (defmonad domonad with-monad maybe-t m-lift m-chain)]))
24 |
25 | (in-ns 'probabilistic-clojure.utils.finite-distributions)
26 |
27 | ; The probability distribution monad. It is limited to finite probability
28 | ; distributions (e.g. there is a finite number of possible value), which
29 | ; are represented as maps from values to probabilities.
30 |
31 | (defmonad dist-m
32 | "Monad describing computations on fuzzy quantities, represented by a finite
33 | probability distribution for the possible values. A distribution is
34 | represented by a map from values to probabilities."
35 | [m-result (fn m-result-dist [v]
36 | {v 1})
37 | m-bind (fn m-bind-dist [mv f]
38 | (reduce (partial merge-with +)
39 | (for [[x p] mv [y q] (f x)]
40 | {y (* q p)})))
41 | ])
42 |
43 | ; Applying the monad transformer maybe-t to the basic dist monad results
44 | ; in the cond-dist monad that can handle invalid values. The total probability
45 | ; for invalid values ends up as the probability of m-zero (which is nil).
46 | ; The function normalize takes this probability out of the distribution and
47 | ; re-distributes its weight over the valid values.
48 |
49 | (def cond-dist-m
50 | "Variant of the dist monad that can handle undefined values."
51 | (maybe-t dist-m))
52 |
53 | ; Normalization
54 |
55 | (defn- scale-by
56 | "Multiply each entry in dist by the scale factor s and remove zero entries."
57 | [dist s]
58 | (into {}
59 | (for [[val p] dist :when (> p 0)]
60 | [val (* p s)])))
61 |
62 | (defn normalize-cond [cdist]
63 | "Normalize a probability distribution resulting from a computation in
64 | the cond-dist monad by re-distributing the weight of the invalid values
65 | over the valid ones."
66 | (let [missing (get cdist nil 0)
67 | dist (dissoc cdist nil)]
68 | (cond (zero? missing) dist
69 | (= 1 missing) {}
70 | :else (let [scale (/ 1 (- 1 missing))]
71 | (scale-by dist scale)))))
72 |
73 | (defn normalize
74 | "Convert a weight map (e.g. a map of counter values) to a distribution
75 | by multiplying with a normalization factor. If the map has a key
76 | :total, its value is assumed to be the sum over all the other values and
77 | it is used for normalization. Otherwise, the sum is calculated
78 | explicitly. The :total key is removed from the resulting distribution."
79 | [weights]
80 | (let [total (:total weights)
81 | w (dissoc weights :total)
82 | s (/ 1 (if (nil? total) (reduce + (vals w)) total))]
83 | (scale-by w s)))
84 |
85 | ; Functions that construct distributions
86 |
87 | (defn uniform
88 | "Return a distribution in which each of the elements of coll
89 | has the same probability."
90 | [coll]
91 | (let [n (count coll)
92 | p (/ 1 n)]
93 | (into {} (for [x (seq coll)] [x p]))))
94 |
95 | (defn choose
96 | "Construct a distribution from an explicit list of probabilities
97 | and values. They are given in the form of a vector of probability-value
98 | pairs. In the last pair, the probability can be given by the keyword
99 | :else, which stands for 1 minus the total of the other probabilities."
100 | [& choices]
101 | (letfn [(add-choice [dist [p v]]
102 | (cond (nil? p) dist
103 | (= p :else)
104 | (let [total-p (reduce + (vals dist))]
105 | (assoc dist v (- 1 total-p)))
106 | :else (assoc dist v p)))]
107 | (reduce add-choice {} (partition 2 choices))))
108 |
109 | (defn bernoulli
110 | [p]
111 | "Returns the Bernoulli distribution for probability p."
112 | (choose p 1 :else 0))
113 |
114 | (defn- bc
115 | [n]
116 | "Returns the binomial coefficients for a given n."
117 | (let [r (inc n)]
118 | (loop [c 1
119 | f (list 1)]
120 | (if (> c n)
121 | f
122 | (recur (inc c) (cons (* (/ (- r c) c) (first f)) f))))))
123 |
124 | (defn binomial
125 | [n p]
126 | "Returns the binomial distribution, which is the distribution of the
127 | number of successes in a series of n experiments whose individual
128 | success probability is p."
129 | (let [q (- 1 p)
130 | n1 (inc n)
131 | k (range n1)
132 | pk (take n1 (iterate #(* p %) 1))
133 | ql (reverse (take n1 (iterate #(* q %) 1)))
134 | f (bc n)]
135 | (into {} (map vector k (map * f pk ql)))))
136 |
137 | (defn make-distribution
138 | "Returns the distribution in which each element x of the collection
139 | has a probability proportional to (f x)"
140 | [coll f]
141 | (normalize (into {} (for [k coll] [k (f k)]))))
142 |
143 | (defn zipf
144 | "Returns the Zipf distribution in which the numbers k=1..n have
145 | probabilities proportional to 1/k^s."
146 | [s n]
147 | (make-distribution (range 1 (inc n)) #(/ (java.lang.Math/pow % s))))
148 |
149 | (defn certainly
150 | "Returns a distribution in which the single value v has probability 1."
151 | [v]
152 | {v 1})
153 |
154 | (with-monad dist-m
155 |
156 | (defn join-with
157 | "Returns the distribution of (f x y) with x from dist1 and y from dist2."
158 | [f dist1 dist2]
159 | ((m-lift 2 f) dist1 dist2))
160 |
161 | )
162 |
163 | (with-monad cond-dist-m
164 | (defn cond-prob
165 | "Returns the conditional probability for the values in dist that satisfy
166 | the predicate pred."
167 | [pred dist]
168 | (normalize-cond
169 | (domonad
170 | [v dist
171 | :when (pred v)]
172 | v))))
173 |
174 | ; Select (with equal probability) N items from a sequence
175 |
176 | (defn- nth-and-rest [n xs]
177 | "Return a list containing the n-th value of xs and the sequence
178 | obtained by removing the n-th value from xs."
179 | (let [[h t] (split-at n xs)]
180 | (list (first t) (concat h (rest t)))))
181 |
182 | (with-monad dist-m
183 |
184 | (defn- select-n [n xs]
185 | (letfn [(select-1 [[s xs]]
186 | (uniform (for [i (range (count xs))]
187 | (let [[nth rest] (nth-and-rest i xs)]
188 | (list (cons nth s) rest)))))]
189 | ((m-chain (replicate n select-1)) (list '() xs))))
190 |
191 | (defn select [n xs]
192 | "Return the distribution for all possible ordered selections of n elements
193 | out of xs."
194 | ((m-lift 1 first) (select-n n xs)))
195 |
196 | )
197 |
198 | ; Find the probability that a given predicate is satisfied
199 |
200 | (defn prob
201 | "Return the probability that the predicate pred is satisfied in the
202 | distribution dist, i.e. the sum of the probabilities of the values
203 | that satisfy pred."
204 | [pred dist]
205 | (apply + (for [[x p] dist :when (pred x)] p)))
206 |
207 |
--------------------------------------------------------------------------------
/src/probabilistic_clojure/utils/sampling.clj:
--------------------------------------------------------------------------------
1 | ;;; Copyright (C) 2011 Nils Bertschinger
2 |
3 | ;;; This file is part of Probabilistic-Clojure
4 |
5 | ;;; Probabilistic-Clojure is free software: you can redistribute it and/or modify
6 | ;;; it under the terms of the GNU Lesser General Public License as published by
7 | ;;; the Free Software Foundation, either version 3 of the License, or
8 | ;;; (at your option) any later version.
9 |
10 | ;;; Probabilistic-Clojure is distributed in the hope that it will be useful,
11 | ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | ;;; GNU Lesser General Public License for more details.
14 |
15 | ;;; You should have received a copy of the GNU Lesser General Public License
16 | ;;; along with Probabilistic-Clojure. If not, see .
17 |
18 | (ns
19 | ^{:author "Nils Bertschinger"
20 | :doc "Utility functions for discrete probability distributions."}
21 | probabilistic-clojure.utils.sampling)
22 |
23 |
24 | (defn sample-from
25 | "Sample from a discrete distribution implemented as a hash-map from
26 | values to probabilities."
27 | [dist]
28 | (when (seq dist)
29 | (let [total (reduce + (vals dist))
30 | threshold (rand)]
31 | (loop [cum-p 0
32 | [[v p] & more] (seq dist)]
33 | (if (< threshold (+ cum-p p))
34 | v
35 | (recur (+ cum-p p) more))))))
36 |
37 | ;;; fast sampling using the alias method
38 |
39 | (defn init-alias
40 | "Takes a vector of probabilities and initializes the \"magic\" arrays
41 | prob and alias used by the alias method."
42 | [p]
43 | (let [n (count p)
44 | {large :large, small :small}
45 | (group-by (fn [i] (if (> (p i) (/ 1 n))
46 | :large
47 | :small))
48 | (range n))
49 |
50 | prob (make-array Double n)
51 | alias (make-array Long n)]
52 |
53 | (loop [p p
54 | small small
55 | large large]
56 | (if (and (seq small) (seq large))
57 | (let [[j & small] small
58 | [k & large] large]
59 | (aset prob j (double (* n (p j))))
60 | (aset alias j k)
61 |
62 | (let [p (assoc p k
63 | (+ (p k) (- (p j) (/ 1 n))))
64 | push-large? (> (p k) (/ 1 n))]
65 | (recur p
66 | (if push-large? small (cons k small))
67 | (if push-large? (cons k large) large))))
68 | (do (loop [small small]
69 | (when (seq small)
70 | (aset prob (first small) (double 1))
71 | (recur (rest small))))
72 | (loop [large large]
73 | (when (seq large)
74 | (aset prob (first large) (double 1))
75 | (recur (rest large)))))))
76 |
77 | [n (vec (seq prob)) (vec (seq alias))]))
78 |
79 | (defn sample-alias
80 | "Draws one sample using the alias method. n denotes the length of the vectors prob and alias."
81 | [n prob alias]
82 | (let [u (* n (rand))
83 | j (int u)]
84 | (if (<= (- u j) (prob j))
85 | j
86 | (alias j))))
87 |
88 | ;;; Lazy streams of random draws
89 |
90 | (defn random-selection
91 | "Returns a lazy sequence of random draws from dist. Optionally the requested
92 | number of samples can be specified."
93 | ([dist]
94 | (repeatedly (fn [] (sample-from dist))))
95 | ([n dist]
96 | (repeatedly n (fn [] (sample-from dist)))))
97 |
98 | (defn random-selection-alias
99 | "Returns a lazy sequence of random draws from dist using the alias method (very fast if a large
100 | number of samples is required). Optionally the requested number of samples can be specified."
101 | ([dist]
102 | (repeatedly (let [vs (vec (keys dist))
103 | [n prob alias] (init-alias (vec (vals dist)))]
104 | (fn [] (vs (sample-alias n prob alias))))))
105 | ([n dist]
106 | (take n (random-selection-alias dist))))
107 |
108 | ;;; Distribution utilities
109 |
110 | (defn normalize
111 | "Normalize the distribution given by the hash-map dist"
112 | [dist]
113 | (let [total (reduce + (vals dist))]
114 | (if (= total 1)
115 | dist
116 | (into {} (for [[x p] dist] [x (/ p total)])))))
117 |
118 | (defn density
119 | "Like frequencies, but normalizes the counts."
120 | [vs]
121 | (let [freqs (frequencies vs)
122 | total (reduce + (vals freqs))]
123 | (into {} (for [[v c] freqs] [v (double (/ c total))]))))
124 |
125 |
126 |
--------------------------------------------------------------------------------
/src/probabilistic_clojure/utils/stuff.clj:
--------------------------------------------------------------------------------
1 | ;;; Copyright (C) 2011 Nils Bertschinger
2 |
3 | ;;; This file is part of Probabilistic-Clojure
4 |
5 | ;;; Probabilistic-Clojure is free software: you can redistribute it and/or modify
6 | ;;; it under the terms of the GNU Lesser General Public License as published by
7 | ;;; the Free Software Foundation, either version 3 of the License, or
8 | ;;; (at your option) any later version.
9 |
10 | ;;; Probabilistic-Clojure is distributed in the hope that it will be useful,
11 | ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
12 | ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 | ;;; GNU Lesser General Public License for more details.
14 |
15 | ;;; You should have received a copy of the GNU Lesser General Public License
16 | ;;; along with Probabilistic-Clojure. If not, see .
17 |
18 | (ns
19 | ^{:author "Nils Bertschinger"
20 | :doc "Small collections of little helpers"}
21 | probabilistic-clojure.utils.stuff)
22 |
23 | (defn ensure-list [x]
24 | (if (seq? x) x (list x)))
25 |
26 | (defn error [& args]
27 | (throw (Error. (apply str args))))
28 |
29 | (defn transpose
30 | "Transpose a list of lists, i.e. (transpose [[1 2] [3 4] [5 6]]) = [[1 3 5] [2 4 6]]"
31 | [lls]
32 | (apply map list lls))
33 |
34 | (defn indexed
35 | "Returns a new collection containing index-value pairs for each value
36 | in the given collection."
37 | [coll]
38 | (map vector (iterate inc 0) coll))
39 |
--------------------------------------------------------------------------------