├── LICENSE.md ├── Methods ├── L1Minimization.m ├── LeastSquaresPCE.m ├── OrthogonalMatchingPursuit.m └── RandomizedGreedy.m ├── README.md ├── SpectralToolbox ├── HermitePhysicistPoly.m ├── HermiteProbabilistPoly.m ├── LegendrePoly.m └── MultivariatePC.m ├── TestProblems ├── algebraic_1.m ├── algebraic_2.m ├── algebraic_3.m ├── diff_2D_stochastic_forcing.m └── diffusion_equation_stochastic_forcing.m ├── scripts ├── create_plots.m ├── example_run.m ├── post_process_lowmem.m ├── run_algorithms.m ├── run_algorithms_lowmem.m ├── run_sampling.m └── run_test_problems.m └── tools ├── ImprovedInputParser.m └── sparse_grid.m /LICENSE.md: -------------------------------------------------------------------------------- 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 | -------------------------------------------------------------------------------- /Methods/L1Minimization.m: -------------------------------------------------------------------------------- 1 | % Author: Ricardo Baptista and Prasanth Nair 2 | % Date: March 2019 3 | % 4 | % See LICENSE.md for copyright information 5 | % 6 | 7 | classdef L1Minimization < LeastSquaresPCE 8 | % L1Minimization Class computes coefficients 9 | % of PCE expansion given N pairs of samples (X,Y) using 10 | % the BPDN L1 minimization algorithm 11 | % 12 | % Methods include: fit, train, eval_residual 13 | % 14 | 15 | properties 16 | 17 | end 18 | 19 | methods 20 | function L1 = L1Minimization(dim, order, basis, varargin) 21 | 22 | % define LS PC object 23 | L1@LeastSquaresPCE(dim, order, basis, varargin{:}); 24 | 25 | % check if spg_bpdn is in the path 26 | if exist('spg_bpdn','file') ~= 2 27 | error('Please add SPGL1 solver to path - see README'); 28 | end 29 | 30 | end %endFunction 31 | %------------------------------------------------------------------ 32 | %------------------------------------------------------------------ 33 | function L1 = fit(L1, X, Y) 34 | 35 | % evaluate basis functions 36 | Psi = L1.poly.BasisEval(X); 37 | 38 | % save Y, and Psi 39 | L1.Y = Y; 40 | L1.Psi = Psi; 41 | 42 | % define training function 43 | solver = @(Xt, Yt, delta) L1.train(Xt, Yt, delta); 44 | 45 | % run cross-validation to determine \delta parameter 46 | delta_opt = L1.cross_validate(solver, Psi, Y); 47 | 48 | % solve for coefficients with optimal delta 49 | L1 = solver(Psi, Y, delta_opt); 50 | 51 | end %endFunction 52 | %------------------------------------------------------------------ 53 | %------------------------------------------------------------------ 54 | function L1 = train(L1, Psi, Y, delta) 55 | 56 | % extract normalization of basis to define preconditoner 57 | precond = sqrt(sum(Psi.^2,1)); 58 | W = diag(1./precond); 59 | 60 | % define A, b matrices for BPDN solver 61 | A = Psi*W; 62 | b = Y; 63 | 64 | % Solve for the solution 65 | options = spgSetParms('verbosity',0,'weights',diag(W)); 66 | [soln,~,~,info] = spg_bpdn(A, b, delta, options); 67 | 68 | % If not converged, print error message 69 | if (info.stat > 5) 70 | warning('BPDN solver did not converge.') 71 | end 72 | 73 | % save solution in L1 structure 74 | soln = W*soln; 75 | L1.coeffs = nonzeros(soln); 76 | L1.indices = find(soln); 77 | L1.dict = setdiff(1:L1.n_basis(), L1.indices); 78 | 79 | end 80 | %------------------------------------------------------------------ 81 | %------------------------------------------------------------------ 82 | function residual = eval_residual(L1) 83 | residual = L1.Psi(:,L1.indices)*L1.coeffs - L1.Y; 84 | end %endFunction 85 | %------------------------------------------------------------------ 86 | %------------------------------------------------------------------ 87 | end %endMethods 88 | 89 | end %endClass 90 | -------------------------------------------------------------------------------- /Methods/LeastSquaresPCE.m: -------------------------------------------------------------------------------- 1 | % Author: Ricardo Baptista and Prasanth Nair 2 | % Date: March 2019 3 | % 4 | % See LICENSE.md for copyright information 5 | % 6 | 7 | classdef LeastSquaresPCE 8 | % LeastSquaresPCE Class computes coefficients of PCE 9 | % expansion given N pairs of samples (X,Y) using 10 | % approximate least-squares minimization techniques. 11 | % 12 | % The implemented methods defined as subclasses are: 13 | % - unregularized L2 minimization (parent) 14 | % - OMP & OMP with optimal basis selection 15 | % - L1 minimization (BPDN) 16 | % - Randomized greedy (RGA) 17 | % 18 | % Methods include: cross_validate, validation_error, fit, testErr, n_basis 19 | % 20 | 21 | properties 22 | 23 | dim % input dimension 24 | order % order of expansion 25 | poly % multivariate polynomial object 26 | 27 | dict % list of available basis functions 28 | indices % list of selected basis functions 29 | coeffs % basis coefficients 30 | 31 | Psi % evaluations of basis functions 32 | Y % evaluations of model output 33 | 34 | end 35 | 36 | methods 37 | function PC = LeastSquaresPCE(dim, order, basis, varargin) 38 | 39 | % Define PC object 40 | p = ImprovedInputParser; 41 | addRequired(p,'dim'); 42 | addRequired(p,'order'); 43 | parse(p,dim,order,varargin{:}); 44 | PC = passMatchedArgsToProperties(p, PC); 45 | 46 | % save multivariate PC object 47 | PC.poly = MultivariatePC(dim, order, basis); 48 | 49 | end %endFunction 50 | %------------------------------------------------------------------ 51 | %------------------------------------------------------------------ 52 | function nPC = n_basis(PC) 53 | nPC = PC.poly.ncoeff(); 54 | end %endFunction 55 | %------------------------------------------------------------------ 56 | %------------------------------------------------------------------ 57 | function PC = fit(PC,X,Y) 58 | 59 | % evaluate basis functions 60 | Psi_ = PC.poly.BasisEval(X); 61 | 62 | % save Y, Psi 63 | PC.Y = Y; 64 | PC.Psi = Psi_; 65 | 66 | % evaluate coefficients using normal equations 67 | PC.coeffs = (Psi_'*Psi_)\(Psi_'*Y); 68 | 69 | % define indices and empty dictionary 70 | PC.indices = 1:PC.n_basis(); 71 | PC.dict = []; 72 | 73 | end %endFunction 74 | %------------------------------------------------------------------ 75 | %------------------------------------------------------------------ 76 | function delta = cross_validate(PC, PCEsolver, X, Y) 77 | 78 | % define number of Cross-Validation folds 79 | n_folds = 4; 80 | 81 | % residual error evaluations 82 | delta_cv = logspace(-5,1,100); 83 | 84 | % determine total number of samples 85 | N = size(X,1); 86 | 87 | % define matrix to store test error 88 | test_error = nan(n_folds, length(delta_cv)); 89 | 90 | for i=1:n_folds 91 | 92 | % Determine the number of terms in each set 93 | pts_pfold = floor(N/n_folds); 94 | test_pts = (i-1)*pts_pfold+1:i*pts_pfold; 95 | train_pts = setdiff(1:N, test_pts); 96 | 97 | % separate dataset into training and test sets 98 | xTrain = X(train_pts,:); 99 | yTrain = Y(train_pts,:); 100 | 101 | xTest = X(test_pts,:); 102 | yTest = Y(test_pts,:); 103 | 104 | % Train model and determine the training-set error 105 | for j=1:length(delta_cv) 106 | PCE = PCEsolver(xTrain, yTrain, delta_cv(j)); 107 | test_error(i,j) = PCE.validation_error(xTest, yTest); 108 | end 109 | 110 | end 111 | 112 | % compute average test error 113 | mean_error = nanmean(test_error,1); 114 | 115 | % Find minimum validation error 116 | [~, idx_min] = min(mean_error); 117 | delta = delta_cv(idx_min(1)); 118 | 119 | % Rescale optimal delta based on number of samples 120 | % consider minimum of delta in case of multiple values 121 | delta = sqrt(N/length(train_pts))*min(delta); 122 | 123 | end %endFunction 124 | %------------------------------------------------------------------ 125 | %------------------------------------------------------------------ 126 | function err = validation_error(PC, Psi, Y) 127 | % evaluate L2 norm of prediction error at (X,Y) 128 | err = norm(Psi(:,PC.indices)*PC.coeffs - Y, 2); 129 | end %endFunction 130 | %------------------------------------------------------------------ 131 | %------------------------------------------------------------------ 132 | function [TestE, MeanE, StdE] = testErr(PC, XTest, YTest, wTest) 133 | 134 | % evaluate basis functions at XTest 135 | Psi_ = PC.poly.BasisEval(XTest); 136 | Yhat = Psi_(:,PC.indices)*PC.coeffs; 137 | 138 | % compute relative weighted test error 139 | L2Err = (YTest - Yhat).^2; 140 | TestE = (wTest*L2Err)/(wTest*(YTest.^2)); 141 | 142 | % evaluate mean and standard deviation of yTest 143 | meanTest = wTest*YTest; 144 | stdTest = sqrt(wTest*YTest.^2 - meanTest^2); 145 | 146 | % evaluate mean and standard deviation of PC expansion 147 | if PC.indices(1) == 1 148 | meanPC = PC.coeffs(1); 149 | else 150 | meanPC = mean(Yhat); 151 | end 152 | stdPC = sqrt(sum((PC.coeffs).^2) - meanPC^2); 153 | 154 | % compute relative mean and standard deviation error 155 | MeanE = norm(meanPC - meanTest)/norm(meanTest); 156 | StdE = norm(stdPC - stdTest)/norm(stdTest); 157 | 158 | end %endFunction 159 | %------------------------------------------------------------------ 160 | %------------------------------------------------------------------ 161 | end %endMethods 162 | 163 | end %endClass 164 | -------------------------------------------------------------------------------- /Methods/OrthogonalMatchingPursuit.m: -------------------------------------------------------------------------------- 1 | % Author: Ricardo Baptista and Prasanth Nair 2 | % Date: March 2019 3 | % 4 | % See LICENSE.md for copyright information 5 | % 6 | 7 | classdef OrthogonalMatchingPursuit < LeastSquaresPCE 8 | % OrthogonalMatchingPursuit Class computes coefficients 9 | % of PCE expansion given N pairs of samples (X,Y) using 10 | % the OMP techniques 11 | % 12 | % Methods include: fit, train, select_basis, evalCoeffs, 13 | % evalResidual, updateQR 14 | % 15 | 16 | properties 17 | 18 | alg % approach for OMP minimization (opt or old) 19 | Q % QR decomposition of Psi(:,basis) 20 | R % QR decomposition of Psi(:,basis) 21 | PsiNorm % stored L2 norm of basis functions 22 | residual % current training residual of approximation 23 | 24 | end 25 | 26 | methods 27 | function OMP = OrthogonalMatchingPursuit(dim, order, basis, alg, varargin) 28 | 29 | % define OMP object 30 | OMP@LeastSquaresPCE(dim, order, basis, varargin{:}); 31 | OMP.alg = alg; 32 | 33 | end %endFunction 34 | %------------------------------------------------------------------ 35 | %------------------------------------------------------------------ 36 | function OMP = fit(OMP, X, Y) 37 | 38 | % evaluate basis functions 39 | Psi = OMP.poly.BasisEval(X); 40 | 41 | % define training function 42 | solver = @(Xt, Yt, delta) OMP.train(Xt, Yt, delta); 43 | 44 | % run cross-validation to determine \delta parameter 45 | delta_opt = OMP.cross_validate(solver, Psi, Y); 46 | 47 | % solve for coefficients with optimal delta 48 | OMP = solver(Psi, Y, delta_opt); 49 | 50 | end %endFunction 51 | %------------------------------------------------------------------ 52 | %------------------------------------------------------------------ 53 | function OMP = train(OMP, Psi, Y, delta) 54 | 55 | % save Y, Psi and compute L2 norm of basis evaluations 56 | OMP.Y = Y; 57 | OMP.Psi = Psi; 58 | OMP.PsiNorm = sum(Psi.^2,1); 59 | OMP.residual = Y; 60 | 61 | % determine the number of basis elements 62 | n_basis = OMP.n_basis(); 63 | 64 | % define initial PC dictionary (including constant term) 65 | OMP.dict = 2:n_basis; 66 | OMP.indices = 1; 67 | 68 | % initialize Q, R, and PsiNorm (after updating OMP.indices) 69 | if strcmp(OMP.alg, 'opt') 70 | [OMP.Q, OMP.R, OMP.PsiNorm] = OMP.updateQR(); 71 | end 72 | 73 | % initialize L2 norm of residual 74 | OMP.coeffs = OMP.evalCoeffs(); 75 | OMP.residual = OMP.evalResidual(); 76 | L2res = norm(OMP.residual, 2); 77 | 78 | % run OMP until dictionary is empty or norm of 79 | % training error is less than delta 80 | while(L2res >= delta && ~isempty(OMP.dict)) 81 | 82 | % find next basis_idx and add to index 83 | basis_idx = OMP.selectBasis(); 84 | OMP.indices = [OMP.indices, basis_idx]; 85 | OMP.dict(OMP.dict == basis_idx) = []; 86 | 87 | % evaluate coefficients 88 | OMP.coeffs = OMP.evalCoeffs(); 89 | 90 | % evaluate training residual 91 | OMP.residual = OMP.evalResidual(); 92 | L2res = norm(OMP.residual,2); 93 | 94 | % update PsiNorm decomposition 95 | if strcmp(OMP.alg, 'opt') 96 | [OMP.Q, OMP.R, OMP.PsiNorm] = OMP.updateQR(); 97 | end 98 | 99 | end 100 | 101 | end %endFunction 102 | %------------------------------------------------------------------ 103 | %------------------------------------------------------------------ 104 | function basis_idx = selectBasis(OMP) 105 | 106 | % extract residual, Psi and PsiNorm 107 | residual_ = OMP.residual; 108 | Psi_ = OMP.Psi; 109 | PsiNorm_ = OMP.PsiNorm; 110 | 111 | % define basis functions to test 112 | basis = OMP.dict; 113 | 114 | % extract basis functions and denominators 115 | Psi_t = Psi_(:,basis); 116 | PsiNorm_t = PsiNorm_(:,basis); 117 | 118 | % compute correlations of basis vectors with residual 119 | basis_corr = (residual_'*Psi_t).^2./PsiNorm_t; 120 | 121 | % Identify maximum correlation or assign 1 for the first term 122 | [~, opt_idx] = max(abs(basis_corr)); 123 | basis_idx = basis(opt_idx); 124 | 125 | end %endFunction 126 | %------------------------------------------------------------------ 127 | %------------------------------------------------------------------ 128 | function coeffs = evalCoeffs(OMP) 129 | Psi_ = OMP.Psi(:,OMP.indices); 130 | coeffs = (Psi_'*Psi_)\(Psi_'*OMP.Y); 131 | end %endFunction 132 | %------------------------------------------------------------------ 133 | %------------------------------------------------------------------ 134 | function residual = evalResidual(OMP) 135 | residual = OMP.Psi(:,OMP.indices)*OMP.coeffs - OMP.Y; 136 | end %endFunction 137 | %------------------------------------------------------------------ 138 | %------------------------------------------------------------------ 139 | function [Q, R, PsiNorm] = updateQR(OMP) 140 | 141 | % extract Psi 142 | Psi_ = OMP.Psi(:,OMP.indices); 143 | 144 | % update Q,R 145 | if isempty(OMP.Q) || isempty(OMP.R) 146 | [Q,R] = qr(Psi_); 147 | else 148 | [Q,R] = qrinsert(OMP.Q, OMP.R, size(Psi_,2), Psi_(:,end)); 149 | end 150 | 151 | % update PsiNorm 152 | Q_k = Q(:,length(OMP.indices)); 153 | PsiNorm = OMP.PsiNorm - (Q_k'*OMP.Psi).^2; 154 | 155 | end %endFunction 156 | %------------------------------------------------------------------ 157 | %------------------------------------------------------------------ 158 | end %endMethods 159 | 160 | end %endClass 161 | -------------------------------------------------------------------------------- /Methods/RandomizedGreedy.m: -------------------------------------------------------------------------------- 1 | % Author: Ricardo Baptista and Prasanth Nair 2 | % Date: March 2019 3 | % 4 | % See LICENSE.md for copyright information 5 | % 6 | 7 | classdef RandomizedGreedy < LeastSquaresPCE 8 | % LeastSquaresPCE Class computes coefficients of PCE 9 | % expansion given N pairs of samples (X,Y) using 10 | % approximate least-squares minimization techniques. 11 | % The implemented methods are: unregularized, OMP, 12 | % l1 minimization, and RGA (randomized algorithm). 13 | % 14 | % Methods include: fit, post_process, train, select_basis, 15 | % evalResidual, terminationCriteria, evalCoeffs, 16 | % greedyBacktrack, LeaveOneOut, updateQR 17 | % 18 | 19 | properties 20 | 21 | Q % QR decomposition of Psi(:,basis) 22 | R % QR decomposition of Psi(:,basis) 23 | PsiNorm % stored L2 norm of basis functions 24 | residual % current training residual of approximation 25 | LOO % track leave one out error for termination criteria 26 | 27 | diffAvg % parameter for absolute change in mean LOO 28 | pChange % parameter for relative change in mean LOO 29 | RepExp % parameter for number of repeated RGA experiments 30 | 31 | end 32 | 33 | methods 34 | function RGA = RandomizedGreedy(dim, order, basis, varargin) 35 | 36 | % define RGA object 37 | RGA@LeastSquaresPCE(dim, order, basis, varargin{:}); 38 | 39 | % define tolerances for termination criteria 40 | RGA.diffAvg = 0; 41 | RGA.pChange = 0.01; 42 | 43 | % define parameter for number of RGA experiments 44 | RGA.RepExp = 10; 45 | 46 | end %endFunction 47 | %------------------------------------------------------------------ 48 | %------------------------------------------------------------------ 49 | function RGA = fit(RGA, X, Y) 50 | 51 | % evaluate basis functions 52 | Psi = RGA.poly.BasisEval(X); 53 | 54 | % repeat RGA training for RepExp times 55 | RGA_PCE = cell(RGA.RepExp,1); 56 | for i=1:RGA.RepExp 57 | RGA_PCE{i} = RGA.train(Psi, Y); 58 | end 59 | 60 | % extract LOO errors 61 | RGA_LOO = zeros(RGA.RepExp,1); 62 | for i=1:RGA.RepExp 63 | RGA_LOO(i) = min(RGA_PCE{i}.LOO); 64 | end 65 | 66 | % find expansion with minimum LOO error 67 | [~,opt_idx] = min(RGA_LOO); 68 | RGA = RGA_PCE{opt_idx}; 69 | 70 | end %endFunction 71 | %------------------------------------------------------------------ 72 | %------------------------------------------------------------------ 73 | function RGA = train(RGA, Psi, Y) 74 | 75 | % save Y, Psi and compute L2 norm of basis evaluations 76 | RGA.Y = Y; 77 | RGA.Psi = Psi; 78 | RGA.PsiNorm = sum(Psi.^2,1); 79 | RGA.residual = Y; 80 | 81 | % determine the number of basis elements 82 | n_basis = RGA.n_basis(); 83 | 84 | % define PC dictionary (including constant term) 85 | RGA.dict = 2:n_basis; 86 | RGA.indices = 1; 87 | 88 | % initialize Q, R, and PsiNorm (after updating RGA.indices) 89 | [RGA.Q, RGA.R, RGA.PsiNorm] = RGA.updateQR(); 90 | 91 | % update residual and LOO error (after updating RGA.indices) 92 | RGA.residual = RGA.evalResidual(); 93 | RGA.LOO = RGA.LeaveOneOut(); 94 | 95 | % initialize termination criteria 96 | term_crit = 0; 97 | 98 | while(term_crit == 0 && ~isempty(RGA.dict)) 99 | 100 | % select next basis function 101 | basis_idx = RGA.select_basis(); 102 | RGA.indices = [RGA.indices, basis_idx]; 103 | RGA.dict(RGA.dict == basis_idx) = []; 104 | 105 | % update Q, R, and PsiNorm 106 | [RGA.Q, RGA.R, RGA.PsiNorm] = RGA.updateQR(); 107 | 108 | % evaluate residual and Leave-One-Out 109 | RGA.residual = RGA.evalResidual(); 110 | RGA.LOO = [RGA.LOO, RGA.LeaveOneOut()]; 111 | 112 | % evaluate termination criteria 113 | term_crit = RGA.terminationCriteria(); 114 | end 115 | 116 | % backtrack solution to minimum value of stopping criteria 117 | RGA = RGA.greedyBacktrack(); 118 | 119 | % evaluate coefficients and post_process solution 120 | RGA.coeffs = RGA.evalCoeffs(); 121 | 122 | end %endFunction 123 | %------------------------------------------------------------------ 124 | %------------------------------------------------------------------ 125 | function basis_idx = select_basis(RGA) 126 | 127 | % extract residual, Psi and PsiNorm 128 | residual_ = RGA.residual; 129 | Psi_ = RGA.Psi; 130 | PsiNorm_ = RGA.PsiNorm; 131 | 132 | % define basis functions to test 133 | n_basis = min(60,length(RGA.dict)); 134 | [basis, ~] = datasample(RGA.dict, n_basis, 'Replace', false); 135 | 136 | % extract basis functions and denominators 137 | Psi_t = Psi_(:,basis); 138 | PsiNorm_t = PsiNorm_(:,basis); 139 | 140 | % compute correlations of basis vectors with residual 141 | basis_corr = (residual_'*Psi_t).^2./PsiNorm_t; 142 | 143 | % Identify maximum correlation or assign 1 for the first term 144 | [~, opt_idx] = max(abs(basis_corr)); 145 | basis_idx = basis(opt_idx); 146 | 147 | end %endFunction 148 | %------------------------------------------------------------------ 149 | %------------------------------------------------------------------ 150 | function [residual] = evalResidual(RGA) 151 | % update residual using QR decomposition 152 | Q_k_ = RGA.Q(:,length(RGA.indices)); 153 | residual = RGA.residual - Q_k_'*RGA.Y*Q_k_; 154 | end %endFunction 155 | %------------------------------------------------------------------ 156 | %------------------------------------------------------------------ 157 | function term_crit = terminationCriteria(RGA) 158 | 159 | % compute moving averages of LOO starting at iteration 10 160 | if length(RGA.indices) >= 10 161 | 162 | % compute mean over two time frames 163 | mu_1 = mean(RGA.LOO(end-4:end)); 164 | mu_2 = mean(RGA.LOO(end-9:end-5)); 165 | 166 | % compute decrease and percent change in LOO error 167 | diff_avg = mu_1 - mu_2; 168 | comp_avg = abs((mu_1 - mu_2)/mu_2); 169 | 170 | else 171 | diff_avg = nan; 172 | comp_avg = nan; 173 | 174 | end 175 | 176 | % evaluate termination crteria 177 | term_crit = (diff_avg > RGA.diffAvg) || ... 178 | (comp_avg < RGA.pChange) || ... 179 | (length(RGA.indices) == size(RGA.Psi,1)); 180 | 181 | end %endFunction 182 | %------------------------------------------------------------------ 183 | %------------------------------------------------------------------ 184 | function coeffs = evalCoeffs(RGA) 185 | Q_ = RGA.Q(:,1:length(RGA.indices)); 186 | R_ = RGA.R(1:length(RGA.indices),:); 187 | coeffs = R_\(Q_'*RGA.Y); 188 | end %endFunction 189 | %------------------------------------------------------------------ 190 | %------------------------------------------------------------------ 191 | function RGA = greedyBacktrack(RGA) 192 | % update properties of PC approximation (Q, R, PsiNorm, residual) 193 | % to setting at minimum of LOO error 194 | 195 | % find minimum of stopping criteria (LOO) 196 | [~, min_idx] = min(RGA.LOO); 197 | 198 | % backtrack removing basis functions 199 | for i=length(RGA.indices):-1:(min_idx+1) 200 | 201 | % update PsiNorm and residual 202 | Q_k_ = RGA.Q(:,length(RGA.indices)); 203 | RGA.PsiNorm = RGA.PsiNorm + (Q_k_'*RGA.Psi).^2; 204 | RGA.residual = RGA.residual + Q_k_'*RGA.Y*Q_k_; 205 | 206 | % udate QR decomposition (by removing column) 207 | [RGA.Q, RGA.R] = qrdelete(RGA.Q, RGA.R, i); 208 | 209 | % update dictionary and indices 210 | RGA.dict = sort([RGA.dict, RGA.indices(end)]); 211 | RGA.indices(end) = []; 212 | 213 | end 214 | 215 | end %endFunction 216 | %------------------------------------------------------------------ 217 | %------------------------------------------------------------------ 218 | function LOO = LeaveOneOut(RGA) 219 | 220 | % extract residual and Q_k 221 | residual_ = RGA.residual; 222 | Q_ = RGA.Q(:,1:length(RGA.indices)); 223 | 224 | % compute gradient with entrywise min for stability 225 | res_gradient = 1 - sum(Q_.^2,2); 226 | res_gradient = max(abs(res_gradient), 1e-12); 227 | 228 | % compute LOO error 229 | N = size(RGA.Psi,1); 230 | LOO = 1/N*sum((residual_./res_gradient).^2); 231 | 232 | end %endFunction 233 | %------------------------------------------------------------------ 234 | %------------------------------------------------------------------ 235 | function [Q, R, PsiNorm] = updateQR(RGA) 236 | % update Q, R and PsiNorm after adding a new index to Psi 237 | 238 | % extract Psi 239 | Psi_ = RGA.Psi(:,RGA.indices); 240 | 241 | % update Q,R 242 | if isempty(RGA.Q) || isempty(RGA.R) 243 | [Q,R] = qr(Psi_); 244 | else 245 | [Q,R] = qrinsert(RGA.Q, RGA.R, size(Psi_,2), Psi_(:,end)); 246 | end 247 | 248 | % update PsiNorm 249 | Q_k_ = Q(:,length(RGA.indices)); 250 | PsiNorm = RGA.PsiNorm - (Q_k_'*RGA.Psi).^2; 251 | 252 | end %endFunction 253 | %------------------------------------------------------------------ 254 | %------------------------------------------------------------------ 255 | end %endMethods 256 | 257 | end %endClass 258 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Polynomial Chaos Randomized Greedy Algorithm (RGA) 2 | 3 | ## What is the RG Algorithm? 4 | 5 | The RGA is a greedy approach for building a sparse Polynomial Chaos (PC) approximation of a function given input and output sample evaluations. At each iteration, the algorithm evaluates a random subset of basis functions from a large candidate dictionary to greedily select terms to add to the approximation without having a computational cost that scales with the dictionary size. This is combined with an efficient QR-based strategy to update the expansion and a leave-one-out estimate to measure generalization error. For more information on the details of the algorithm, please see the [JCP paper](https://www.sciencedirect.com/science/article/pii/S0021999119300865). 6 | 7 | ## Authors 8 | 9 | Ricardo Baptista (MIT) and Prasanth Nair (University of Toronto) 10 | 11 | E-mails: or , 12 | 13 | ## Installation 14 | 15 | The Randomized Greedy Algorithm is implemented in MATLAB. This package includes all necessary classes and methods to run the RGA. To compare to PC approximations that are constructed using L1 minimization, the code requires the [SPGL1](https://www.cs.ubc.ca/~mpf/spgl1/) library to be available in the local path. To assess the accuracy of the PC approximations, the scripts evaluate the polynomial models at Sparse Grid and pseudo-random Sobol points. To generate these points, the code requires the [Sparse Grid](https://people.sc.fsu.edu/~jburkardt/m_src/sparse_grid_cc/sparse_grid_cc.html) and [Sobol](https://people.sc.fsu.edu/~jburkardt/m_src/sobol/sobol.html) libraries to be available in the local path. 16 | 17 | ## Example running RGA on a benchmark problem 18 | 19 | We provide an example of running the RGA on an algebraic test problem with 5 dimensional inputs. The PC approximation is built using training data ranging in size from N = 10 to N = 1000 input points and function evaluations. The code compares the RGA to a complete basis PC expansion, L1 minimization, and two variants of Orthogonal Matching Pursuit. The code can also be run from MATLAB using the file `scripts/example_run.m`. 20 | 21 | The script first defines the input parameters. These include the dimension of the inputs `d`, the basis functions `basis`, the maximum order of the total degree polynomial basis `order`, and the anonymous target function `func`. 22 | 23 | For each N, we sample a uniform set of points on ![equation](https://latex.codecogs.com/gif.latex?%5B-1%2C1%5D%5E%7Bd%7D) and evaluate the function at these inputs. Only these sample points are seen by the algorithm during the training phase. 24 | 25 | ```Matlab 26 | 27 | Xall = 2*rand(N,d) - 1; 28 | Yall = func(Xall); 29 | 30 | ``` 31 | 32 | For each sample size, N, the function extracts a subset of the training points `X,Y` from `Xall,Yall` and builds the sparse PC model using `fit`. Given a set of testing points `XTest, YTest, wTest`, the `TestErr` function estimates the relative error in the mean and standard deviation as well as the relative mean-squared error of the approximation. 33 | 34 | ```Matlab 35 | 36 | RGA = RandomizedGreedy(d, order, basis); 37 | RGA = RGA.fit(X,Y); 38 | [TestErr, MeanErr, StdDevErr] = RGA.TestErr(XTest, YTest, wTest); 39 | 40 | ``` 41 | 42 | The script produces a plot with the convergence results from running RGA and other sparse PC algorithms for increasing N. 43 | -------------------------------------------------------------------------------- /SpectralToolbox/HermitePhysicistPoly.m: -------------------------------------------------------------------------------- 1 | % Author: Ricardo Baptista and Prasanth Nair 2 | % Date: March 2019 3 | % 4 | % See LICENSE.md for copyright information 5 | % 6 | 7 | classdef HermitePhysicistPoly 8 | % HermitePhysicistPoly defines Physicist Hermite polynomials 9 | % 10 | % Un-normalized: 11 | % H_0(x) = 1 12 | % H_1(x) = 2*x 13 | % H_2(x) = 4x^2 - 2 14 | % 15 | % Normalized: 16 | % \tilde{H}_n(x) = H_n(x)/\sqrt(n!*2^n*\sqrt(pi)) 17 | % 18 | % Methods include: Evaluate, GradEvaluate 19 | 20 | properties 21 | 22 | end %endProperties 23 | 24 | methods 25 | function HP = HermitePhysicistPoly(varargin) 26 | 27 | % Define HP object 28 | p = ImprovedInputParser; 29 | parse(p, varargin{:}); 30 | HP = passMatchedArgsToProperties(p, HP); 31 | 32 | end %endFunction 33 | %--------------------------------------------------------- 34 | %--------------------------------------------------------- 35 | function c = MonomialCoeffs(HP, N, norm) 36 | % Return the monomial polynomial coefficients 37 | % normalized coefficients divide by \sqrt(\sqrt(pi) * 2^N * N!) 38 | c = HP.HermiteCoeffs(N); 39 | if norm == true 40 | c = c/sqrt(sqrt(pi) * 2^N * factorial(N)); 41 | end 42 | end %endFunction 43 | %--------------------------------------------------------- 44 | %--------------------------------------------------------- 45 | function cf = HermiteCoeffs(HP, N) 46 | % Compute the coefficients of the Hermite polynomials 47 | % using a recursive algorithm. Input: N = polynomial order 48 | % 49 | % Example: [1], H(0,x) = 1 50 | % [0, 2], P(1,x) = 2*x 51 | % [-2, 0, 4], P(2,x) = 4x^2 - 2; 52 | % 53 | % Reference: adapted from John Burkardt (2010) 54 | 55 | % N<0, N=0, and N=1 cases 56 | if N < 0 57 | c = []; 58 | return 59 | elseif N == 0 60 | c = 1; 61 | return 62 | elseif if N == 1 63 | c = [0 2]; 64 | return 65 | end 66 | 67 | % compute N>=2 by recursion 68 | c = [1, 0; 0, 2]; 69 | for i=2:N 70 | c(i+1,1) = -2.0 * ( i - 1 ) * c(i-1,1); 71 | c(i+1,2:i-1) = 2.0 * c(i ,1:i-2)... 72 | -2.0 * ( i - 1 ) * c(i-1,2:i-1); 73 | c(i+1, i ) = 2.0 * c(i , i-1); 74 | c(i+1, i+1) = 2.0 * c(i , i ); 75 | end 76 | c = c(end,:); 77 | 78 | end % endFunction 79 | %--------------------------------------------------------- 80 | %--------------------------------------------------------- 81 | function p = Evaluate(HP, x, N, norm) 82 | % Evaluate the N-th order Hermite physicist polynomial 83 | % at m=size(x,1) points using the recursion relation 84 | % H_0(x) = 1 and H_{n}(x) = 2xH_{n-1}(x) - H_{n-1}'(x) 85 | % where H_{n-1}'(x) = 2(n-1)H_{n-2}(x) 86 | 87 | % set initial condition H_0(x) for recursion 88 | m = size(x,1); 89 | p = ones(m,1); 90 | 91 | % run recursion by tracking H_{n-1}, H_{n}, H_{n+1} 92 | if N > 0 93 | 94 | % initialize p_jm1, p_jm2 95 | p_jm1 = p; 96 | p_jm2 = zeros(m,1); 97 | 98 | % evaluate H_{j} by recursion and 99 | % saving H_{j-1}(x) and H_{j}(x) 100 | for j=1:N 101 | p = 2*x.*p_jm1 - 2*(j-1)*p_jm2; 102 | p_jm2 = p_jm1; 103 | p_jm1 = p; 104 | end 105 | end 106 | 107 | % normalize polynomials 108 | if norm == true 109 | p = p/sqrt(gamma(N+1) * 2.^N * sqrt(pi)); 110 | end 111 | 112 | end %endFunction 113 | %--------------------------------------------------------- 114 | %--------------------------------------------------------- 115 | function dp = GradEvaluate(HP, x, N, k, norm) 116 | % Evaluate the k-th derivative of the N-th order Hermite 117 | % physicist polynomial at m=size(x,1) points using the 118 | % relation H_{n}^(k)(x) = 2^{k} n!/(n-k)! H_{n-k}(x) 119 | 120 | if N >= k 121 | fact = 2^k*exp(gammaln(N+1) - gammaln(N-k+1)); 122 | dp = fact*HP.Evaluate(x, N-k, norm); 123 | if norm == true 124 | dp = dp/sqrt(fact); 125 | end 126 | else 127 | dp = zeros(size(x)); 128 | end 129 | 130 | end %endFunction 131 | %--------------------------------------------------------- 132 | %--------------------------------------------------------- 133 | end %endMethods 134 | 135 | end %endClass 136 | -------------------------------------------------------------------------------- /SpectralToolbox/HermiteProbabilistPoly.m: -------------------------------------------------------------------------------- 1 | % Author: Ricardo Baptista and Prasanth Nair 2 | % Date: March 2019 3 | % 4 | % See LICENSE.md for copyright information 5 | % 6 | 7 | classdef HermiteProbabilistPoly 8 | % HermiteProbabilistPoly defines Probabilist Hermite polynomials 9 | % using the rescaling of the physicist Hermite polynomials 10 | % 11 | % Un-normalized: 12 | % He_0(x) = 1 13 | % He_1(x) = x 14 | % He_2(x) = x^2 - 1 15 | % 16 | % Normalized: 17 | % \tilde{He}_n(x) = He_n(x)/\sqrt(\sqrt(2*pi)*n!) 18 | % 19 | % Methods include: Evaluate, GradEvaluate 20 | 21 | properties 22 | 23 | HPhy % Physicist Hermite polynomial object 24 | 25 | end 26 | 27 | methods 28 | function HP = HermiteProbabilistPoly(varargin) 29 | 30 | % Define HP object 31 | p = ImprovedInputParser; 32 | parse(p, varargin{:}); 33 | HP = passMatchedArgsToProperties(p, HP); 34 | 35 | % Set Physicist polynomial property 36 | HP.HPhy = HermitePhysicistPoly(); 37 | 38 | end %endFunction 39 | %--------------------------------------------------------- 40 | %--------------------------------------------------------- 41 | function p = Evaluate(HP, x, N, norm) 42 | % Evaluate the N-th order Hermite probabilists' polynomial 43 | % using the relation He_n(x) = 2^(-n/2)*H_n(x/sqrt(2)) 44 | % accounting for the correct scaling factors 45 | 46 | p = 1/sqrt(2^N)*HP.HPhy.Evaluate(x/sqrt(2),N,false); 47 | if norm == true 48 | p = p/sqrt(sqrt(2*pi) * gamma(N+1)); 49 | end 50 | 51 | end %endFunction 52 | %--------------------------------------------------------- 53 | %--------------------------------------------------------- 54 | function dp = GradEvaluate(HP, x, N, k, norm) 55 | % Evaluate the k-th derivative of the N-th order Hermite 56 | % probabilists' polynomial at m=size(x,1) points using the 57 | % relation He_n(x) = 2^(-n/2)*H_n(x/sqrt(2)) and accounting 58 | % for the correct scaling factors 59 | 60 | dp = 1/sqrt(2^N)*HP.HPhy.GradEvaluate(x/sqrt(2),N,k,false); 61 | dp = dp*(1/sqrt(2))^k; 62 | if norm == true 63 | dp = dp/sqrt(sqrt(2*pi) * gamma(N+1)); 64 | end 65 | 66 | end %endFunction 67 | %--------------------------------------------------------- 68 | %--------------------------------------------------------- 69 | end %endMethods 70 | 71 | end %endClass 72 | -------------------------------------------------------------------------------- /SpectralToolbox/LegendrePoly.m: -------------------------------------------------------------------------------- 1 | % Author: Ricardo Baptista and Prasanth Nair 2 | % Date: March 2019 3 | % 4 | % See LICENSE.md for copyright information 5 | % 6 | 7 | classdef LegendrePoly 8 | % LegendrePoly defines Legendre polynomials on [-1,1] 9 | % 10 | % Un-normalized: 11 | % H_0(x) = 1 12 | % H_1(x) = x 13 | % H_2(x) = 0.5*(3x^2 - 1) 14 | % 15 | % Normalized: 16 | % \tilde{P}_n(x) = H_n(x)/\sqrt(2 / (2*n+1)) 17 | % 18 | % Methods include: Evaluate, MonomialCoeffs, GradEvaluate 19 | 20 | properties 21 | 22 | end %endProperties 23 | 24 | methods 25 | function LP = LegendrePoly(varargin) 26 | 27 | % Define LP object 28 | p = ImprovedInputParser; 29 | parse(p, varargin{:}); 30 | LP = passMatchedArgsToProperties(p, LP); 31 | 32 | end %endFunction 33 | %--------------------------------------------------------- 34 | %--------------------------------------------------------- 35 | function c = MonomialCoeffs(LP, N, norm) 36 | % Return the monomial polynomial coefficients. 37 | % Normalized coefficients divide by \sqrt(1/(2*N+1)) 38 | c = LP.LegCoeffs(N); 39 | if norm == true 40 | c = c/sqrt(1/(2*N+1)); 41 | end 42 | end %endFunction 43 | %--------------------------------------------------------- 44 | %--------------------------------------------------------- 45 | function c = LegCoeffs(LP, N) 46 | % Compute the coefficients of the Legendre polynomials 47 | % using a recursive algorithm. Input: N = polynomial order 48 | % 49 | % Example: [1], P(0,x) = 1 50 | % [0, 1], P(1,x) = x 51 | % [-0.5, 0, 1.5], P(2,x) = 1.5x^2 - 0.5; 52 | % 53 | % Reference: adapted from John Burkardt (2004) 54 | 55 | % N<0, N=0, and N=1 cases 56 | if N < 0 57 | c = []; 58 | return 59 | elseif N == 0 60 | c = 1; 61 | return 62 | elseif N == 1 63 | c = [0 1]; 64 | return 65 | end 66 | 67 | % compute N>=2 by recursion 68 | c = [1, 0; 0, 1]; 69 | for i=2:N 70 | c(i+1,1:i-1) = ( - i + 1 ) * c(i-1,1:i-1) / (i); 71 | c(i+1,2:i+1) = c(i+1,2:i+1) + ( i + i - 1 ) * c(i ,1:i ) / (i); 72 | end 73 | c = c(end,:); 74 | 75 | end %endFunction 76 | %--------------------------------------------------------- 77 | %--------------------------------------------------------- 78 | function p = Evaluate(LP, x, N, norm) 79 | % Evaluate the N-th order Legendre polynomial at m=size(x,1) 80 | % points using the recursion relation P_0(x) = 1 and 81 | % nP_{n}(x) = (2n-1)*x*P_{n-1}(x) - (n-1)P_{n-2}(x) 82 | 83 | % set initial condition P_0(x) for recursion 84 | m = size(x,1); 85 | p = ones(m,1); 86 | 87 | % run recursion by tracking P_{n-1}, P_{n}, P_{n+1} 88 | if N > 0 89 | 90 | % initialize p_jm1, p_jm2 91 | p_jm1 = p; 92 | p_jm2 = zeros(m,1); 93 | 94 | % evaluate H_{j} by recursion and 95 | % saving H_{j-1}(x) and H_{j}(x) 96 | for j=1:N 97 | p = (2*j-1)/j*x.*p_jm1 - (j-1)/j*p_jm2; 98 | p_jm2 = p_jm1; 99 | p_jm1 = p; 100 | end 101 | end 102 | 103 | % normalize polynomials 104 | if norm == true 105 | p = p/sqrt(1/(2*N+1)); 106 | end 107 | 108 | end %endFunction 109 | %--------------------------------------------------------- 110 | %--------------------------------------------------------- 111 | function dp = GradEvaluate(LP, x, N, k, norm) 112 | % Evaluate the k-th derivative of the N-th order Legendre 113 | % polynomials at m=size(x,1) points using the 114 | % relation (x^2-1)/N P_{n}'(x) = xP_{n}(x) - P_{n-1}(x) 115 | 116 | if k == 0 117 | dp = LP.Evaluate(x, N, norm); 118 | elseif k == 1 119 | dp = x.*LP.Evaluate(x, N, false) - ... 120 | LP.Evaluate(x, N-1, false); 121 | dp = N./(x.^2 - 1).*dp; 122 | if norm == true 123 | dp = dp/sqrt(1/(2*N+1)); 124 | end 125 | else 126 | error('Derivative is not implemented for k > 1.') 127 | end 128 | 129 | end %endFunction 130 | %--------------------------------------------------------- 131 | %--------------------------------------------------------- 132 | end %endMethods 133 | 134 | end %endClass 135 | -------------------------------------------------------------------------------- /SpectralToolbox/MultivariatePC.m: -------------------------------------------------------------------------------- 1 | % Author: Ricardo Baptista and Prasanth Nair 2 | % Date: March 2019 3 | % 4 | % See LICENSE.md for copyright information 5 | % 6 | 7 | classdef MultivariatePC 8 | % MultivariatePC defines a class of multivariate 9 | % Hermite or Legendre polynomial basis functions: 10 | % H(x) = \sum_{\alpha} \Psi_{\alpha}*c_{\alpha} 11 | % 12 | % Methods: BasisEval, dxBasisEval, Evaluate, Grad_a, Grad_x 13 | % 14 | % Author: Ricardo Baptista 15 | % Date: November 2018 16 | 17 | properties 18 | 19 | poly % object for univariate base polynomial 20 | dim % input dimension 21 | order % polynomial order 22 | norm % normalization property of monomials 23 | coeff % total order expansion coefficients 24 | 25 | basis_precomp % precomputed basis evaluations 26 | dxbasis_precomp % precomputed derivatives of basis evaluations 27 | 28 | end 29 | 30 | methods 31 | function mPC = MultivariatePC(dim,order,basis,varargin) 32 | 33 | % Define TM object 34 | p = ImprovedInputParser; 35 | addRequired(p,'dim'); 36 | addRequired(p,'order'); 37 | parse(p,dim,order,varargin{:}); 38 | mPC = passMatchedArgsToProperties(p, mPC); 39 | 40 | % Define hermite base polynomial 41 | if strcmp(basis,'Legendre') 42 | mPC.poly = LegendrePoly(); 43 | elseif strcmp(basis, 'Hermite') 44 | mPC.poly = HermiteProbabilistPoly(); 45 | else 46 | error('Basis is not implemented') 47 | end 48 | 49 | % set normalization property 50 | mPC.norm = true; 51 | 52 | % Initialize precomputed 53 | mPC.basis_precomp = []; 54 | mPC.dxbasis_precomp = []; 55 | 56 | end %endFunction 57 | %------------------------------------------------------------------ 58 | %------------------------------------------------------------------ 59 | function d = ncoeff(mPC) 60 | d = nchoosek(mPC.dim + mPC.order, mPC.order); 61 | end %endFunction 62 | %------------------------------------------------------------------ 63 | %------------------------------------------------------------------ 64 | function mIndices = totalDeg(mPC, d, order) 65 | % totalDeg: Function computes indices of total degree PC 66 | % expansion. Output is a cell with indices for each order 67 | % 68 | % Reference: MATLAB polynomial chaos toolbox 69 | 70 | % declare cell to store indices for each order 71 | mIndices = cell(order+1,1); % multi-index 72 | mIndices{1} = zeros(1,d); % multi-index for length 0 73 | 74 | if d == 1 75 | for q=1:order 76 | mIndices{q+1} = q; 77 | end 78 | else 79 | for q = 1:order 80 | s = nchoosek(1:d+q-1,d-1); 81 | s1 = zeros(size(s,1),1); 82 | s2 = (d+q)+s1; 83 | mIndices{q+1} = flipud(diff([s1 s s2],1,2))-1; % -1 due to MATLAB indexing 84 | if sum(mIndices{q+1},2) ~= q*ones(nchoosek(d+q-1,d-1),1) 85 | error('The sum of each row has to be equal to q-th order'); 86 | end 87 | end 88 | end 89 | 90 | % convert orders to matrix 91 | mIndices = cell2mat(mIndices); 92 | 93 | end %endFunction 94 | %------------------------------------------------------------------ 95 | %------------------------------------------------------------------ 96 | function Psi = BasisEval(mPC, X) 97 | 98 | % check if data is empty and return constant in this case 99 | m = size(X,2); 100 | if m == 0 101 | Psi = mPC.poly.Evaluate(ones(m,1), 0, mPC.norm); 102 | else 103 | Psi = mPC.PolyVandermonde(X, 0, []); 104 | end 105 | 106 | end %endFunction 107 | %------------------------------------------------------------------ 108 | %------------------------------------------------------------------ 109 | function dxPsi = dxBasisEval(mPC, X) 110 | dxPsi = cell(mPC.d,1); 111 | for i=1:d 112 | dxPsi{i} = mPC.PolyVandermonde(X, 1, i); 113 | end 114 | dxPsi = cell2mat(dxPsi); 115 | end %endFunction 116 | %------------------------------------------------------------------ 117 | %------------------------------------------------------------------ 118 | function Psi = PolyVandermonde(mPC, X, k, grad_dim) 119 | 120 | % determine the number of samples and parameters 121 | [N, d] = size(X); 122 | 123 | % find multi-indices for total degree PC expansion 124 | mIndices = mPC.totalDeg(d, mPC.order); 125 | n_basis = size(mIndices,1); 126 | 127 | % declare matrix to store polynomial evaluations 128 | Psi = zeros(N, n_basis); 129 | 130 | % evaluate all basis functions 131 | for i=1:n_basis 132 | 133 | % extract row from basis_prod 134 | poly_ind = mIndices(i,:); 135 | 136 | % extract the value of the basis functions for all data values 137 | poly_all = zeros(N, d); 138 | for j=1:d 139 | if (k ~= 0) && (j==grad_dim) 140 | poly_all(:,j) = mPC.poly.GradEvaluate(X(:,j), poly_ind(j), k, mPC.norm); 141 | else 142 | poly_all(:,j) = mPC.poly.Evaluate(X(:,j), poly_ind(j), mPC.norm); 143 | end 144 | end 145 | 146 | % compute product of 1D basis functions and assign to PC_basis_value 147 | Psi(:,i) = prod(poly_all,2); 148 | 149 | end 150 | 151 | end %endFunction 152 | %------------------------------------------------------------------ 153 | %------------------------------------------------------------------ 154 | function S = Evaluate(mPC, X) 155 | 156 | % check dimension of input samples 157 | if size(X,2) ~= mPC.dim 158 | error('Inputs and poly dimension mismatch') 159 | end 160 | 161 | % evaluate S(x) = Psi(x)*coeff 162 | if isempty(mPC.basis_precomp) 163 | mPC.basis_precomp = mPC.BasisEval(X); 164 | end 165 | S = mPC.basis_precomp*mPC.coeff; 166 | 167 | end %endFunction 168 | %------------------------------------------------------------------ 169 | %------------------------------------------------------------------ 170 | function daS = Grad_a(mPC, X) 171 | 172 | % check dimension of input samples 173 | if size(X,2) ~= mPC.dim 174 | error('Inputs and poly dimension mismatch') 175 | end 176 | 177 | % evaluate \nabla_coeff S(x) = Psi(x) 178 | if isempty(mPC.basis_precomp) 179 | mPC.basis_precomp = mPC.BasisEval(X); 180 | end 181 | daS = mPC.basis_precomp; 182 | 183 | end %endFunction 184 | %------------------------------------------------------------------ 185 | %------------------------------------------------------------------ 186 | function dxS = Grad_x(mPC, X) 187 | 188 | % check dimension of input samples 189 | if size(X,2) ~= mPC.dim 190 | error('Inputs and poly dimension mismatch') 191 | end 192 | 193 | % evaluate (\nabla_x Psi(x))mPC.coeff,1,1,mPC.ncoeff 194 | if isempty(mPC.dxbasis_precomp) 195 | mPC.dxbasis_precomp = mPC.dxBasisEval(X); 196 | end 197 | 198 | % evaluate \nabla_x S(x) = (\nabla_x Psi(x))*coeff with reshape 199 | coeff_rep = repmat(reshape(mPC.coeff,1,1,mPC.ncoeff),size(X,1),size(X,2),1); 200 | dxS = sum(mPC.dxbasis_precomp.*coeff_rep,3); 201 | 202 | end %endFunction 203 | %------------------------------------------------------------------ 204 | %------------------------------------------------------------------ 205 | function d2aS = Hess_a(mPC, X) 206 | 207 | % find number of input samples 208 | N = size(X,1); 209 | 210 | % evaluate \nabla^2_coeff S(x) = 0 211 | d2aS = zeros(N, mPC.ncoeff, mPC.ncoeff); 212 | 213 | end %endFunction 214 | %------------------------------------------------------------------ 215 | %------------------------------------------------------------------ 216 | end %endMethods 217 | 218 | end %endClass 219 | -------------------------------------------------------------------------------- /TestProblems/algebraic_1.m: -------------------------------------------------------------------------------- 1 | % Author: Ricardo Baptista and Prasanth Nair 2 | % Date: March 2019 3 | % 4 | % See LICENSE.md for copyright information 5 | % 6 | 7 | function y_eval = algebraic_1(theta) 8 | % ALGEBRAIC_1: Function evaluates f(x) = (1 + sum(c_k*xi_k))^(-(d+1)) 9 | % for a set of input theta parameters in [-1,1]^d 10 | 11 | % Determine the number of samples and parameters 12 | [N,d] = size(theta); 13 | 14 | % Declare avector for the function evaluations 15 | y_eval = zeros(N,1); 16 | 17 | % Evaluate the function for all theta parameters 18 | for i=1:N 19 | 20 | % Evaluate the component coefficients 21 | c_k_comp = ((1:d) - 0.5)/d; 22 | c_k_vect = c_k_comp/(4*sum(c_k_comp)); 23 | 24 | % Transform inputs to [0,1] and compute inner product with c_k 25 | new_theta = 0.5*theta(i,:) + 0.5; 26 | algebraic_fn = sum(c_k_vect.*new_theta); 27 | 28 | % Assign result to y_eval 29 | y_eval(i) = (1 + algebraic_fn)^(-1*(d+1)); 30 | 31 | end 32 | 33 | % -- END OF FILE -- 34 | -------------------------------------------------------------------------------- /TestProblems/algebraic_2.m: -------------------------------------------------------------------------------- 1 | % Author: Ricardo Baptista and Prasanth Nair 2 | % Date: March 2019 3 | % 4 | % See LICENSE.md for copyright information 5 | % 6 | 7 | function y_eval = algebraic_2(theta) 8 | % ALGEBRAIC_2: Function evaluates f(x) = (1 + sum(c_k*xi_k))^(-(d+1)) 9 | % for a set of input theta parameters in [-1,1]^d 10 | 11 | % Determine the number of samples and parameters 12 | [N,d] = size(theta); 13 | 14 | % Declare avector for the function evaluations 15 | y_eval = zeros(N,1); 16 | 17 | % Evaluate the function for all theta parameters 18 | for i=1:N 19 | 20 | % Evaluate the component coefficients 21 | c_k_comp = 1./((1:d).^2); 22 | c_k_vect = c_k_comp/(4*sum(c_k_comp)); 23 | 24 | % Transform inputs to [0,1] and compute inner product with c_k 25 | new_theta = 0.5*theta(i,:) + 0.5; 26 | algebraic_fn = sum(c_k_vect.*new_theta); 27 | 28 | % Assign result to y_eval 29 | y_eval(i) = (1 + algebraic_fn)^(-1*(d+1)); 30 | 31 | end 32 | 33 | % -- END OF FILE -- 34 | -------------------------------------------------------------------------------- /TestProblems/algebraic_3.m: -------------------------------------------------------------------------------- 1 | % Author: Ricardo Baptista and Prasanth Nair 2 | % Date: March 2019 3 | % 4 | % See LICENSE.md for copyright information 5 | % 6 | 7 | function y_eval = algebraic_3(theta) 8 | % ALGEBRAIC_3: Function evaluates f(x) = (1 + sum(c_k*xi_k))^(-(d+1)) 9 | % for a set of input theta parameters in [-1,1]^d 10 | 11 | % Determine the number of samples and parameters 12 | [N,d] = size(theta); 13 | 14 | % Declare avector for the function evaluations 15 | y_eval = zeros(N,1); 16 | 17 | % Evaluate the function for all theta parameters 18 | for i=1:N 19 | 20 | % Evaluate the component coefficients 21 | c_k_comp = exp((1:d)*log(10^(-8))/d); 22 | c_k_vect = c_k_comp/(4*sum(c_k_comp)); 23 | 24 | % Transform inputs to [0,1] and compute inner product with c_k 25 | new_theta = 0.5*theta(i,:) + 0.5; 26 | algebraic_fn = sum(c_k_vect.*new_theta); 27 | 28 | % Assign result to y_eval 29 | y_eval(i) = (1 + algebraic_fn)^(-1*(d+1)); 30 | 31 | end 32 | 33 | % -- END OF FILE -- 34 | -------------------------------------------------------------------------------- /TestProblems/diff_2D_stochastic_forcing.m: -------------------------------------------------------------------------------- 1 | % Author: Ricardo Baptista and Prasanth Nair 2 | % Date: March 2019 3 | % 4 | % See LICENSE.md for copyright information 5 | % 6 | 7 | function [global_M, global_K, global_F, KL, p, e, t, int_p] = ... 8 | diff_2D_stochastic_forcing(n_par, sigma, lc, dim_lim) 9 | % DIFF_2D_STOCHASTIC_FORCING: Function assembles the 2D discretized 10 | % weak form of the parametrized diffusion equation based on a 11 | % Karhunen-Loeve expansion with a Gaussian correlation function 12 | % for the parameters 13 | % 14 | % Inputs: n_par - number of parameters in the problem 15 | % mean_d - mean of parameters 16 | % sigma_d - variance of parameters 17 | % lc - correlation length of parameters 18 | % dim_lim - dimensions of spatial coordinates 19 | 20 | %% Geometry and Boundary Conditions 21 | 22 | % Define rectangular geometry 23 | g = decsg([3 4 0 1 1 0 0 0 1 1]'); 24 | 25 | % Define the mesh for the geometry 26 | [p,e,t] = initmesh(g); 27 | [p,e,t] = refinemesh(g,p,e,t); 28 | fprintf('Created a mesh with %i nodes.\n', length(p)); 29 | 30 | % Get the indexes of interior/boundary FE nodes 31 | [ind_interior, ~] = getindexesMesh(p, dim_lim); 32 | 33 | % Set values of interior nodes 34 | int_p = p(:,ind_interior); 35 | 36 | %% Initial Solve of Deterministic PDE 37 | 38 | % Coefficients of elliptic PDE problem -div(c*grad(u))+a*u=f 39 | c = 1; 40 | a = 0; 41 | 42 | % Define the source term as a spatial function 43 | sf = '-1'; 44 | 45 | % Extract the Mass and Stiffness Matrices 46 | [K, ~, F] = assema(p,t,c,a,sf); % M_other is NULL 47 | [~, M, ~] = assema(p,t,c,1,sf); % M is a SPD matrix 48 | 49 | %% KL Expansion 50 | 51 | % Declare matrix for correlation evaluations 52 | szmesh=size(p,2); 53 | C = zeros(szmesh, szmesh); 54 | 55 | % Evaluate the correlation function 56 | for i=1:szmesh 57 | for j=1:szmesh 58 | C(i,j) = exp(-(p(1,i)-p(1,j))^2/(2*lc(1)^2)-(p(2,i)-p(2,j))^2/(2*lc(2)^2)); 59 | end 60 | end 61 | C = sigma^2*C; 62 | 63 | % Find the eigenvalues of the KL expansion 64 | W = M*C*M; 65 | W = 0.5*(W+W'); % Symmetrization (otherwise W is not perfectly symmetric) 66 | [VV,DD] = eig(W,full(M)); 67 | 68 | % Check that the eigenvectors are orthonormalized wrt the mass matrix: 69 | % VV'*M*VV 70 | 71 | % Extract the eigenvalues and sort by increasing order 72 | diagDD = diag(DD); 73 | eigenvalKL = sort(diagDD); 74 | 75 | % Extract the spatial modes of the KL expansion 76 | ksort = diag(eigenvalKL); 77 | spModesKL = VV(:,szmesh-n_par+1:szmesh)*... 78 | sqrt(ksort(szmesh-n_par+1:szmesh,szmesh-n_par+1:szmesh)); 79 | 80 | % Extract the KL expansion 81 | KL = spModesKL(ind_interior,:); 82 | 83 | % Extract mesh parameters 84 | nbTriangles = size(t,2); 85 | A = ones(3,3); 86 | RFcentroids = zeros(nbTriangles,n_par); 87 | 88 | % Interpolate the Basis Functions on the Triangular Mesh 89 | for m=1:n_par 90 | RFm=spModesKL(:,m); 91 | for k=1:nbTriangles 92 | ii=t(1:3,k); 93 | alpha=RFm(ii); 94 | coordCentroid(1)=mean(p(1,ii)); 95 | coordCentroid(2)=mean(p(2,ii)); 96 | A(:,2)=p(1,ii)'; 97 | A(:,3)=p(2,ii)'; 98 | beta=A\alpha; 99 | RFcentroids(k,m)=beta(1)+beta(2)*coordCentroid(1)+beta(3)*coordCentroid(2); 100 | end 101 | end 102 | 103 | %% Final Solution of PDE 104 | 105 | % Extract stiffness matrices for KL expansion 106 | KKL = cell(n_par,1); 107 | for m=1:n_par 108 | cm = RFcentroids(:,n_par-m+1)'; 109 | [KKL{m}, ~, ~] = assema(p, t, cm, 0, zeros(nbTriangles,1)'); 110 | end 111 | 112 | % Extract right hand side vectors for KL expansion 113 | FKL = cell(n_par,1); 114 | for m=1:n_par 115 | cm = RFcentroids(:,n_par-m+1)'; 116 | [~, ~, FKL{m}] = assema(p, t, 0, 0, cm); 117 | end 118 | 119 | % Extract mass/stiffness matrix elements for interior nodes 120 | M_int = M(ind_interior,ind_interior); % Mass Matrix 121 | K_int = K(ind_interior,ind_interior); % (Main) Stiffness Matrix 122 | F_int = F(ind_interior); 123 | 124 | % Extract KL stiffness matrix elements for interior nodes 125 | KKL_int = cell(n_par, 1); 126 | FKL_int = cell(n_par, 1); 127 | for m = 1:n_par 128 | KKL_int{m} = KKL{m}(ind_interior,ind_interior); 129 | FKL_int{m} = FKL{m}(ind_interior); 130 | end 131 | 132 | % Assemble terms for function call 133 | global_M = M_int; 134 | global_K = [{K_int}; KKL_int]; 135 | global_F = [{F_int}; FKL_int]; 136 | 137 | end 138 | 139 | function [ind_interior,ind_boundary] = getindexesMesh(p, dim_lim) 140 | 141 | xmin=dim_lim(1); 142 | xmax=dim_lim(2); 143 | 144 | nbTot=size(p,2); 145 | 146 | cpt_boundary=0; 147 | cpt_interior=0; 148 | for i=1:nbTot 149 | if ((p(1,i)==xmin)|(p(1,i)==xmax)|(p(2,i)==xmin)|(p(2,i)==xmax)) 150 | cpt_boundary=cpt_boundary+1; 151 | ind_boundary(cpt_boundary)=i; 152 | else 153 | cpt_interior=cpt_interior+1; 154 | ind_interior(cpt_interior)=i; 155 | end 156 | end 157 | 158 | end 159 | -------------------------------------------------------------------------------- /TestProblems/diffusion_equation_stochastic_forcing.m: -------------------------------------------------------------------------------- 1 | % Author: Ricardo Baptista and Prasanth Nair 2 | % Date: March 2019 3 | % 4 | % See LICENSE.md for copyright information 5 | % 6 | 7 | function soln_x_loc = diffusion_equation_stochastic_forcing(theta) 8 | % DIFFUSION_EQUATION_STOCHASTIC_FORCING: Function evaluates the 2D 9 | % stochastic diffusion equation with KL expansions for the diffusivity 10 | % and the forcing term at different theta values based on the created 11 | % model and the declared parameters. 12 | 13 | % flip theta 14 | theta = theta'; 15 | 16 | %% Declare Constants 17 | 18 | % Constants for the Diffusion Equation 19 | sigma = 0.7; 20 | corl = [0.05, 0.05]; 21 | 22 | % Quantity of Interest in Spatial Domain 23 | x_loc = [0.5, 0.5]; 24 | 25 | % Define 1D Spatial Dimensions 26 | dim_lim = [0,1]; 27 | 28 | % Determine the number of parameters and points 29 | n_par = size(theta,1); 30 | n_pts = size(theta,2); 31 | 32 | %% Evaluate Governing Equations 33 | 34 | % Find file_name 35 | file_name = ['../TestProblems/Diffusion_SForce_s' num2str(sigma) '_p' num2str(n_par) '.mat']; 36 | 37 | % Extract global K and F matrices and mesh terms (p & t) 38 | if exist(file_name , 'file') 39 | load(file_name) 40 | else 41 | [~,global_K,global_F,~,~,~,~,int_p] = diff_2D_stochastic_forcing(n_par/2, sigma, corl, dim_lim); 42 | save(file_name,'global_K','global_F','int_p'); 43 | end 44 | 45 | %% Evaluate Diffusion PDE 46 | 47 | % Declare vector for solution 48 | soln_x_loc = zeros(n_pts,1); 49 | 50 | % Divide theta parameters 51 | theta_M = theta(1:n_par/2,:); 52 | theta_F = theta(n_par/2+1:end,:); 53 | 54 | % Extract triangular cell containing interpolation point 55 | X = int_p(1,:)'; 56 | Y = int_p(2,:)'; 57 | tri = delaunay (X, Y); 58 | idx = tsearchn([X, Y], tri, [x_loc(1), x_loc(2)]); 59 | pts = tri(idx, :); 60 | 61 | for i=1:n_pts 62 | 63 | % Evaluate the leading matrix 64 | K_matrix = global_K{1}; 65 | for j=1:n_par/2 66 | K_matrix = K_matrix + global_K{j+1}*theta_M(j,i); 67 | end 68 | 69 | % Evaluate the source term 70 | F_matrix = global_F{1}; 71 | for j=1:n_par/2 72 | F_matrix = F_matrix + global_F{j+1}*theta_F(j,i); 73 | end 74 | 75 | % Determine the exact solution 76 | soln = K_matrix\F_matrix; 77 | 78 | % Extract value at location of interest (x_loc) by interpolation 79 | F = scatteredInterpolant(X(pts), Y(pts), soln(pts)); 80 | soln_x_loc(i) = F(x_loc(1), x_loc(2)); 81 | 82 | end 83 | 84 | end 85 | 86 | % -- END OF FILE -- 87 | -------------------------------------------------------------------------------- /scripts/create_plots.m: -------------------------------------------------------------------------------- 1 | % Author: Ricardo Baptista and Prasanth Nair 2 | % Date: March 2019 3 | % 4 | % See LICENSE.md for copyright information 5 | % 6 | 7 | function create_plots(test) 8 | % PLOTTING: Plot convergence trends for statistics and sparsity boxplots 9 | 10 | % load parameters 11 | d = test.d; 12 | order = test.order; 13 | func_str = test.func_str; 14 | N = test.N; 15 | 16 | % load data 17 | load(['../results/' func_str '_d' num2str(d) '_ord' num2str(order)]); 18 | 19 | % load sample data 20 | load(['../results/' func_str '_d' num2str(d) '_samples'], 'MC_out', 'QMC_out'); 21 | 22 | %% Plot results 23 | 24 | % Declare mean and standard error functions 25 | Mout = @(c, field) cell2mat(cellfun(@(x) x.(field), c, 'uniformoutput',false)); 26 | pmean = @(c, field) mean(Mout(c, field),2); 27 | pste = @(c, field) 1.96*std(Mout(c, field),[],2)/sqrt(size(c,2)); 28 | 29 | % define colors 30 | gColor = [85;170;170]/255; 31 | bColor = [60;60;230]/255; 32 | rColor = [200;0;0]/255; 33 | pColor = [170;0;170]/255; 34 | yColor = [225;125;0]/255; 35 | 36 | % plot error in mean 37 | figure 38 | hold on 39 | grid on 40 | errorbar(N, pmean(OMP_out,'MeanE'), pste(OMP_out,'MeanE'), '-o', 'Color', gColor, 'LineWidth', 2, 'MarkerSize', 8, 'DisplayName', 'OMP'); 41 | errorbar(N, pmean(OMPN_out,'MeanE'), pste(OMPN_out,'MeanE'), '-d', 'Color', gColor, 'LineWidth', 2, 'MarkerSize', 8, 'DisplayName', 'OMPN'); 42 | errorbar(N, pmean(BPDN_out,'MeanE'), pste(BPDN_out,'MeanE'), '-o', 'Color', bColor, 'LineWidth', 2, 'MarkerSize', 8, 'DisplayName', 'BPDN'); 43 | errorbar(N, pmean(RGA_out,'MeanE'), pste(RGA_out,'MeanE'), '-o', 'Color', rColor, 'LineWidth', 2, 'MarkerSize', 8, 'DisplayName', 'RGA'); 44 | errorbar(N, pmean(MC_out,'MeanE'), pste(MC_out,'MeanE'), '-.o', 'Color', pColor, 'LineWidth', 2, 'MarkerSize', 8, 'DisplayName', 'MC'); 45 | errorbar(N, pmean(QMC_out,'MeanE'), pste(QMC_out,'MeanE'), '-.o', 'Color', yColor, 'LineWidth', 2, 'MarkerSize', 8, 'DisplayName', 'QMC'); 46 | xlabel('Number of Samples, N') 47 | ylabel('Relative Mean Error') 48 | legend('show', 'location', 'southwest') 49 | xlim([0,max(N)]) 50 | set(gca,'YScale','log') 51 | set(gca,'YMinorGrid','Off') 52 | hold off 53 | print('-depsc',['../results/' func_str '_MeanErr_vs_N']) 54 | 55 | % plot error in standard deviation 56 | figure 57 | hold on 58 | grid on 59 | errorbar(N, pmean(OMP_out,'StdE'), pste(OMP_out,'StdE'), '-o', 'Color', gColor, 'LineWidth', 2, 'MarkerSize', 8, 'DisplayName', 'OMP'); 60 | errorbar(N, pmean(OMPN_out,'StdE'), pste(OMPN_out,'StdE'), '-d', 'Color', gColor, 'LineWidth', 2, 'MarkerSize', 8, 'DisplayName', 'OMPN'); 61 | errorbar(N, pmean(BPDN_out,'StdE'), pste(BPDN_out,'StdE'), '-o', 'Color', bColor, 'LineWidth', 2, 'MarkerSize', 8, 'DisplayName', 'BPDN'); 62 | errorbar(N, pmean(RGA_out,'StdE'), pste(RGA_out,'StdE'), '-o', 'Color', rColor, 'LineWidth', 2, 'MarkerSize', 8, 'DisplayName', 'RGA'); 63 | errorbar(N, pmean(MC_out,'StdE'), pste(MC_out,'StdE'), '-.o', 'Color', pColor, 'LineWidth', 2, 'MarkerSize', 8, 'DisplayName', 'MC'); 64 | errorbar(N, pmean(QMC_out,'StdE'), pste(QMC_out,'StdE'), '-.o', 'Color', yColor, 'LineWidth', 2, 'MarkerSize', 8, 'DisplayName', 'QMC'); 65 | xlabel('Number of Samples, N') 66 | ylabel('Relative Standard Deviation Error') 67 | legend('show', 'location', 'southwest') 68 | xlim([0,max(N)]) 69 | set(gca,'YScale','log') 70 | set(gca,'YMinorGrid','Off') 71 | hold off 72 | print('-depsc',['../results/' func_str '_StdErr_vs_N']) 73 | 74 | % plot test error 75 | figure 76 | hold on 77 | grid on 78 | errorbar(N, pmean(OMP_out,'TestE'), pste(OMP_out,'TestE'), '-o', 'Color', gColor, 'LineWidth', 2, 'MarkerSize', 8, 'DisplayName', 'OMP'); 79 | errorbar(N, pmean(OMPN_out,'TestE'), pste(OMPN_out,'TestE'), '-d', 'Color', gColor, 'LineWidth', 2, 'MarkerSize', 8, 'DisplayName', 'OMPN'); 80 | errorbar(N, pmean(BPDN_out,'TestE'), pste(BPDN_out,'TestE'), '-o', 'Color', bColor, 'LineWidth', 2, 'MarkerSize', 8, 'DisplayName', 'BPDN'); 81 | errorbar(N, pmean(RGA_out,'TestE'), pste(RGA_out,'TestE'), '-o', 'Color', rColor, 'LineWidth', 2, 'MarkerSize', 8, 'DisplayName', 'RGA'); 82 | xlabel('Number of Samples, N') 83 | ylabel('Test Set Error') 84 | legend('show', 'location', 'southwest') 85 | xlim([0,max(N)]) 86 | set(gca,'YScale','log') 87 | set(gca,'YMinorGrid','Off') 88 | hold off 89 | print('-depsc',['../results/' func_str '_TestErr_vs_N']) 90 | 91 | % plot sparsity 92 | figure 93 | hold on 94 | grid on 95 | errorbar(N, pmean(OMP_out,'spars'), pste(OMP_out,'spars'), '-o', 'Color', gColor, 'LineWidth', 2, 'MarkerSize', 8, 'DisplayName', 'OMP'); 96 | errorbar(N, pmean(OMPN_out,'spars'), pste(OMPN_out,'spars'), '-d', 'Color', gColor, 'LineWidth', 2, 'MarkerSize', 8, 'DisplayName', 'OMPN'); 97 | errorbar(N, pmean(BPDN_out,'spars'), pste(BPDN_out,'spars'), '-o', 'Color', bColor, 'LineWidth', 2, 'MarkerSize', 8, 'DisplayName', 'BPDN'); 98 | errorbar(N, pmean(RGA_out,'spars'), pste(RGA_out,'spars'), '-o', 'Color', rColor, 'LineWidth', 2, 'MarkerSize', 8, 'DisplayName', 'RGA'); 99 | xlabel('Number of Samples, N') 100 | ylabel('$\|\mathbf{c}\|_{0}$') 101 | legend('show', 'location', 'southeast') 102 | xlim([0,max(N)]) 103 | set(gca,'YMinorGrid','Off') 104 | hold off 105 | print('-depsc',['../results/' func_str '_Spars_vs_N']) 106 | 107 | % plot runtime 108 | figure 109 | hold on 110 | grid on 111 | errorbar(N, pmean(OMP_out,'time'), pste(OMP_out,'time'), '-o', 'Color', gColor, 'LineWidth', 2, 'MarkerSize', 8, 'DisplayName', 'OMP'); 112 | errorbar(N, pmean(OMPN_out,'time'), pste(OMPN_out,'time'), '-d', 'Color', gColor, 'LineWidth', 2, 'MarkerSize', 8, 'DisplayName', 'OMPN'); 113 | errorbar(N, pmean(BPDN_out,'time'), pste(BPDN_out,'time'), '-o', 'Color', bColor, 'LineWidth', 2, 'MarkerSize', 8, 'DisplayName', 'BPDN'); 114 | errorbar(N, pmean(RGA_out,'time'), pste(RGA_out,'time'), '-o', 'Color', rColor, 'LineWidth', 2, 'MarkerSize', 8, 'DisplayName', 'RGA'); 115 | xlabel('Number of Samples, N') 116 | ylabel('Runtime, T') 117 | legend('show', 'location', 'southeast') 118 | xlim([0,max(N)]) 119 | set(gca,'YScale','log') 120 | set(gca,'YMinorGrid','Off') 121 | hold off 122 | print('-depsc',['../results/' func_str '_Runtime_vs_N']) 123 | 124 | end 125 | 126 | % -- END OF FILE -- 127 | -------------------------------------------------------------------------------- /scripts/example_run.m: -------------------------------------------------------------------------------- 1 | % Polynomial Chaos Randomized Greedy Algorithm 2 | % 3 | % Copyright (C) 2019 R. Baptista & P. Nair 4 | % 5 | % GreedyPC is free software: you can redistribute it and/or modify 6 | % it under the terms of the GNU 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 | % GreedyPC 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 General Public License for more details. 14 | % 15 | % You should have received a copy of the GNU General Public License 16 | % along with GreedyPC. If not, see . 17 | % 18 | % Copyright (C) 2019 MIT & University of Toronto 19 | % Authors: Ricardo Baptista & Prasanth Nair 20 | % E-mails: rsb@mit.edu or ricarsb@gmail.com & pbn@utias.utoronto.ca 21 | % 22 | 23 | % Test script for Least Squares PCE code 24 | clear; close all; clc 25 | 26 | addpath('../SpectralToolbox') 27 | addpath('../TestProblems') 28 | addpath('../Methods') 29 | addpath('../tools') 30 | 31 | % define test parameters 32 | d = 5; 33 | order = 3; 34 | grid_level = 5; 35 | basis = 'Legendre'; 36 | func = @(x) algebraic_1(x); 37 | N = floor(logspace(1,3,10)); 38 | 39 | % generate training data: uniform inputs on [-1,1] 40 | Xall = 2*rand(max(N), d) - 1; 41 | Yall = func(Xall); 42 | 43 | % call sparse grid to determine the test samples 44 | [XTest, wTest] = sparse_grid(d, grid_level, 'unif'); 45 | YTest = func(XTest); 46 | 47 | % declare vectors to store results 48 | TestE = zeros(length(N),5); 49 | MeanE = zeros(length(N),5); 50 | StdE = zeros(length(N),5); 51 | 52 | for i=1:length(N) 53 | 54 | fprintf('Test: N = %d\n', N(i)); 55 | 56 | % extract samples 57 | X = Xall(1:N(i),:); 58 | Y = Yall(1:N(i)); 59 | 60 | % train PC model using LeastSquares 61 | FPC = LeastSquaresPCE(d, order, basis); 62 | FPC = FPC.fit(X,Y); 63 | [TestE(i,1), MeanE(i,1), StdE(i,1)] = FPC.testErr(XTest, YTest, wTest); 64 | 65 | % train PC model using BPDN 66 | BPDN = L1Minimization(d, order, basis); 67 | BPDN = BPDN.fit(X,Y); 68 | [TestE(i,2), MeanE(i,2), StdE(i,2)] = BPDN.testErr(XTest, YTest, wTest); 69 | 70 | % train PC model using traditional OMP 71 | OMP = OrthogonalMatchingPursuit(d, order, basis, 'old'); 72 | OMP = OMP.fit(X,Y); 73 | [TestE(i,3), MeanE(i,3), StdE(i,3)] = OMP.testErr(XTest, YTest, wTest); 74 | 75 | % train PC model using OMP with optimal basis selection strategy 76 | OMPN = OrthogonalMatchingPursuit(d, order, basis, 'opt'); 77 | OMPN = OMPN.fit(X,Y); 78 | [TestE(i,4), MeanE(i,4), StdE(i,4)] = OMPN.testErr(XTest, YTest, wTest); 79 | 80 | % train PC model using Randomized Greedy algorithm 81 | RGA = RandomizedGreedy(d, order, basis); 82 | RGA = RGA.fit(X,Y); 83 | [TestE(i,5), MeanE(i,5), StdE(i,5)] = RGA.testErr(XTest, YTest, wTest); 84 | 85 | end 86 | 87 | % plot results 88 | figure('position',[0,0,1200,600]); 89 | 90 | subplot(1,3,1) 91 | loglog(N, MeanE, '-o', 'MarkerSize', 10) 92 | xlabel('$N$') 93 | ylabel('Mean Error') 94 | legend({'FPC','BPDN','OMP','OMPN','RGA'}) 95 | 96 | subplot(1,3,2) 97 | loglog(N, StdE, '-o', 'MarkerSize', 10) 98 | xlabel('$N$') 99 | ylabel('Std Error') 100 | legend({'FPC','BPDN','OMP','OMPN','RGA'}) 101 | 102 | subplot(1,3,3) 103 | loglog(N, TestE, '-o', 'MarkerSize', 10) 104 | xlabel('$N$') 105 | ylabel('Test Set Error') 106 | legend({'FPC','BPDN','OMP','OMPN','RGA'}) 107 | 108 | % -- END OF FILE -- -------------------------------------------------------------------------------- /scripts/post_process_lowmem.m: -------------------------------------------------------------------------------- 1 | % Author: Ricardo Baptista and Prasanth Nair 2 | % Date: March 2019 3 | % 4 | % See LICENSE.md for copyright information 5 | % 6 | 7 | function post_process_lowmem(test) 8 | % POST_PROCESS_LOWMEM: Runs the post processing using the 9 | % the sparse grid model evaluations for the FPC, BPDN, OMP 10 | % OMPN and RGA algorithms after running the script 11 | % run_algorithms_lowmem.m 12 | 13 | % extract parameters 14 | d = test.d; 15 | order = test.order; 16 | grid_level = test.grid_level; 17 | func = test.func; 18 | func_str = test.func_str; 19 | N = test.N; 20 | n_trials = test.n_trials; 21 | 22 | % load data from file 23 | file_name = ['../results/' func_str '_d' num2str(d) '_ord' num2str(order) '_lowmemory']; 24 | load(file_name,'FPC_out','BPDN_out','OMP_out','OMPN_out','RGA_out'); 25 | models = {FPC_out, BPDN_out, OMP_out, OMPN_out, RGA_out}; 26 | 27 | % call sparse grid to determine the test samples 28 | [XTest, wTest] = sparse_grid(d, grid_level, 'unif'); 29 | YTest = func(XTest); 30 | 31 | % evaluate all basis functions at XTest 32 | Psi_ = FPC_out{1,1}.PCE.poly.BasisEval(XTest); 33 | 34 | for k=1:length(models) 35 | 36 | % extract model 37 | model_out = models{k}; 38 | 39 | for i=1:length(N) 40 | for j=1:n_trials 41 | 42 | fprintf('Test: N = %d, run = %d\n', N(i), j); 43 | 44 | % extract PC expansion 45 | PC = model_out{i,j}.PCE; 46 | 47 | % evaluate expansion at XTest 48 | coeff = zeros(size(Psi_,2),1); 49 | coeff(PC.indices) = PC.coeffs; 50 | Yhat = Psi_*coeff; 51 | 52 | % compute relative weighted test error 53 | L2Err = (YTest - Yhat).^2; 54 | model_out{i,j}.TestE = (wTest*L2Err)/(wTest*(YTest.^2)); 55 | 56 | % evaluate mean and standard deviation of yTest 57 | meanTest = wTest*YTest; 58 | stdTest = sqrt(wTest*YTest.^2 - meanTest^2); 59 | 60 | % evaluate mean and standard deviation of PC expansion 61 | if PC.indices(1) == 1 62 | meanPC = PC.coeffs(1); 63 | else 64 | meanPC = mean(Yhat); 65 | end 66 | stdPC = sqrt(sum((PC.coeffs).^2) - meanPC^2); 67 | 68 | % compute relative mean and standard deviation error 69 | model_out{i,j}.MeanE = norm(meanPC - meanTest)/norm(meanTest); 70 | model_out{i,j}.StdE = norm(stdPC - stdTest)/norm(stdTest); 71 | 72 | model_out{i,j}.PCE = []; 73 | 74 | end 75 | end 76 | 77 | % save model_out 78 | models{k} = model_out; 79 | 80 | end 81 | 82 | % extract models 83 | FPC_out = models{1}; 84 | BPDN_out = models{2}; 85 | OMP_out = models{3}; 86 | OMPN_out = models{4}; 87 | RGA_out = models{5}; 88 | 89 | % save matlab file with results 90 | save(['../results/' func_str '_d' num2str(d) '_ord' num2str(order)]); 91 | 92 | end 93 | -------------------------------------------------------------------------------- /scripts/run_algorithms.m: -------------------------------------------------------------------------------- 1 | % Author: Ricardo Baptista and Prasanth Nair 2 | % Date: March 2019 3 | % 4 | % See LICENSE.md for copyright information 5 | % 6 | 7 | function run_algorithms(test) 8 | % RUN_ALGORITHMS: Runs the linear regression algorithms 9 | % on the test case specified in the test struct. The results 10 | % are saved in the results/test_name file. 11 | 12 | % extract parameters 13 | d = test.d; 14 | order = test.order; 15 | grid_level = test.grid_level; 16 | basis = test.basis; 17 | func = test.func; 18 | func_str = test.func_str; 19 | N = test.N; 20 | n_trials = test.n_trials; 21 | 22 | % call sparse grid to determine the test samples 23 | [XTest, wTest] = sparse_grid(d, grid_level, 'unif'); 24 | YTest = func(XTest); 25 | 26 | % declare vectors to store results 27 | FPC_out = cell(length(N), n_trials); 28 | BPDN_out = cell(length(N), n_trials); 29 | OMP_out = cell(length(N), n_trials); 30 | OMPN_out = cell(length(N), n_trials); 31 | RGA_out = cell(length(N), n_trials); 32 | 33 | % define grid of parameters 34 | [Run, Nm] = meshgrid(1:n_trials, N); 35 | 36 | % Run for each algorithm 37 | n_proc = 10; 38 | c = parcluster('local'); 39 | c.NumWorkers = n_proc; 40 | parpool(n_proc); 41 | 42 | parfor i=1:length(N)*n_trials 43 | 44 | fprintf('Test: N = %d, run = %d\n', Nm(i), Run(i)); 45 | 46 | % generate training data: uniform inputs on [-1,1] 47 | X = 2*rand(Nm(i), d) - 1; 48 | Y = func(X); 49 | 50 | % setup structs to save results 51 | FPCpp = struct; 52 | BPDNpp = struct; 53 | OMPpp = struct; 54 | OMPNpp = struct; 55 | RGApp = struct; 56 | 57 | % train PC model using LeastSquares 58 | FPC = LeastSquaresPCE(d, order, basis); 59 | tic; FPC = FPC.fit(X,Y); FPCpp.time = toc; 60 | [FPCpp.TestE, FPCpp.MeanE, FPCpp.StdE] = FPC.testErr(XTest, YTest, wTest); 61 | FPCpp.spars = length(FPC.indices); 62 | 63 | % train PC model using BPDN 64 | BPDN = L1Minimization(d, order, basis); 65 | tic; BPDN = BPDN.fit(X,Y); BPDNpp.time = toc; 66 | [BPDNpp.TestE, BPDNpp.MeanE, BPDNpp.StdE] = BPDN.testErr(XTest, YTest, wTest); 67 | BPDNpp.spars = length(BPDN.indices); 68 | 69 | % train PC model using traditional OMP 70 | OMP = OrthogonalMatchingPursuit(d, order, basis, 'old'); 71 | tic; OMP = OMP.fit(X,Y); OMPpp.time = toc; 72 | [OMPpp.TestE, OMPpp.MeanE, OMPpp.StdE] = OMP.testErr(XTest, YTest, wTest); 73 | OMPpp.spars = length(OMP.indices); 74 | 75 | % train PC model using OMP with optimal basis selection strategy 76 | OMP = OrthogonalMatchingPursuit(d, order, basis, 'opt'); 77 | tic; OMP = OMP.fit(X,Y); OMPNpp.time = toc; 78 | [OMPNpp.TestE, OMPNpp.MeanE, OMPNpp.StdE] = OMP.testErr(XTest, YTest, wTest); 79 | OMPNpp.spars = length(OMP.indices); 80 | 81 | % train PC model using Randomized Greedy algorithm 82 | RGA = RandomizedGreedy(d, order, basis); 83 | tic; RGA = RGA.fit(X,Y); RGApp.time = toc; 84 | [RGApp.TestE, RGApp.MeanE, RGApp.StdE] = RGA.testErr(XTest, YTest, wTest); 85 | RGApp.spars = length(RGA.indices); 86 | 87 | % save structs 88 | FPC_out{i} = FPCpp; 89 | BPDN_out{i} = BPDNpp; 90 | OMP_out{i} = OMPpp; 91 | OMPN_out{i} = OMPNpp; 92 | RGA_out{i} = RGApp; 93 | 94 | end 95 | 96 | delete(gcp('nocreate')) 97 | 98 | % save matlab file with results 99 | save(['../results/' func_str '_d' num2str(d) '_ord' num2str(order)]); 100 | 101 | end 102 | -------------------------------------------------------------------------------- /scripts/run_algorithms_lowmem.m: -------------------------------------------------------------------------------- 1 | % Author: Ricardo Baptista and Prasanth Nair 2 | % Date: March 2019 3 | % 4 | % See LICENSE.md for copyright information 5 | % 6 | 7 | function run_algorithms_lowmem(test) 8 | % RUN_ALGORITHMS_LOWMEM: Runs the linear regression algorithms 9 | % on the test case specified in the test struct without any 10 | % sparse grid post_processing. The results are saved in the 11 | % results/test_name file. 12 | 13 | % extract parameters 14 | d = test.d; 15 | order = test.order; 16 | basis = test.basis; 17 | func = test.func; 18 | func_str = test.func_str; 19 | N = test.N; 20 | n_trials = test.n_trials; 21 | 22 | % declare vectors to store results 23 | FPC_out = cell(length(N), n_trials); 24 | BPDN_out = cell(length(N), n_trials); 25 | OMP_out = cell(length(N), n_trials); 26 | OMPN_out = cell(length(N), n_trials); 27 | RGA_out = cell(length(N), n_trials); 28 | 29 | % define grid of parameters 30 | [Run, Nm] = meshgrid(1:n_trials, N); 31 | 32 | % Run for each algorithm 33 | n_proc = 10; 34 | c = parcluster('local'); 35 | c.NumWorkers = n_proc; 36 | parpool(n_proc); 37 | 38 | parfor i=1:length(N)*n_trials 39 | 40 | fprintf('Test: N = %d, run = %d\n', Nm(i), Run(i)); 41 | 42 | % generate training data: uniform inputs on [-1,1] 43 | X = 2*rand(Nm(i), d) - 1; 44 | Y = func(X); 45 | 46 | % setup structs to save results 47 | FPCpp = struct; 48 | BPDNpp = struct; 49 | OMPpp = struct; 50 | OMPNpp = struct; 51 | RGApp = struct; 52 | 53 | % train PC model using LeastSquares 54 | FPC = LeastSquaresPCE(d, order, basis); 55 | tic; FPC = FPC.fit(X,Y); FPCpp.time = toc; 56 | FPCpp.spars = length(FPC.indices); 57 | FPCpp.PCE = FPC; 58 | 59 | % train PC model using BPDN 60 | BPDN = L1Minimization(d, order, basis); 61 | tic; BPDN = BPDN.fit(X,Y); BPDNpp.time = toc; 62 | BPDNpp.spars = length(BPDN.indices); 63 | BPDNpp.PCE = BPDN; 64 | 65 | % train PC model using traditional OMP 66 | OMP = OrthogonalMatchingPursuit(d, order, basis, 'old'); 67 | tic; OMP = OMP.fit(X,Y); OMPpp.time = toc; 68 | OMPpp.spars = length(OMP.indices); 69 | OMPpp.PCE = OMP; 70 | 71 | % train PC model using OMP with optimal basis selection strategy 72 | OMP = OrthogonalMatchingPursuit(d, order, basis, 'opt'); 73 | tic; OMP = OMP.fit(X,Y); OMPNpp.time = toc; 74 | OMPNpp.spars = length(OMP.indices); 75 | OMPNpp.PCE = OMP; 76 | 77 | % train PC model using Randomized Greedy algorithm 78 | RGA = RandomizedGreedy(d, order, basis); 79 | tic; RGA = RGA.fit(X,Y); RGApp.time = toc; 80 | RGApp.spars = length(RGA.indices); 81 | RGApp.PCE = RGA; 82 | 83 | % save structs 84 | FPC_out{i} = FPCpp; 85 | BPDN_out{i} = BPDNpp; 86 | OMP_out{i} = OMPpp; 87 | OMPN_out{i} = OMPNpp; 88 | RGA_out{i} = RGApp; 89 | 90 | end 91 | 92 | delete(gcp('nocreate')) 93 | 94 | % save matlab file with results 95 | save(['../results/' func_str '_d' num2str(d) '_ord' num2str(order) '_lowmemory']); 96 | 97 | % run post-processing 98 | post_process_lowmem(test) 99 | 100 | end 101 | -------------------------------------------------------------------------------- /scripts/run_sampling.m: -------------------------------------------------------------------------------- 1 | % Author: Ricardo Baptista and Prasanth Nair 2 | % Date: March 2019 3 | % 4 | % See LICENSE.md for copyright information 5 | % 6 | 7 | function run_sampling(test) 8 | % RUN_SAMPLING: Runs the sampling based methods (MC and QMC) 9 | % on the test case specified in the test struct. The results 10 | % are saved in the results/test_name file. 11 | 12 | % extract parameters 13 | d = test.d; 14 | order = test.order; 15 | grid_level = test.grid_level; 16 | basis = test.basis; 17 | func = test.func; 18 | func_str = test.func_str; 19 | N = test.N; 20 | n_trials = test.MCtrials; 21 | 22 | % call sparse grid to determine the test samples 23 | [XTest, wTest] = sparse_grid(d, grid_level, 'unif'); 24 | YTest = func(XTest); 25 | 26 | % evaluate mean and standard deviation of yTest 27 | meanTest = wTest*YTest; 28 | stdTest = sqrt(wTest*YTest.^2 - meanTest^2); 29 | 30 | % declare vectors to store results 31 | MC_out = cell(length(N), n_trials); 32 | QMC_out = cell(length(N), 1); 33 | 34 | % define grid of parameters 35 | [Run, Nm] = meshgrid(1:n_trials, N); 36 | 37 | % Run for each algorithm 38 | n_proc = 10; 39 | c = parcluster('local'); 40 | c.NumWorkers = n_proc; 41 | parpool(n_proc); 42 | 43 | %% Monte Carlo Sampling 44 | parfor i=1:length(N)*n_trials 45 | 46 | % setup structs to save results 47 | MCpp = struct; 48 | 49 | % generate training data: uniform inputs on [-1,1] 50 | X = 2*rand(Nm(i), d) - 1; 51 | Y = func(X); 52 | 53 | % evaluate statistics 54 | meanMC = mean(Y); 55 | stdMC = sqrt(mean(Y.^2) - meanMC^2); 56 | 57 | % Evaluate statistics 58 | MCpp.MeanE = norm(meanMC - meanTest)/norm(meanTest); 59 | MCpp.StdE = norm(stdMC - stdTest)/norm(stdTest); 60 | 61 | % save struct 62 | MC_out{i} = MCpp; 63 | 64 | end 65 | 66 | % check if sobol is in current path 67 | if exist('i4_sobol_generate','file') ~= 2 68 | error('Please add Sobol scripts to path - see README') 69 | end 70 | 71 | %% Quasi Monte Carlo (Sobol) Sampling 72 | parfor i=1:length(N) 73 | 74 | % setup structs to save results 75 | QMCpp = struct; 76 | 77 | % Generate samples 78 | X = 2*i4_sobol_generate(d, N(i), 0)' - 1; 79 | Y = func(X); 80 | 81 | % evaluate statistics 82 | meanQMC = mean(Y); 83 | stdQMC = sqrt(mean(Y.^2) - meanQMC^2); 84 | 85 | % Evaluate statistics 86 | QMCpp.MeanE = norm(meanQMC - meanTest)/norm(meanTest); 87 | QMCpp.StdE = norm(stdQMC - stdTest)/norm(stdTest); 88 | 89 | % save struct 90 | QMC_out{i} = QMCpp; 91 | 92 | end 93 | 94 | delete(gcp('nocreate')) 95 | 96 | % save matlab file with results 97 | save(['../results/' func_str '_d' num2str(d) '_samples']); 98 | 99 | end 100 | -------------------------------------------------------------------------------- /scripts/run_test_problems.m: -------------------------------------------------------------------------------- 1 | % Polynomial Chaos Randomized Greedy Algorithm 2 | % 3 | % Copyright (C) 2019 R. Baptista & P. Nair 4 | % 5 | % GreedyPC is free software: you can redistribute it and/or modify 6 | % it under the terms of the GNU 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 | % GreedyPC 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 General Public License for more details. 14 | % 15 | % You should have received a copy of the GNU General Public License 16 | % along with GreedyPC. If not, see . 17 | % 18 | % Copyright (C) 2019 MIT & University of Toronto 19 | % Authors: Ricardo Baptista & Prasanth Nair 20 | % E-mails: rsb@mit.edu or ricarsb@gmail.com & pbn@utias.utoronto.ca 21 | % 22 | 23 | % Reproduce studies in JCP Paper 24 | clear; close all; clc 25 | 26 | addpath('../SpectralToolbox') 27 | addpath('../TestProblems') 28 | addpath('../Methods') 29 | addpath('../tools') 30 | 31 | % make folder to store results 32 | if ~exist('../results', 'dir') 33 | mkdir('../results') 34 | end 35 | 36 | %% ALGEBRAIC 1 37 | 38 | % define test parameters 39 | test = struct; 40 | test.d = 10; 41 | test.order = 4; 42 | test.grid_level = 5; 43 | test.basis = 'Legendre'; 44 | test.func = @(x) algebraic_1(x); 45 | test.func_str = 'algebraic_1'; 46 | test.N = [50, 100, 200, 400, 600, 800, 1000]; 47 | test.n_trials = 5; 48 | test.MCtrials = 100; 49 | 50 | % run algorithms 51 | run_sampling(test); 52 | run_algorithms(test) 53 | create_plots(test) 54 | 55 | %% ALGEBRAIC 2 56 | 57 | % define test parameters 58 | test = struct; 59 | test.d = 10; 60 | test.order = 4; 61 | test.grid_level = 5; 62 | test.basis = 'Legendre'; 63 | test.func = @(x) algebraic_2(x); 64 | test.func_str = 'algebraic_2'; 65 | test.N = [50, 100, 200, 400, 600, 800, 1000]; 66 | test.n_trials = 5; 67 | test.MCtrials = 100; 68 | 69 | % run algorithms 70 | run_sampling(test); 71 | run_algorithms(test) 72 | create_plots(test) 73 | 74 | %% ALGEBRAIC 3 75 | 76 | % define test parameters 77 | test = struct; 78 | test.d = 10; 79 | test.order = 4; 80 | test.grid_level = 5; 81 | test.basis = 'Legendre'; 82 | test.func = @(x) algebraic_3(x); 83 | test.func_str = 'algebraic_3'; 84 | test.N = [50, 100, 200, 400, 600, 800, 1000]; 85 | test.n_trials = 5; 86 | test.MCtrials = 100; 87 | 88 | % run algorithms 89 | run_sampling(test); 90 | run_algorithms(test) 91 | create_plots(test) 92 | 93 | %% DIFFUSION EQUATION 94 | 95 | % define test parameters 96 | test = struct; 97 | test.d = 20; 98 | test.order = 3; 99 | test.grid_level = 5; 100 | test.basis = 'Legendre'; 101 | test.func = @(x) diffusion_equation_stochastic_forcing(x); 102 | test.func_str = 'diff_equation'; 103 | test.N = [50, 100, 200, 400, 600, 800, 1000]; 104 | test.n_trials = 5; 105 | test.MCtrials = 100; 106 | 107 | % run algorithms 108 | run_sampling(test); 109 | run_algorithms_lowmem(test) 110 | create_plots(test) 111 | 112 | % -- END OF FILE -- 113 | -------------------------------------------------------------------------------- /tools/ImprovedInputParser.m: -------------------------------------------------------------------------------- 1 | classdef ImprovedInputParser < inputParser 2 | % 3 | 4 | % This file is part of the Matlab Toolbox TENSALG for Tensor Algebra, 5 | % developed under the BSD Licence. 6 | % See the LICENSE file for conditions. 7 | 8 | properties 9 | unmatchedArgs 10 | end 11 | 12 | methods 13 | function p = ImprovedInputParser() 14 | p@inputParser(); 15 | p.KeepUnmatched = true; 16 | end 17 | function parse(p,varargin) 18 | parse@inputParser(p,varargin{:}); 19 | makeUnmatchedArgs(p); 20 | end 21 | 22 | function makeUnmatchedArgs(p) 23 | tmp = [fieldnames(p.Unmatched), ... 24 | struct2cell(p.Unmatched)]; 25 | p.unmatchedArgs = reshape(tmp',[],1)'; 26 | end 27 | 28 | function obj = passMatchedArgsToProperties(p,obj) 29 | fNames = fieldnames(p.Results); 30 | for k = 1:numel(fNames) 31 | obj.(fNames{k}) = p.Results.(fNames{k}); 32 | end 33 | end 34 | end 35 | end 36 | -------------------------------------------------------------------------------- /tools/sparse_grid.m: -------------------------------------------------------------------------------- 1 | % Author: Ricardo Baptista and Prasanth Nair 2 | % Date: March 2019 3 | % 4 | % See LICENSE.md for copyright information 5 | % 6 | 7 | function [nodes, weights] = sparse_grid(n_dim, grid_level, dist) 8 | % SPARSE_GRI: Function computes the nodes and weights to evaluate a 9 | % multi-dimensional integral using a Cleanshaw-Curtis sparse grid scheme. 10 | % 11 | % This function uses the sparse_grid_cfn_size.m and sparse_grid_cc.m 12 | % functions that are supplied with the SPARSE_GRID_CC program 13 | % by John Burkardt (2009) available at: 14 | % people.sc.fsu.edu/~jburkardt/m_src/sparse_grid_cc/sparse_grid_cc.html 15 | 16 | % Declare File Name 17 | file_name = ['sparsegrid_cc_dim_' num2str(n_dim) '_level_' num2str(grid_level) '.mat']; 18 | 19 | % Check if file exists, if not run sparse grid code 20 | if exist(file_name, 'file') 21 | 22 | % Load file contents 23 | load(file_name); 24 | 25 | else 26 | 27 | % check if sparse grid tool is in path 28 | if (exist('sparse_grid_cfn_size','file') ~= 2) || ... 29 | (exist('sparse_grid_cc','file') ~= 2) 30 | error('Please add sparse_grid tools to current path - see README'); 31 | end 32 | 33 | % Calculate the number of points in the sparse grid 34 | num_pts = sparse_grid_cfn_size(n_dim, grid_level); 35 | 36 | % Generate the nodes and weights of the sparse grid quadrature rule 37 | [weights, nodes] = sparse_grid_cc(n_dim, grid_level, num_pts); 38 | 39 | % Save files 40 | save(file_name, 'weights', 'nodes'); 41 | 42 | end 43 | 44 | nodes = nodes'; 45 | 46 | % Scale weights based on distribution 47 | if strcmp(dist,'unif') 48 | weights = weights/(2^n_dim); 49 | else 50 | error('Distribution is Not Recognized') 51 | end --------------------------------------------------------------------------------