├── .gitignore ├── LICENSE.txt ├── MANIFEST.in ├── README.rst ├── doc ├── Makefile ├── advanced_configuration.rst ├── conf.py ├── index.rst ├── modules.rst ├── pcs.rst ├── pysmac.rst ├── pysmac.utils.rst └── quickstart.rst ├── examples ├── branin_example.py ├── merge_pcs.py ├── rosenbrock_example.py ├── sklearn_example.py ├── sklearn_example_advanced_crossvalidation.py └── sklearn_model_selection.py ├── pysmac ├── __init__.py ├── analyzer.py ├── optimizer.py ├── remote_smac.py ├── smac │ └── smac-v2.10.03-master-778 │ │ ├── LICENSE-AGPLv3.txt │ │ ├── lib │ │ ├── DomainInter.jar │ │ ├── Jama-1.0.2.jar │ │ ├── LICENSE-AGPLv3.txt │ │ ├── aeatk-src.jar │ │ ├── aeatk.jar │ │ ├── commons-collections-3.2.1-sources.jar │ │ ├── commons-collections-3.2.1.jar │ │ ├── commons-io-2.1.jar │ │ ├── commons-math-2.2.jar │ │ ├── commons-math3-3.3.jar │ │ ├── exp4j-0.3.10.jar │ │ ├── exp4j-0.4.3.BETA-3.jar │ │ ├── fastrf-src.jar │ │ ├── fastrf.jar │ │ ├── guava-14.0.1.jar │ │ ├── jackson-annotations-2.3.1.jar │ │ ├── jackson-core-2.3.1.jar │ │ ├── jackson-databind-2.3.1.jar │ │ ├── jcip-annotations-src.jar │ │ ├── jcip-annotations.jar │ │ ├── jcommander.jar │ │ ├── jmatharray.jar │ │ ├── logback-access-1.1.2.jar │ │ ├── logback-classic-1.1.2.jar │ │ ├── logback-core-1.1.2.jar │ │ ├── numerics4j-1.3.jar │ │ ├── opencsv-2.3.jar │ │ ├── slf4j-api-1.7.5.jar │ │ ├── smac-src.jar │ │ ├── smac.jar │ │ └── spi-0.2.4.jar │ │ ├── smac │ │ ├── smac-validate │ │ ├── smac-validate.bat │ │ ├── smac.bat │ │ └── util │ │ ├── algo-test │ │ ├── algo-test.bat │ │ ├── bash_autocomplete.sh │ │ ├── ipc-client │ │ ├── ipc-client.bat │ │ ├── json-executor │ │ ├── json-executor.bat │ │ ├── pcs-check │ │ ├── pcs-check.bat │ │ ├── sat-check │ │ ├── sat-check.bat │ │ ├── state-merge │ │ ├── state-merge.bat │ │ ├── tae-evaluator │ │ ├── tae-evaluator.bat │ │ ├── verify-scenario │ │ └── verify-scenario.bat └── utils │ ├── __init__.py │ ├── java_helper.py │ ├── multiprocessing_wrapper.py │ ├── pcs_merge.py │ ├── smac_input_readers.py │ ├── smac_output_readers.py │ └── state_merge.py └── setup.py /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | *.swp 3 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 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 Affero General Public License is a free, copyleft license for 11 | software and other kinds of works, specifically designed to ensure 12 | cooperation with the community in the case of network server software. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | our General Public Licenses are intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. 19 | 20 | When we speak of free software, we are referring to freedom, not 21 | price. Our General Public Licenses are designed to make sure that you 22 | have the freedom to distribute copies of free software (and charge for 23 | them if you wish), that you receive source code or can get it if you 24 | want it, that you can change the software or use pieces of it in new 25 | free programs, and that you know you can do these things. 26 | 27 | Developers that use our General Public Licenses protect your rights 28 | with two steps: (1) assert copyright on the software, and (2) offer 29 | you this License which gives you legal permission to copy, distribute 30 | and/or modify the software. 31 | 32 | A secondary benefit of defending all users' freedom is that 33 | improvements made in alternate versions of the program, if they 34 | receive widespread use, become available for other developers to 35 | incorporate. Many developers of free software are heartened and 36 | encouraged by the resulting cooperation. However, in the case of 37 | software used on network servers, this result may fail to come about. 38 | The GNU General Public License permits making a modified version and 39 | letting the public access it on a server without ever releasing its 40 | source code to the public. 41 | 42 | The GNU Affero General Public License is designed specifically to 43 | ensure that, in such cases, the modified source code becomes available 44 | to the community. It requires the operator of a network server to 45 | provide the source code of the modified version running there to the 46 | users of that server. Therefore, public use of a modified version, on 47 | a publicly accessible server, gives the public access to the source 48 | code of the modified version. 49 | 50 | An older license, called the Affero General Public License and 51 | published by Affero, was designed to accomplish similar goals. This is 52 | a different license, not a version of the Affero GPL, but Affero has 53 | released a new version of the Affero GPL which permits relicensing under 54 | this license. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | TERMS AND CONDITIONS 60 | 61 | 0. Definitions. 62 | 63 | "This License" refers to version 3 of the GNU Affero General Public License. 64 | 65 | "Copyright" also means copyright-like laws that apply to other kinds of 66 | works, such as semiconductor masks. 67 | 68 | "The Program" refers to any copyrightable work licensed under this 69 | License. Each licensee is addressed as "you". "Licensees" and 70 | "recipients" may be individuals or organizations. 71 | 72 | To "modify" a work means to copy from or adapt all or part of the work 73 | in a fashion requiring copyright permission, other than the making of an 74 | exact copy. The resulting work is called a "modified version" of the 75 | earlier work or a work "based on" the earlier work. 76 | 77 | A "covered work" means either the unmodified Program or a work based 78 | on the Program. 79 | 80 | To "propagate" a work means to do anything with it that, without 81 | permission, would make you directly or secondarily liable for 82 | infringement under applicable copyright law, except executing it on a 83 | computer or modifying a private copy. Propagation includes copying, 84 | distribution (with or without modification), making available to the 85 | public, and in some countries other activities as well. 86 | 87 | To "convey" a work means any kind of propagation that enables other 88 | parties to make or receive copies. Mere interaction with a user through 89 | a computer network, with no transfer of a copy, is not conveying. 90 | 91 | An interactive user interface displays "Appropriate Legal Notices" 92 | to the extent that it includes a convenient and prominently visible 93 | feature that (1) displays an appropriate copyright notice, and (2) 94 | tells the user that there is no warranty for the work (except to the 95 | extent that warranties are provided), that licensees may convey the 96 | work under this License, and how to view a copy of this License. If 97 | the interface presents a list of user commands or options, such as a 98 | menu, a prominent item in the list meets this criterion. 99 | 100 | 1. Source Code. 101 | 102 | The "source code" for a work means the preferred form of the work 103 | for making modifications to it. "Object code" means any non-source 104 | form of a work. 105 | 106 | A "Standard Interface" means an interface that either is an official 107 | standard defined by a recognized standards body, or, in the case of 108 | interfaces specified for a particular programming language, one that 109 | is widely used among developers working in that language. 110 | 111 | The "System Libraries" of an executable work include anything, other 112 | than the work as a whole, that (a) is included in the normal form of 113 | packaging a Major Component, but which is not part of that Major 114 | Component, and (b) serves only to enable use of the work with that 115 | Major Component, or to implement a Standard Interface for which an 116 | implementation is available to the public in source code form. A 117 | "Major Component", in this context, means a major essential component 118 | (kernel, window system, and so on) of the specific operating system 119 | (if any) on which the executable work runs, or a compiler used to 120 | produce the work, or an object code interpreter used to run it. 121 | 122 | The "Corresponding Source" for a work in object code form means all 123 | the source code needed to generate, install, and (for an executable 124 | work) run the object code and to modify the work, including scripts to 125 | control those activities. However, it does not include the work's 126 | System Libraries, or general-purpose tools or generally available free 127 | programs which are used unmodified in performing those activities but 128 | which are not part of the work. For example, Corresponding Source 129 | includes interface definition files associated with source files for 130 | the work, and the source code for shared libraries and dynamically 131 | linked subprograms that the work is specifically designed to require, 132 | such as by intimate data communication or control flow between those 133 | subprograms and other parts of the work. 134 | 135 | The Corresponding Source need not include anything that users 136 | can regenerate automatically from other parts of the Corresponding 137 | Source. 138 | 139 | The Corresponding Source for a work in source code form is that 140 | same work. 141 | 142 | 2. Basic Permissions. 143 | 144 | All rights granted under this License are granted for the term of 145 | copyright on the Program, and are irrevocable provided the stated 146 | conditions are met. This License explicitly affirms your unlimited 147 | permission to run the unmodified Program. The output from running a 148 | covered work is covered by this License only if the output, given its 149 | content, constitutes a covered work. This License acknowledges your 150 | rights of fair use or other equivalent, as provided by copyright law. 151 | 152 | You may make, run and propagate covered works that you do not 153 | convey, without conditions so long as your license otherwise remains 154 | in force. You may convey covered works to others for the sole purpose 155 | of having them make modifications exclusively for you, or provide you 156 | with facilities for running those works, provided that you comply with 157 | the terms of this License in conveying all material for which you do 158 | not control copyright. Those thus making or running the covered works 159 | for you must do so exclusively on your behalf, under your direction 160 | and control, on terms that prohibit them from making any copies of 161 | your copyrighted material outside their relationship with you. 162 | 163 | Conveying under any other circumstances is permitted solely under 164 | the conditions stated below. Sublicensing is not allowed; section 10 165 | makes it unnecessary. 166 | 167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 168 | 169 | No covered work shall be deemed part of an effective technological 170 | measure under any applicable law fulfilling obligations under article 171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 172 | similar laws prohibiting or restricting circumvention of such 173 | measures. 174 | 175 | When you convey a covered work, you waive any legal power to forbid 176 | circumvention of technological measures to the extent such circumvention 177 | is effected by exercising rights under this License with respect to 178 | the covered work, and you disclaim any intention to limit operation or 179 | modification of the work as a means of enforcing, against the work's 180 | users, your or third parties' legal rights to forbid circumvention of 181 | technological measures. 182 | 183 | 4. Conveying Verbatim Copies. 184 | 185 | You may convey verbatim copies of the Program's source code as you 186 | receive it, in any medium, provided that you conspicuously and 187 | appropriately publish on each copy an appropriate copyright notice; 188 | keep intact all notices stating that this License and any 189 | non-permissive terms added in accord with section 7 apply to the code; 190 | keep intact all notices of the absence of any warranty; and give all 191 | recipients a copy of this License along with the Program. 192 | 193 | You may charge any price or no price for each copy that you convey, 194 | and you may offer support or warranty protection for a fee. 195 | 196 | 5. Conveying Modified Source Versions. 197 | 198 | You may convey a work based on the Program, or the modifications to 199 | produce it from the Program, in the form of source code under the 200 | terms of section 4, provided that you also meet all of these conditions: 201 | 202 | a) The work must carry prominent notices stating that you modified 203 | it, and giving a relevant date. 204 | 205 | b) The work must carry prominent notices stating that it is 206 | released under this License and any conditions added under section 207 | 7. This requirement modifies the requirement in section 4 to 208 | "keep intact all notices". 209 | 210 | c) You must license the entire work, as a whole, under this 211 | License to anyone who comes into possession of a copy. This 212 | License will therefore apply, along with any applicable section 7 213 | additional terms, to the whole of the work, and all its parts, 214 | regardless of how they are packaged. This License gives no 215 | permission to license the work in any other way, but it does not 216 | invalidate such permission if you have separately received it. 217 | 218 | d) If the work has interactive user interfaces, each must display 219 | Appropriate Legal Notices; however, if the Program has interactive 220 | interfaces that do not display Appropriate Legal Notices, your 221 | work need not make them do so. 222 | 223 | A compilation of a covered work with other separate and independent 224 | works, which are not by their nature extensions of the covered work, 225 | and which are not combined with it such as to form a larger program, 226 | in or on a volume of a storage or distribution medium, is called an 227 | "aggregate" if the compilation and its resulting copyright are not 228 | used to limit the access or legal rights of the compilation's users 229 | beyond what the individual works permit. Inclusion of a covered work 230 | in an aggregate does not cause this License to apply to the other 231 | parts of the aggregate. 232 | 233 | 6. Conveying Non-Source Forms. 234 | 235 | You may convey a covered work in object code form under the terms 236 | of sections 4 and 5, provided that you also convey the 237 | machine-readable Corresponding Source under the terms of this License, 238 | in one of these ways: 239 | 240 | a) Convey the object code in, or embodied in, a physical product 241 | (including a physical distribution medium), accompanied by the 242 | Corresponding Source fixed on a durable physical medium 243 | customarily used for software interchange. 244 | 245 | b) Convey the object code in, or embodied in, a physical product 246 | (including a physical distribution medium), accompanied by a 247 | written offer, valid for at least three years and valid for as 248 | long as you offer spare parts or customer support for that product 249 | model, to give anyone who possesses the object code either (1) a 250 | copy of the Corresponding Source for all the software in the 251 | product that is covered by this License, on a durable physical 252 | medium customarily used for software interchange, for a price no 253 | more than your reasonable cost of physically performing this 254 | conveying of source, or (2) access to copy the 255 | Corresponding Source from a network server at no charge. 256 | 257 | c) Convey individual copies of the object code with a copy of the 258 | written offer to provide the Corresponding Source. This 259 | alternative is allowed only occasionally and noncommercially, and 260 | only if you received the object code with such an offer, in accord 261 | with subsection 6b. 262 | 263 | d) Convey the object code by offering access from a designated 264 | place (gratis or for a charge), and offer equivalent access to the 265 | Corresponding Source in the same way through the same place at no 266 | further charge. You need not require recipients to copy the 267 | Corresponding Source along with the object code. If the place to 268 | copy the object code is a network server, the Corresponding Source 269 | may be on a different server (operated by you or a third party) 270 | that supports equivalent copying facilities, provided you maintain 271 | clear directions next to the object code saying where to find the 272 | Corresponding Source. Regardless of what server hosts the 273 | Corresponding Source, you remain obligated to ensure that it is 274 | available for as long as needed to satisfy these requirements. 275 | 276 | e) Convey the object code using peer-to-peer transmission, provided 277 | you inform other peers where the object code and Corresponding 278 | Source of the work are being offered to the general public at no 279 | charge under subsection 6d. 280 | 281 | A separable portion of the object code, whose source code is excluded 282 | from the Corresponding Source as a System Library, need not be 283 | included in conveying the object code work. 284 | 285 | A "User Product" is either (1) a "consumer product", which means any 286 | tangible personal property which is normally used for personal, family, 287 | or household purposes, or (2) anything designed or sold for incorporation 288 | into a dwelling. In determining whether a product is a consumer product, 289 | doubtful cases shall be resolved in favor of coverage. For a particular 290 | product received by a particular user, "normally used" refers to a 291 | typical or common use of that class of product, regardless of the status 292 | of the particular user or of the way in which the particular user 293 | actually uses, or expects or is expected to use, the product. A product 294 | is a consumer product regardless of whether the product has substantial 295 | commercial, industrial or non-consumer uses, unless such uses represent 296 | the only significant mode of use of the product. 297 | 298 | "Installation Information" for a User Product means any methods, 299 | procedures, authorization keys, or other information required to install 300 | and execute modified versions of a covered work in that User Product from 301 | a modified version of its Corresponding Source. The information must 302 | suffice to ensure that the continued functioning of the modified object 303 | code is in no case prevented or interfered with solely because 304 | modification has been made. 305 | 306 | If you convey an object code work under this section in, or with, or 307 | specifically for use in, a User Product, and the conveying occurs as 308 | part of a transaction in which the right of possession and use of the 309 | User Product is transferred to the recipient in perpetuity or for a 310 | fixed term (regardless of how the transaction is characterized), the 311 | Corresponding Source conveyed under this section must be accompanied 312 | by the Installation Information. But this requirement does not apply 313 | if neither you nor any third party retains the ability to install 314 | modified object code on the User Product (for example, the work has 315 | been installed in ROM). 316 | 317 | The requirement to provide Installation Information does not include a 318 | requirement to continue to provide support service, warranty, or updates 319 | for a work that has been modified or installed by the recipient, or for 320 | the User Product in which it has been modified or installed. Access to a 321 | network may be denied when the modification itself materially and 322 | adversely affects the operation of the network or violates the rules and 323 | protocols for communication across the network. 324 | 325 | Corresponding Source conveyed, and Installation Information provided, 326 | in accord with this section must be in a format that is publicly 327 | documented (and with an implementation available to the public in 328 | source code form), and must require no special password or key for 329 | unpacking, reading or copying. 330 | 331 | 7. Additional Terms. 332 | 333 | "Additional permissions" are terms that supplement the terms of this 334 | License by making exceptions from one or more of its conditions. 335 | Additional permissions that are applicable to the entire Program shall 336 | be treated as though they were included in this License, to the extent 337 | that they are valid under applicable law. If additional permissions 338 | apply only to part of the Program, that part may be used separately 339 | under those permissions, but the entire Program remains governed by 340 | this License without regard to the additional permissions. 341 | 342 | When you convey a copy of a covered work, you may at your option 343 | remove any additional permissions from that copy, or from any part of 344 | it. (Additional permissions may be written to require their own 345 | removal in certain cases when you modify the work.) You may place 346 | additional permissions on material, added by you to a covered work, 347 | for which you have or can give appropriate copyright permission. 348 | 349 | Notwithstanding any other provision of this License, for material you 350 | add to a covered work, you may (if authorized by the copyright holders of 351 | that material) supplement the terms of this License with terms: 352 | 353 | a) Disclaiming warranty or limiting liability differently from the 354 | terms of sections 15 and 16 of this License; or 355 | 356 | b) Requiring preservation of specified reasonable legal notices or 357 | author attributions in that material or in the Appropriate Legal 358 | Notices displayed by works containing it; or 359 | 360 | c) Prohibiting misrepresentation of the origin of that material, or 361 | requiring that modified versions of such material be marked in 362 | reasonable ways as different from the original version; or 363 | 364 | d) Limiting the use for publicity purposes of names of licensors or 365 | authors of the material; or 366 | 367 | e) Declining to grant rights under trademark law for use of some 368 | trade names, trademarks, or service marks; or 369 | 370 | f) Requiring indemnification of licensors and authors of that 371 | material by anyone who conveys the material (or modified versions of 372 | it) with contractual assumptions of liability to the recipient, for 373 | any liability that these contractual assumptions directly impose on 374 | those licensors and authors. 375 | 376 | All other non-permissive additional terms are considered "further 377 | restrictions" within the meaning of section 10. If the Program as you 378 | received it, or any part of it, contains a notice stating that it is 379 | governed by this License along with a term that is a further 380 | restriction, you may remove that term. If a license document contains 381 | a further restriction but permits relicensing or conveying under this 382 | License, you may add to a covered work material governed by the terms 383 | of that license document, provided that the further restriction does 384 | not survive such relicensing or conveying. 385 | 386 | If you add terms to a covered work in accord with this section, you 387 | must place, in the relevant source files, a statement of the 388 | additional terms that apply to those files, or a notice indicating 389 | where to find the applicable terms. 390 | 391 | Additional terms, permissive or non-permissive, may be stated in the 392 | form of a separately written license, or stated as exceptions; 393 | the above requirements apply either way. 394 | 395 | 8. Termination. 396 | 397 | You may not propagate or modify a covered work except as expressly 398 | provided under this License. Any attempt otherwise to propagate or 399 | modify it is void, and will automatically terminate your rights under 400 | this License (including any patent licenses granted under the third 401 | paragraph of section 11). 402 | 403 | However, if you cease all violation of this License, then your 404 | license from a particular copyright holder is reinstated (a) 405 | provisionally, unless and until the copyright holder explicitly and 406 | finally terminates your license, and (b) permanently, if the copyright 407 | holder fails to notify you of the violation by some reasonable means 408 | prior to 60 days after the cessation. 409 | 410 | Moreover, your license from a particular copyright holder is 411 | reinstated permanently if the copyright holder notifies you of the 412 | violation by some reasonable means, this is the first time you have 413 | received notice of violation of this License (for any work) from that 414 | copyright holder, and you cure the violation prior to 30 days after 415 | your receipt of the notice. 416 | 417 | Termination of your rights under this section does not terminate the 418 | licenses of parties who have received copies or rights from you under 419 | this License. If your rights have been terminated and not permanently 420 | reinstated, you do not qualify to receive new licenses for the same 421 | material under section 10. 422 | 423 | 9. Acceptance Not Required for Having Copies. 424 | 425 | You are not required to accept this License in order to receive or 426 | run a copy of the Program. Ancillary propagation of a covered work 427 | occurring solely as a consequence of using peer-to-peer transmission 428 | to receive a copy likewise does not require acceptance. However, 429 | nothing other than this License grants you permission to propagate or 430 | modify any covered work. These actions infringe copyright if you do 431 | not accept this License. Therefore, by modifying or propagating a 432 | covered work, you indicate your acceptance of this License to do so. 433 | 434 | 10. Automatic Licensing of Downstream Recipients. 435 | 436 | Each time you convey a covered work, the recipient automatically 437 | receives a license from the original licensors, to run, modify and 438 | propagate that work, subject to this License. You are not responsible 439 | for enforcing compliance by third parties with this License. 440 | 441 | An "entity transaction" is a transaction transferring control of an 442 | organization, or substantially all assets of one, or subdividing an 443 | organization, or merging organizations. If propagation of a covered 444 | work results from an entity transaction, each party to that 445 | transaction who receives a copy of the work also receives whatever 446 | licenses to the work the party's predecessor in interest had or could 447 | give under the previous paragraph, plus a right to possession of the 448 | Corresponding Source of the work from the predecessor in interest, if 449 | the predecessor has it or can get it with reasonable efforts. 450 | 451 | You may not impose any further restrictions on the exercise of the 452 | rights granted or affirmed under this License. For example, you may 453 | not impose a license fee, royalty, or other charge for exercise of 454 | rights granted under this License, and you may not initiate litigation 455 | (including a cross-claim or counterclaim in a lawsuit) alleging that 456 | any patent claim is infringed by making, using, selling, offering for 457 | sale, or importing the Program or any portion of it. 458 | 459 | 11. Patents. 460 | 461 | A "contributor" is a copyright holder who authorizes use under this 462 | License of the Program or a work on which the Program is based. The 463 | work thus licensed is called the contributor's "contributor version". 464 | 465 | A contributor's "essential patent claims" are all patent claims 466 | owned or controlled by the contributor, whether already acquired or 467 | hereafter acquired, that would be infringed by some manner, permitted 468 | by this License, of making, using, or selling its contributor version, 469 | but do not include claims that would be infringed only as a 470 | consequence of further modification of the contributor version. For 471 | purposes of this definition, "control" includes the right to grant 472 | patent sublicenses in a manner consistent with the requirements of 473 | this License. 474 | 475 | Each contributor grants you a non-exclusive, worldwide, royalty-free 476 | patent license under the contributor's essential patent claims, to 477 | make, use, sell, offer for sale, import and otherwise run, modify and 478 | propagate the contents of its contributor version. 479 | 480 | In the following three paragraphs, a "patent license" is any express 481 | agreement or commitment, however denominated, not to enforce a patent 482 | (such as an express permission to practice a patent or covenant not to 483 | sue for patent infringement). To "grant" such a patent license to a 484 | party means to make such an agreement or commitment not to enforce a 485 | patent against the party. 486 | 487 | If you convey a covered work, knowingly relying on a patent license, 488 | and the Corresponding Source of the work is not available for anyone 489 | to copy, free of charge and under the terms of this License, through a 490 | publicly available network server or other readily accessible means, 491 | then you must either (1) cause the Corresponding Source to be so 492 | available, or (2) arrange to deprive yourself of the benefit of the 493 | patent license for this particular work, or (3) arrange, in a manner 494 | consistent with the requirements of this License, to extend the patent 495 | license to downstream recipients. "Knowingly relying" means you have 496 | actual knowledge that, but for the patent license, your conveying the 497 | covered work in a country, or your recipient's use of the covered work 498 | in a country, would infringe one or more identifiable patents in that 499 | country that you have reason to believe are valid. 500 | 501 | If, pursuant to or in connection with a single transaction or 502 | arrangement, you convey, or propagate by procuring conveyance of, a 503 | covered work, and grant a patent license to some of the parties 504 | receiving the covered work authorizing them to use, propagate, modify 505 | or convey a specific copy of the covered work, then the patent license 506 | you grant is automatically extended to all recipients of the covered 507 | work and works based on it. 508 | 509 | A patent license is "discriminatory" if it does not include within 510 | the scope of its coverage, prohibits the exercise of, or is 511 | conditioned on the non-exercise of one or more of the rights that are 512 | specifically granted under this License. You may not convey a covered 513 | work if you are a party to an arrangement with a third party that is 514 | in the business of distributing software, under which you make payment 515 | to the third party based on the extent of your activity of conveying 516 | the work, and under which the third party grants, to any of the 517 | parties who would receive the covered work from you, a discriminatory 518 | patent license (a) in connection with copies of the covered work 519 | conveyed by you (or copies made from those copies), or (b) primarily 520 | for and in connection with specific products or compilations that 521 | contain the covered work, unless you entered into that arrangement, 522 | or that patent license was granted, prior to 28 March 2007. 523 | 524 | Nothing in this License shall be construed as excluding or limiting 525 | any implied license or other defenses to infringement that may 526 | otherwise be available to you under applicable patent law. 527 | 528 | 12. No Surrender of Others' Freedom. 529 | 530 | If conditions are imposed on you (whether by court order, agreement or 531 | otherwise) that contradict the conditions of this License, they do not 532 | excuse you from the conditions of this License. If you cannot convey a 533 | covered work so as to satisfy simultaneously your obligations under this 534 | License and any other pertinent obligations, then as a consequence you may 535 | not convey it at all. For example, if you agree to terms that obligate you 536 | to collect a royalty for further conveying from those to whom you convey 537 | the Program, the only way you could satisfy both those terms and this 538 | License would be to refrain entirely from conveying the Program. 539 | 540 | 13. Remote Network Interaction; Use with the GNU General Public License. 541 | 542 | Notwithstanding any other provision of this License, if you modify the 543 | Program, your modified version must prominently offer all users 544 | interacting with it remotely through a computer network (if your version 545 | supports such interaction) an opportunity to receive the Corresponding 546 | Source of your version by providing access to the Corresponding Source 547 | from a network server at no charge, through some standard or customary 548 | means of facilitating copying of software. This Corresponding Source 549 | shall include the Corresponding Source for any work covered by version 3 550 | of the GNU General Public License that is incorporated pursuant to the 551 | following paragraph. 552 | 553 | Notwithstanding any other provision of this License, you have 554 | permission to link or combine any covered work with a work licensed 555 | under version 3 of the GNU General Public License into a single 556 | combined work, and to convey the resulting work. The terms of this 557 | License will continue to apply to the part which is the covered work, 558 | but the work with which it is combined will remain governed by version 559 | 3 of the GNU General Public License. 560 | 561 | 14. Revised Versions of this License. 562 | 563 | The Free Software Foundation may publish revised and/or new versions of 564 | the GNU Affero General Public License from time to time. Such new versions 565 | will be similar in spirit to the present version, but may differ in detail to 566 | address new problems or concerns. 567 | 568 | Each version is given a distinguishing version number. If the 569 | Program specifies that a certain numbered version of the GNU Affero General 570 | Public License "or any later version" applies to it, you have the 571 | option of following the terms and conditions either of that numbered 572 | version or of any later version published by the Free Software 573 | Foundation. If the Program does not specify a version number of the 574 | GNU Affero General Public License, you may choose any version ever published 575 | by the Free Software Foundation. 576 | 577 | If the Program specifies that a proxy can decide which future 578 | versions of the GNU Affero General Public License can be used, that proxy's 579 | public statement of acceptance of a version permanently authorizes you 580 | to choose that version for the Program. 581 | 582 | Later license versions may give you additional or different 583 | permissions. However, no additional obligations are imposed on any 584 | author or copyright holder as a result of your choosing to follow a 585 | later version. 586 | 587 | 15. Disclaimer of Warranty. 588 | 589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 597 | 598 | 16. Limitation of Liability. 599 | 600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 608 | SUCH DAMAGES. 609 | 610 | 17. Interpretation of Sections 15 and 16. 611 | 612 | If the disclaimer of warranty and limitation of liability provided 613 | above cannot be given local legal effect according to their terms, 614 | reviewing courts shall apply local law that most closely approximates 615 | an absolute waiver of all civil liability in connection with the 616 | Program, unless a warranty or assumption of liability accompanies a 617 | copy of the Program in return for a fee. 618 | 619 | END OF TERMS AND CONDITIONS 620 | 621 | How to Apply These Terms to Your New Programs 622 | 623 | If you develop a new program, and you want it to be of the greatest 624 | possible use to the public, the best way to achieve this is to make it 625 | free software which everyone can redistribute and change under these terms. 626 | 627 | To do so, attach the following notices to the program. It is safest 628 | to attach them to the start of each source file to most effectively 629 | state the exclusion of warranty; and each file should have at least 630 | the "copyright" line and a pointer to where the full notice is found. 631 | 632 | 633 | Copyright (C) 634 | 635 | This program is free software: you can redistribute it and/or modify 636 | it under the terms of the GNU Affero General Public License as published by 637 | the Free Software Foundation, either version 3 of the License, or 638 | (at your option) any later version. 639 | 640 | This program is distributed in the hope that it will be useful, 641 | but WITHOUT ANY WARRANTY; without even the implied warranty of 642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 643 | GNU Affero General Public License for more details. 644 | 645 | You should have received a copy of the GNU Affero General Public License 646 | along with this program. If not, see . 647 | 648 | Also add information on how to contact you by electronic and paper mail. 649 | 650 | If your software can interact with users remotely through a computer 651 | network, you should also make sure that it provides a way for users to 652 | get its source. For example, if your program is a web application, its 653 | interface could display a "Source" link that leads users to an archive 654 | of the code. There are many ways you could offer source, and different 655 | solutions will be better for different programs; see section 13 for the 656 | specific requirements. 657 | 658 | You should also get your employer (if you work as a programmer) or school, 659 | if any, to sign a "copyright disclaimer" for the program, if necessary. 660 | For more information on this, and how to apply and follow the GNU AGPL, see 661 | . -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | recursive-include pysmac/smac *.jar 2 | recursive-include pysmac/smac *.bat 3 | recursive-include pysmac/smac smac 4 | include Readme.md 5 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | pysmac 2 | ====== 3 | 4 | Simple python wrapper to [SMAC](http://www.cs.ubc.ca/labs/beta/Projects/SMAC/), a versatile tool for optimizing algorithm parameters. 5 | 6 | SMAC is free for academic & non-commercial usage. Please contact Frank Hutter to discuss obtaining a license for commercial purposes. 7 | 8 | This wrapper is intented to use SMAC directly from Python to minimize a objective function. It also contains some rudimentary analyzing tools that can also be applied to already existing SMAC runs. 9 | 10 | 11 | 12 | Installation 13 | ------------ 14 | 15 | To install pysmac, we advise using the Python package management system: 16 | 17 | .. code-block:: shell 18 | 19 | pip install git+https://github.com/automl/pysmac.git --user 20 | 21 | If you prefer, you can clone the repository and install it manually via 22 | 23 | .. code-block:: shell 24 | 25 | python setup.py install 26 | 27 | 28 | Documentation 29 | ----------- 30 | 31 | The documentation for pySMAC is hosted on http://pysmac.readthedocs.org/. It contains a `Quickstart guide `_ for the impatient, but also a detailed manual. 32 | -------------------------------------------------------------------------------- /doc/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = _build 9 | 10 | # User-friendly check for sphinx-build 11 | ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) 12 | $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) 13 | endif 14 | 15 | # Internal variables. 16 | PAPEROPT_a4 = -D latex_paper_size=a4 17 | PAPEROPT_letter = -D latex_paper_size=letter 18 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 19 | # the i18n builder cannot share the environment and doctrees with the others 20 | I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 21 | 22 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest coverage gettext 23 | 24 | help: 25 | @echo "Please use \`make ' where is one of" 26 | @echo " html to make standalone HTML files" 27 | @echo " dirhtml to make HTML files named index.html in directories" 28 | @echo " singlehtml to make a single large HTML file" 29 | @echo " pickle to make pickle files" 30 | @echo " json to make JSON files" 31 | @echo " htmlhelp to make HTML files and a HTML help project" 32 | @echo " qthelp to make HTML files and a qthelp project" 33 | @echo " applehelp to make an Apple Help Book" 34 | @echo " devhelp to make HTML files and a Devhelp project" 35 | @echo " epub to make an epub" 36 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 37 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 38 | @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" 39 | @echo " text to make text files" 40 | @echo " man to make manual pages" 41 | @echo " texinfo to make Texinfo files" 42 | @echo " info to make Texinfo files and run them through makeinfo" 43 | @echo " gettext to make PO message catalogs" 44 | @echo " changes to make an overview of all changed/added/deprecated items" 45 | @echo " xml to make Docutils-native XML files" 46 | @echo " pseudoxml to make pseudoxml-XML files for display purposes" 47 | @echo " linkcheck to check all external links for integrity" 48 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 49 | @echo " coverage to run coverage check of the documentation (if enabled)" 50 | 51 | clean: 52 | rm -rf $(BUILDDIR)/* 53 | 54 | html: 55 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 56 | @echo 57 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 58 | 59 | dirhtml: 60 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 61 | @echo 62 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 63 | 64 | singlehtml: 65 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 66 | @echo 67 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 68 | 69 | pickle: 70 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 71 | @echo 72 | @echo "Build finished; now you can process the pickle files." 73 | 74 | json: 75 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 76 | @echo 77 | @echo "Build finished; now you can process the JSON files." 78 | 79 | htmlhelp: 80 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 81 | @echo 82 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 83 | ".hhp project file in $(BUILDDIR)/htmlhelp." 84 | 85 | qthelp: 86 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 87 | @echo 88 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 89 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 90 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/pySMAC.qhcp" 91 | @echo "To view the help file:" 92 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/pySMAC.qhc" 93 | 94 | applehelp: 95 | $(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp 96 | @echo 97 | @echo "Build finished. The help book is in $(BUILDDIR)/applehelp." 98 | @echo "N.B. You won't be able to view it unless you put it in" \ 99 | "~/Library/Documentation/Help or install it in your application" \ 100 | "bundle." 101 | 102 | devhelp: 103 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 104 | @echo 105 | @echo "Build finished." 106 | @echo "To view the help file:" 107 | @echo "# mkdir -p $$HOME/.local/share/devhelp/pySMAC" 108 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/pySMAC" 109 | @echo "# devhelp" 110 | 111 | epub: 112 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 113 | @echo 114 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 115 | 116 | latex: 117 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 118 | @echo 119 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 120 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 121 | "(use \`make latexpdf' here to do that automatically)." 122 | 123 | latexpdf: 124 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 125 | @echo "Running LaTeX files through pdflatex..." 126 | $(MAKE) -C $(BUILDDIR)/latex all-pdf 127 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 128 | 129 | latexpdfja: 130 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 131 | @echo "Running LaTeX files through platex and dvipdfmx..." 132 | $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja 133 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 134 | 135 | text: 136 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 137 | @echo 138 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 139 | 140 | man: 141 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 142 | @echo 143 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 144 | 145 | texinfo: 146 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 147 | @echo 148 | @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." 149 | @echo "Run \`make' in that directory to run these through makeinfo" \ 150 | "(use \`make info' here to do that automatically)." 151 | 152 | info: 153 | $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo 154 | @echo "Running Texinfo files through makeinfo..." 155 | make -C $(BUILDDIR)/texinfo info 156 | @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." 157 | 158 | gettext: 159 | $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale 160 | @echo 161 | @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 162 | 163 | changes: 164 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 165 | @echo 166 | @echo "The overview file is in $(BUILDDIR)/changes." 167 | 168 | linkcheck: 169 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 170 | @echo 171 | @echo "Link check complete; look for any errors in the above output " \ 172 | "or in $(BUILDDIR)/linkcheck/output.txt." 173 | 174 | doctest: 175 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 176 | @echo "Testing of doctests in the sources finished, look at the " \ 177 | "results in $(BUILDDIR)/doctest/output.txt." 178 | 179 | coverage: 180 | $(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage 181 | @echo "Testing of coverage in the sources finished, look at the " \ 182 | "results in $(BUILDDIR)/coverage/python.txt." 183 | 184 | xml: 185 | $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml 186 | @echo 187 | @echo "Build finished. The XML files are in $(BUILDDIR)/xml." 188 | 189 | pseudoxml: 190 | $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml 191 | @echo 192 | @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." 193 | -------------------------------------------------------------------------------- /doc/advanced_configuration.rst: -------------------------------------------------------------------------------- 1 | .. _advanced_configuration: 2 | 3 | ================================ 4 | Advanced configuration of pySMAC 5 | ================================ 6 | 7 | Restricting your Functions Resources 8 | ------------------------------------ 9 | 10 | Often in algorithm configuration (SMAC's main application), some configurations 11 | may take too long, consume more memory than they should or have other undesired 12 | side effects. To guard against these cases, pySMAC utilizes a Python module called 13 | **pynisher** which allows you to specify certain limits for your function. 14 | Specifically, you can limit your functions memory consumption, CPU 15 | and wall clock time. Refer to the :py:meth:`pySMAC.optimizer.SMAC_optimizer.minimize` 16 | documentation for further details. Similar limits can be applied to the SMAC process(es) 17 | started in the background. Please check out :py:meth:`pySMAC.optimizer.SMAC_optimizer`. 18 | 19 | If your function takes too long, or tries to allocate too much memory, 20 | the subprocess encapsulating your function receives a signal, and is aborted. 21 | Please refer to the pynisher manual for more details. 22 | 23 | 24 | .. _advanced_options: 25 | 26 | Additional (py)SMAC Options 27 | --------------------------- 28 | 29 | The API of pySMAC is designed to allow a low barrier entry for using it, 30 | but SMAC is a very powerful tool that comes with numerous features. For a 31 | novice this complexity might be overwhelming, but more experienced users 32 | need to be able to access the full potential of SMAC. This is the reason 33 | why pySMAC forces you to create a SMAC_optimizer object before calling its 34 | method minimize. In principle, this could be combined into a 35 | simple function. But splitting it up into two steps allows the user to modify 36 | the standard options of SMAC itself and some advanced features of pySMAC. 37 | 38 | The large number of options in SMAC is far too large to implement a proper 39 | python function taking those as arguments without cluttering the interface 40 | and/or running into trouble when new options are added in future versions. 41 | Instead, the *SMAC_optimizer* object has an attribute called **smac_options**. 42 | This is a dict where the keys-value pair represent a SMAC option and the 43 | corresponding value. It is populated with some defauld values 44 | on creation of the *SMAC_optimizer* object, and will be used to start SMAC 45 | inside the *minimize* method. That way, the user has full control over 46 | every SMAC option by manipulating the entries of said dict before starting 47 | the minimization. 48 | 49 | For example, you might want to change the number of trees in the random 50 | forest SMAC fits internally to the observed data. Looking into the SMAC 51 | manual reveals there exists an option called called "--rf-num-trees" when 52 | calling SMAC from the command line. To use this option in pySMAC, add the key 53 | "rf-num-trees" (dropping the leading hyphens) like that: 54 | 55 | .. code-block:: python 56 | 57 | opt = pySMAC.SMAC_optimizer() 58 | opt.smac_options['rf-num-trees'] = 16 59 | 60 | Now, SMAC would fit 16 trees when the minimize method is called. 61 | 62 | There are a few entries in this dictionary that are not SMAC, but pySMAC 63 | options: 64 | 65 | +----------------+------------------------------------------------------------+---------------+ 66 | | Name | Description | Default | 67 | +================+============================================================+===============+ 68 | |scenario_fn | All important SMAC options are stored in a scenario file. | 'scenario.dat'| 69 | | | This option sets the name for that file. | | 70 | +----------------+------------------------------------------------------------+---------------+ 71 | |java_executable | SMAC itself runs inside a Java Runtime Environment. This | 'java' | 72 | | | option controls how Java is invoked on the command line. | | 73 | | | It is possible to pass additional arguments to Java using | | 74 | | | this entry. E.g., '/usr/bin/java -d32' would tell pySMAC | | 75 | | | where the Java binary can be found and that it should use | | 76 | | | a 32-bit data model if available. Use this if the system | | 77 | | | wide command java is not the JRE you want pySMAC to use. | | 78 | +----------------+------------------------------------------------------------+---------------+ 79 | |timeout_quality | If the function call times out while you optimize the | 2^127 | 80 | | | quality the value specified here will be assumed to be the | | 81 | | | returned value. | | 82 | +----------------+------------------------------------------------------------+---------------+ 83 | 84 | 85 | Optimizing Runtime instead of Quality 86 | ------------------------------------- 87 | 88 | Minimizing a function is a relatively general problem which, in principle, 89 | also allows for runtime optimization. But optimizing the duration of the 90 | function cal is so common and allows for a customized approach that 91 | SMAC has a dedicated mode for it. One of the key differences between 92 | minimizing a functions return value (the quality) rather then the runtime, 93 | is that incomplete runs still contain valuable information in the latter 94 | case. Imagine, SMAC already encountered a configuration that can finish in 95 | 5 seconds. For subsequent runs, there is no need to wait longer than said 96 | 5 seconds for any other configuration to finish. The corresponding option 97 | is called **run-obj**, and can take the values 'RUNTIME' or 'QUALITY' 98 | (default for pySMAC). 99 | 100 | If you want to optimize runtime, the return value of your function should not 101 | be the duration you want SMAC to record for this call. pySMAC automatically 102 | measures the CPU time of your function. The actual return value of your 103 | function is somewhat irrelevant. However, if you want to overwrite pySMAC's 104 | time measurement, your function can return a ``dict`` where the following keys 105 | are used: 106 | 107 | +-------------+--------------------------------------------------------+ 108 | | Key | Explanation | 109 | +=============+========================================================+ 110 | | value | The actual function value. Has to be a float. | 111 | +-------------+--------------------------------------------------------+ 112 | | runtime | The time that is recorded for this run. Does not have | 113 | | | to be the actual runtime, but your function will be | 114 | | | restricted to certain CPU time limits if you optimize | 115 | | | run time. Use this to provide a more precise time | 116 | | | measurement. | 117 | +-------------+--------------------------------------------------------+ 118 | | status | SMAC has historically strong ties to the SAT community,| 119 | | | and where every run yields either shows that a given | 120 | | | boolean formula is satisfiable or unsatisfialble. | 121 | | | The status indicates whether the run was succesfull | 122 | | | (SAT/UNSAT) or not (TIMEOUT/CRASHED/ABORT). Please | 123 | | | consult the SMAC manual for more details. | 124 | +-------------+--------------------------------------------------------+ 125 | 126 | 127 | 128 | .. _training_instances: 129 | 130 | Optimizing on a Set of Instances 131 | -------------------------------- 132 | 133 | Commonly in algorithm configuration, one is not only interested in optimizing 134 | a simple function, but rather the overall performance across a set of 135 | instances (called the training set). This adds to the complexity 136 | of the problem as a single configuration has to be evaluated on several 137 | instances to estimate its performance. 138 | 139 | The num_train_instances argument of :py:meth:`pySMAC.optimizer.SMAC_optimizer.minimize` 140 | specifies the number of instances your function accepts. If it is a positive 141 | integer, pySMAC will call your function with an additional argument, called **instance**. 142 | This parameter will be an int in ``range(num_train_instances)``. What the 143 | underlying meaning of this instance number is has to be implemented in your 144 | function. For example, one can use different cross-validation folds as 145 | instances when optimizing a machine learning method. The file 146 | *sklearn_example_advanced_crossvalidation.py* presents this use-case. 147 | 148 | 149 | 150 | .. _validation: 151 | 152 | Validation 153 | ---------- 154 | 155 | When optimizing on instances, the final evaluation of a configuration's 156 | performance does not take place on the training set used during the 157 | optimization. Doing so usually leads to overfitting, and poor generalization 158 | to unseen instances. Instead, a separate set, called the test set, is used 159 | to assess the performance of a configuration. 160 | 161 | This behavior is activated in pySMAC by specifying the argument 162 | num_test_instances of :py:meth:`pySMAC.optimizer.SMAC_optimizer.minimize`. 163 | These instances are represented by integers from ``range(num_train_instances, num_train_instances + num_test_instances)``. 164 | 165 | After the budget of function evaluations is exhausted, SMAC will run 166 | the configuration with the best estimated trainings performance on the 167 | complete test set as a validation. 168 | 169 | .. note:: 170 | 171 | Right now, this option overwrites the entries 172 | ``validate-only-last-incumbent`` and ``validation`` in the smac_option 173 | ``dict`` (see :ref:`advanced_options`) with ``True``. In future versions, 174 | pySMAC should/will honor user set values for those variables. 175 | 176 | 177 | .. _non-deterministic: 178 | 179 | Non-determinstic Functions 180 | -------------------------- 181 | 182 | If your function uses any source of randomness, and its performance might 183 | crucially depend on it, SMAC can take this into account, too. In order get 184 | reproducible results, SMAC now also associates a seed with every call, that 185 | becomes an argument of your function. Given the same seed and the same input 186 | you function be deterministic. This way, SMAC can rerun the same configuration 187 | with different seeds to estimate the performance. By setting, 188 | ``deterministic = False`` in the call to 189 | :py:meth:`pySMAC.optimizer.SMAC_optimizer.minimize` this behavior is enabled. 190 | 191 | -------------------------------------------------------------------------------- /doc/conf.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | # -*- coding: utf-8 -*- 3 | # 4 | # pySMAC documentation build configuration file, created by 5 | # sphinx-quickstart on Mon Jul 13 09:53:58 2015. 6 | # 7 | # This file is execfile()d with the current directory set to its 8 | # containing dir. 9 | # 10 | # Note that not all possible configuration values are present in this 11 | # autogenerated file. 12 | # 13 | # All configuration values have a default; values that are commented out 14 | # serve to show the default. 15 | 16 | import sys 17 | import os 18 | import shlex 19 | 20 | # If extensions (or modules to document with autodoc) are in another directory, 21 | # add these directories to sys.path here. If the directory is relative to the 22 | # documentation root, use os.path.abspath to make it absolute, like shown here. 23 | #sys.path.insert(0, os.path.abspath('.')) 24 | sys.path.insert(0, os.path.abspath("../../pynisher/")) 25 | sys.path.insert(0, os.path.abspath("..")) 26 | 27 | # to avoid build errors on ReadTheDocs due to missing libraries 28 | try: 29 | from unittest.mock import MagicMock 30 | except ImportError: 31 | from mock import MagicMock 32 | 33 | class Mock(MagicMock): 34 | @classmethod 35 | def __getattr__(cls, name): 36 | return Mock() 37 | 38 | MOCK_MODULES = ['numpy', 'pynisher'] 39 | sys.modules.update((mod_name, Mock()) for mod_name in MOCK_MODULES) 40 | 41 | 42 | # -- General configuration ------------------------------------------------ 43 | 44 | # If your documentation needs a minimal Sphinx version, state it here. 45 | #needs_sphinx = '1.0' 46 | 47 | # Add any Sphinx extension module names here, as strings. They can be 48 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom 49 | # ones. 50 | extensions = [ 51 | 'sphinx.ext.autodoc', 52 | 'sphinx.ext.todo', 53 | 'sphinx.ext.coverage', 54 | 'sphinx.ext.mathjax', 55 | 'sphinx.ext.ifconfig', 56 | 'sphinx.ext.viewcode', 57 | ] 58 | 59 | # Add any paths that contain templates here, relative to this directory. 60 | templates_path = ['_templates'] 61 | 62 | # The suffix(es) of source filenames. 63 | # You can specify multiple suffix as a list of string: 64 | # source_suffix = ['.rst', '.md'] 65 | source_suffix = '.rst' 66 | 67 | # The encoding of source files. 68 | #source_encoding = 'utf-8-sig' 69 | 70 | # The master toctree document. 71 | master_doc = 'index' 72 | 73 | # General information about the project. 74 | project = 'pySMAC' 75 | copyright = '2015, Stefan Falkner' 76 | author = 'Stefan Falkner' 77 | 78 | # The version info for the project you're documenting, acts as replacement for 79 | # |version| and |release|, also used in various other places throughout the 80 | # built documents. 81 | # 82 | # The short X.Y version. 83 | version = '0.9' 84 | # The full version, including alpha/beta/rc tags. 85 | release = '0.9' 86 | 87 | # The language for content autogenerated by Sphinx. Refer to documentation 88 | # for a list of supported languages. 89 | # 90 | # This is also used if you do content translation via gettext catalogs. 91 | # Usually you set "language" from the command line for these cases. 92 | language = None 93 | 94 | # There are two options for replacing |today|: either, you set today to some 95 | # non-false value, then it is used: 96 | #today = '' 97 | # Else, today_fmt is used as the format for a strftime call. 98 | #today_fmt = '%B %d, %Y' 99 | 100 | # List of patterns, relative to source directory, that match files and 101 | # directories to ignore when looking for source files. 102 | exclude_patterns = ['_build'] 103 | 104 | # The reST default role (used for this markup: `text`) to use for all 105 | # documents. 106 | #default_role = None 107 | 108 | # If true, '()' will be appended to :func: etc. cross-reference text. 109 | #add_function_parentheses = True 110 | 111 | # If true, the current module name will be prepended to all description 112 | # unit titles (such as .. function::). 113 | #add_module_names = True 114 | 115 | # If true, sectionauthor and moduleauthor directives will be shown in the 116 | # output. They are ignored by default. 117 | #show_authors = False 118 | 119 | # The name of the Pygments (syntax highlighting) style to use. 120 | pygments_style = 'sphinx' 121 | 122 | # A list of ignored prefixes for module index sorting. 123 | #modindex_common_prefix = [] 124 | 125 | # If true, keep warnings as "system message" paragraphs in the built documents. 126 | #keep_warnings = False 127 | 128 | # If true, `todo` and `todoList` produce output, else they produce nothing. 129 | todo_include_todos = True 130 | 131 | 132 | # -- Options for HTML output ---------------------------------------------- 133 | 134 | # The theme to use for HTML and HTML Help pages. See the documentation for 135 | # a list of builtin themes. 136 | #html_theme = 'classic' 137 | html_theme = 'sphinxdoc' 138 | 139 | # Theme options are theme-specific and customize the look and feel of a theme 140 | # further. For a list of options available for each theme, see the 141 | # documentation. 142 | #html_theme_options = {} 143 | 144 | # Add any paths that contain custom themes here, relative to this directory. 145 | #html_theme_path = [] 146 | 147 | # The name for this set of Sphinx documents. If None, it defaults to 148 | # " v documentation". 149 | #html_title = None 150 | 151 | # A shorter title for the navigation bar. Default is the same as html_title. 152 | #html_short_title = None 153 | 154 | # The name of an image file (relative to this directory) to place at the top 155 | # of the sidebar. 156 | #html_logo = None 157 | 158 | # The name of an image file (within the static path) to use as favicon of the 159 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 160 | # pixels large. 161 | #html_favicon = None 162 | 163 | # Add any paths that contain custom static files (such as style sheets) here, 164 | # relative to this directory. They are copied after the builtin static files, 165 | # so a file named "default.css" will overwrite the builtin "default.css". 166 | html_static_path = ['_static'] 167 | 168 | # Add any extra paths that contain custom files (such as robots.txt or 169 | # .htaccess) here, relative to this directory. These files are copied 170 | # directly to the root of the documentation. 171 | #html_extra_path = [] 172 | 173 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, 174 | # using the given strftime format. 175 | #html_last_updated_fmt = '%b %d, %Y' 176 | 177 | # If true, SmartyPants will be used to convert quotes and dashes to 178 | # typographically correct entities. 179 | #html_use_smartypants = True 180 | 181 | # Custom sidebar templates, maps document names to template names. 182 | #html_sidebars = {} 183 | 184 | # Additional templates that should be rendered to pages, maps page names to 185 | # template names. 186 | #html_additional_pages = {} 187 | 188 | # If false, no module index is generated. 189 | #html_domain_indices = True 190 | 191 | # If false, no index is generated. 192 | #html_use_index = True 193 | 194 | # If true, the index is split into individual pages for each letter. 195 | #html_split_index = False 196 | 197 | # If true, links to the reST sources are added to the pages. 198 | #html_show_sourcelink = True 199 | 200 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 201 | #html_show_sphinx = True 202 | 203 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 204 | #html_show_copyright = True 205 | 206 | # If true, an OpenSearch description file will be output, and all pages will 207 | # contain a tag referring to it. The value of this option must be the 208 | # base URL from which the finished HTML is served. 209 | #html_use_opensearch = '' 210 | 211 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 212 | #html_file_suffix = None 213 | 214 | # Language to be used for generating the HTML full-text search index. 215 | # Sphinx supports the following languages: 216 | # 'da', 'de', 'en', 'es', 'fi', 'fr', 'h', 'it', 'ja' 217 | # 'nl', 'no', 'pt', 'ro', 'r', 'sv', 'tr' 218 | #html_search_language = 'en' 219 | 220 | # A dictionary with options for the search language support, empty by default. 221 | # Now only 'ja' uses this config value 222 | #html_search_options = {'type': 'default'} 223 | 224 | # The name of a javascript file (relative to the configuration directory) that 225 | # implements a search results scorer. If empty, the default will be used. 226 | #html_search_scorer = 'scorer.js' 227 | 228 | # Output file base name for HTML help builder. 229 | htmlhelp_basename = 'pySMACdoc' 230 | 231 | # -- Options for LaTeX output --------------------------------------------- 232 | 233 | latex_elements = { 234 | # The paper size ('letterpaper' or 'a4paper'). 235 | #'papersize': 'letterpaper', 236 | 237 | # The font size ('10pt', '11pt' or '12pt'). 238 | #'pointsize': '10pt', 239 | 240 | # Additional stuff for the LaTeX preamble. 241 | #'preamble': '', 242 | 243 | # Latex figure (float) alignment 244 | #'figure_align': 'htbp', 245 | } 246 | 247 | # Grouping the document tree into LaTeX files. List of tuples 248 | # (source start file, target name, title, 249 | # author, documentclass [howto, manual, or own class]). 250 | latex_documents = [ 251 | (master_doc, 'pySMAC.tex', 'pySMAC Documentation', 252 | 'Stefan Falkner', 'manual'), 253 | ] 254 | 255 | # The name of an image file (relative to this directory) to place at the top of 256 | # the title page. 257 | #latex_logo = None 258 | 259 | # For "manual" documents, if this is true, then toplevel headings are parts, 260 | # not chapters. 261 | #latex_use_parts = False 262 | 263 | # If true, show page references after internal links. 264 | #latex_show_pagerefs = False 265 | 266 | # If true, show URL addresses after external links. 267 | #latex_show_urls = False 268 | 269 | # Documents to append as an appendix to all manuals. 270 | #latex_appendices = [] 271 | 272 | # If false, no module index is generated. 273 | #latex_domain_indices = True 274 | 275 | 276 | # -- Options for manual page output --------------------------------------- 277 | 278 | # One entry per manual page. List of tuples 279 | # (source start file, name, description, authors, manual section). 280 | man_pages = [ 281 | (master_doc, 'pysmac', 'pySMAC Documentation', 282 | [author], 1) 283 | ] 284 | 285 | # If true, show URL addresses after external links. 286 | #man_show_urls = False 287 | 288 | 289 | # -- Options for Texinfo output ------------------------------------------- 290 | 291 | # Grouping the document tree into Texinfo files. List of tuples 292 | # (source start file, target name, title, author, 293 | # dir menu entry, description, category) 294 | texinfo_documents = [ 295 | (master_doc, 'pySMAC', 'pySMAC Documentation', 296 | author, 'pySMAC', 'One line description of project.', 297 | 'Miscellaneous'), 298 | ] 299 | 300 | # Documents to append as an appendix to all manuals. 301 | #texinfo_appendices = [] 302 | 303 | # If false, no module index is generated. 304 | #texinfo_domain_indices = True 305 | 306 | # How to display URL addresses: 'footnote', 'no', or 'inline'. 307 | #texinfo_show_urls = 'footnote' 308 | 309 | # If true, do not generate a @detailmenu in the "Top" node's menu. 310 | #texinfo_no_detailmenu = False 311 | 312 | 313 | 314 | autoclass_content = 'both' 315 | -------------------------------------------------------------------------------- /doc/index.rst: -------------------------------------------------------------------------------- 1 | .. pySMAC documentation master file, created by 2 | sphinx-quickstart on Mon Jul 13 09:53:58 2015. 3 | You can adapt this file completely to your liking, but it should at least 4 | contain the root `toctree` directive. 5 | 6 | Welcome to pySMAC's documentation! 7 | ================================== 8 | 9 | Contents: 10 | 11 | .. toctree:: 12 | :maxdepth: 2 13 | 14 | quickstart 15 | pcs 16 | advanced_configuration 17 | analysis 18 | pysmac 19 | 20 | Indices and tables 21 | ================== 22 | 23 | * :ref:`genindex` 24 | * :ref:`search` 25 | 26 | .. * :ref:`modindex` 27 | -------------------------------------------------------------------------------- /doc/modules.rst: -------------------------------------------------------------------------------- 1 | pySMAC 2 | ====== 3 | 4 | .. toctree:: 5 | :maxdepth: 4 6 | 7 | pysmac 8 | -------------------------------------------------------------------------------- /doc/pcs.rst: -------------------------------------------------------------------------------- 1 | .. _pcs: 2 | 3 | ========================================== 4 | Defining the Parameter Configuration Space 5 | ========================================== 6 | 7 | This pages explains in detail how the types, allowed and default 8 | values of all parameters are defined. It also covers how dependencies 9 | and constraints between them can be modeled. 10 | 11 | .. _parameter_defs: 12 | 13 | Parameter Definitions 14 | ===================== 15 | 16 | The definition of the parameters is stored in a dictionary, where the name 17 | of the parameter as the key, and a tuple containing all necessary information 18 | constitutes the corresponding value. SMAC, the configuration system underlying 19 | pySMAC, discriminates four different parameter types: 20 | 21 | 1. **real** -- take any value in a specified range. 22 | 2. **integer** -- take any integral value in a specified range. 23 | 3. **categorical** -- take one of a finite set of values. 24 | 4. **ordinal** -- are essentially categorical parameters with a natural ordering between the elements. 25 | 26 | 27 | We shall look at a simple example for all four types to show how they are defined: 28 | 29 | .. code-block:: python 30 | 31 | parameter_definitions=dict(\ 32 | a_float_parameter = ("real" , [-3.5, 2.48] , 1.1 ), 33 | an_integer_parameter = ("integer" , [1, 1000] , 2 ,"log"), 34 | a_categorical_parameter = ("categorical", ["yes", "no", "maybe"] , "yes" ), 35 | a_ordinal_parameter = ("ordinal" , ["cold", "cool", "medium", "warm", "hot"], "medium" ) 36 | ) 37 | 38 | The definition of each parameter follows the same pattern: first its type, 39 | followed by a list defining the allowed values, and finally the default value. 40 | 41 | For **real** and **integer** type, the allowed values are defined by a range, 42 | represented by a list with exactly two elements. The default 43 | value has to be inside this range to yield a legal definition. Both the 44 | range and the default of an **integer** have to be Python **int**\s 45 | 46 | There exists an optional flag "log" that can be given additionally as the 47 | last element of a tuple for these two types. If given, the parameter is 48 | varied on a logarithmic scale, meaning that the logarithm of the value is 49 | uniformly distributed between the logarithm of the bounds. Therefore, this 50 | option can only be given if the parameter is strictly positive! 51 | 52 | For **categorical** and **ordinal** the list of allowed values can contain 53 | any number (>0) of elements. Every element constitutes a valid value for 54 | this parameter. The default value has to be among them. The ordering of 55 | an **ordinal** parameter is established by the order in the list. 56 | 57 | The Python type for **categorical** and **ordinal** parameters can be a numeric 58 | type of a string. The only restriction is, that all allowed values for one 59 | parameter are all of the same time. For example, the following definition is 60 | not valid: 61 | 62 | .. code-block:: python 63 | 64 | parameter_definitions=dict(\ 65 | a = ("integer" , [1, 1000] , 2.0 ), # default value is not of type int 66 | b = ("categorical", ["True", "False",1], 1), # 2 str and one int value 67 | ) 68 | 69 | 70 | .. note:: 71 | 72 | Defining the parameter configuration space can be quite challenging, e.g., 73 | if the number of parameters is large. So typos and/or inconsistencies 74 | can happen. SMAC itself checks the definitions in great detail, and pySMAC 75 | provides also some sanity checks with (hopefully) helpful error messages 76 | to assist in this tedious task. 77 | 78 | 79 | 80 | 81 | Conditional Parameter Clauses 82 | ============================= 83 | 84 | In many cases, certain parameters only have any meaning if another one takes 85 | a certain value. For example, one parameter might activate or deactivate a 86 | subroutine which has parameters itself. Naturally, the latter are only relevant 87 | when the subroutine is actually used. These dependencies can be expressed in 88 | pySMAC to accelerate the configuration process (by reducing the number of 89 | active parameters). 90 | 91 | To illustrate this, let's focus on the example in ``sklearn_model_selection.py``. 92 | The script demonstrates a use-case from machine learning. Given a data set, there 93 | are numerous models that can be used to *learn* from it and apply this *knowledge* 94 | to unseen data points. In this simple example, we generate a random data set and 95 | try to find the model (with the best parameter settings) among only three very basic 96 | ones, namely: k-nearest-neighbors, random forests, and extremely randomized trees. 97 | In order to run that example, you need the scikit-learn package, but the 98 | source code below should be illustrative enough to show how to use conditionals. 99 | 100 | 101 | .. literalinclude:: ../examples/sklearn_model_selection.py 102 | :linenos: 103 | 104 | 105 | The output looks like that (note the random data set leads to slightly different numbers for every run): 106 | 107 | .. code-block:: shell 108 | 109 | The default accuracy of the random forest is 0.909091 110 | The default accuracy of the extremely randomized trees is 0.903030 111 | The default accuracy of k-nearest-neighbors is 0.863636 112 | The highest accuracy found: 0.936364 113 | Parameter setting {'knn_weights': 'distance', 'trees_n_estimators': '8', 'knn_n_neighbors': '1', 'classifier': 'random_forest', 'trees_max_features': '10', 'trees_max_depth': '2', 'trees_criterion': 'gini'} 114 | 115 | The script shows how pySMAC can be used for model selection and simultaneous 116 | optimization. The function to be minimized (*choose_classifier*, line 19) 117 | returns the negative accuracy of training one out of three machine learning 118 | models (a random forest, extremely randomized trees, and k-nearest-neighbors). 119 | So effectively, SMAC is asked to maximize the accuracy choosing either of 120 | these models and its respective parameters. 121 | 122 | The parameter definitions are stated between line 44 and 55. Naturally, 123 | the ones for K-nearest-neighbors and the two tree based classifiers are 124 | independent. Therefore, the parameters of the former 125 | affect the accuracy only if this classifier is actually chosen. 126 | 127 | The variable *conditionals*, defined in line 64, shows some examples for 128 | how these dependencies between parameters are expressed. Generally they 129 | follow the template: 130 | 131 | .. code-block:: shell 132 | 133 | child_name | condition1 (&& or ||) condition2 (&& or ||) ... 134 | 135 | The *child* variable is only considered active if the logic expression following 136 | the "|" is true. 137 | 138 | .. note:: 139 | 140 | From the SMAC manual 141 | * Parameters not listed as a child in any conditional parameter clause are always active. 142 | * A child's name can appear only once. 143 | * There is no support for parenthesis with conditionals. The && connective has higher precedence than ||, so a||b&& c||d is the same as a||(b&&c)||d. 144 | 145 | The conditions can take different forms: 146 | 147 | .. code-block:: c 148 | 149 | parent_name in {value1, value2, ... } 150 | parent_name == value parent_name != value 151 | parent_name < value parent_name > value 152 | 153 | The first one is true if the parent takes any of the values listed. The 154 | other expressions have the regular meaning. The operators in the last line 155 | are only legal for **real**, **integer** or **ordinal**, while the 156 | others can be used with any type. 157 | 158 | 159 | Forbidden Parameter Clauses 160 | ============================= 161 | 162 | In some use-cases, certain parameter configurations might be illegal, or 163 | lead to undefined behavior. For example, some algorithms might be able to 164 | employ different data structures, and different subroutines, controlled 165 | by two parameters: 166 | 167 | .. code-block:: python 168 | 169 | parameter_definition = dict(\ 170 | DS = ("categorical", [DataStructure1, DataStructure2, DataStructure3],DataStructure1 ), 171 | SR = ("categorical", [SubRoutine1, SubRoutine2, SubRoutine3], SubRoutine1) 172 | ) 173 | 174 | 175 | Let's assume that DataStructure2 is incompatible with SubRoutine3, 176 | i.e. evaluating this combination does not yield a meaningful result, 177 | or might even cause a system crash. That means one out of nine possible 178 | choices for these two parameters is forbidden. 179 | 180 | One can certainly change the parameters and their definitions such that they exclude 181 | this case explicitly. One could, i.e., combine the two parameters and list 182 | all eight allowed values: 183 | 184 | .. code-block:: python 185 | 186 | parameter_definition = dict(\ 187 | DS_SR = ("categorical", [DS1_SR1, DS1_SR2, DS1_SR2, DS2_SR1, DS2_SR2, DS3_SR1, DS3_SR2, DS3_SR3], [DS1_SR1]) 188 | ) 189 | 190 | This is not only unpractical, but it forbids SMAC to learn about the data 191 | structures and subroutines independently. It is much more efficient to 192 | specifically exclude this one combination by defining a forbidden parameter 193 | clause. The **classic syntax** is as follows: 194 | 195 | .. code-block:: python 196 | 197 | "{parameter_name1 = value1, ..., parameter_nameN = ValueN}" 198 | 199 | It allows to specify combinations of values that are forbidden. For our 200 | example above, the appropriate forbidden clause would be 201 | 202 | .. code-block:: python 203 | 204 | forbidden_confs = ["{DS = DataStructure2, SR = SubRoutine3}"] 205 | 206 | .. note:: 207 | The pair of curly braces {} around the expression is mandatory. The 208 | pySMAC notation here is a direct copy of the SMAC one. These strings 209 | are merely handed over to SMAC without any processing. That way, 210 | statements from the SMAC manual are applicable to pySMAC as well. 211 | 212 | A list of all forbidden clauses is than passed to the minimize method 213 | with the forbidden_clauses keyword. So the corresponding 214 | call to the minimize method would look like this: 215 | 216 | .. code-block:: python 217 | 218 | opt = pysmac.SMAC_optimizer() 219 | value, config = opt.minimize(function_to_minimize, num_function_calls, 220 | parameter_definition, 221 | forbidden_clasuses = forbidden_confs) 222 | 223 | 224 | Of course, conditionals and forbidden clauses are not mutual exclusive, 225 | but you can define both and use them while minimizing the function. 226 | 227 | Introduced in SMAC 2.10, there is an **advanced syntax** that allows more 228 | complex situations to be handled. It allows to compare parameter values to 229 | each other, and apply a limit set of functions: 230 | 231 | +---------------------+----------------------------------------------------------------------------------------+ 232 | |Arithmetic Operations| +,-,*,/,^, Unary +/-, and % | 233 | +---------------------+----------------------------------------------------------------------------------------+ 234 | | Functions | abs, (a)cos, (a)sin, (a)tan, exp, sinh, cosh, ceil, floor, log, log2, log10, sqrt, cbrt| 235 | +---------------------+----------------------------------------------------------------------------------------+ 236 | | Logical Operators | >=, <=, >, <, ==, !=, ||, && | 237 | +---------------------+----------------------------------------------------------------------------------------+ 238 | 239 | 240 | Some examples (without the appropriate parameter definitions) to illustrate this notation: 241 | 242 | .. code-block:: python 243 | 244 | forbidden_confs = ["{activity == 'swimming' && water_temperature < 15}", 245 | "{x^2 + y^2 < 1}", 246 | "{sqrt(a) + log10(b) >= - exp(2)}"] 247 | 248 | 249 | .. note:: 250 | The SMAC manual has an extensive section on important tips and caveats 251 | related to forbidden parameters. Here are some major points 252 | 253 | * SMAC generates random configurations without honoring the forbidden clauses, but rejects those that violate at least one. So constraining the space too much will slow down the process. 254 | * Even meaningless forbidden clauses (those that are always false) still take time to evaluate slowing SMAC down. 255 | * Applying arithmetic operations/function to non-numerical values for categoricals/ordinals leads to undefined behavior! 256 | For **categorical** types only == and != should be used. You may use >=, <=, <, and > for **ordinal** parameters. 257 | * Don't use == and != for **real** types, as they are almost always false, or true respectively. 258 | * names and values of parameters must not contain anything besides alphanumeric characters and underscores. 259 | * When defining **ordinal** parameters, you have to keep the values consistent. E.g. 260 | 261 | .. code-block:: python 262 | 263 | parameter_definition = dict(\ 264 | a = ("ordinal", ["warm", "medium", "cold"], "medium"), 265 | b = ("ordinal", ["cold", "medium", "warm"], "medium"), 266 | c = ("ordinal", [100, 10, 1], 100)) 267 | 268 | The problem here is that "warm < cold" for a, but "warm > cold" for b. 269 | For numerical values the definition of c implies "100<10", which is not true. 270 | 271 | For more details, please refer to the SMAC manual. 272 | 273 | 274 | .. _merge_pcs: 275 | 276 | Combining Parameter Configuration Spaces 277 | ---------------------------------------- 278 | 279 | 280 | .. literalinclude:: ../examples/merge_pcs.py 281 | :linenos: 282 | -------------------------------------------------------------------------------- /doc/pysmac.rst: -------------------------------------------------------------------------------- 1 | Detailed API documentation 2 | ========================== 3 | 4 | .. comment 5 | pysmac.analyzer module 6 | ---------------------- 7 | 8 | .. automodule:: pysmac.analyzer 9 | :members: 10 | :undoc-members: 11 | :show-inheritance: 12 | 13 | pysmac.optimizer module 14 | ----------------------- 15 | 16 | .. automodule:: pysmac.optimizer 17 | :members: 18 | :undoc-members: 19 | :show-inheritance: 20 | 21 | pysmac.remote_smac module 22 | ------------------------- 23 | 24 | .. automodule:: pysmac.remote_smac 25 | :members: 26 | :undoc-members: 27 | :show-inheritance: 28 | 29 | Subpackages 30 | ----------- 31 | 32 | .. toctree:: 33 | 34 | pysmac.utils 35 | -------------------------------------------------------------------------------- /doc/pysmac.utils.rst: -------------------------------------------------------------------------------- 1 | pysmac.utils package 2 | ==================== 3 | 4 | 5 | pysmac.utils.java_helper module 6 | ------------------------------- 7 | 8 | .. automodule:: pysmac.utils.java_helper 9 | :members: 10 | :undoc-members: 11 | :show-inheritance: 12 | 13 | pysmac.utils.multiprocessing_wrapper module 14 | ------------------------------------------- 15 | 16 | .. automodule:: pysmac.utils.multiprocessing_wrapper 17 | :members: 18 | :undoc-members: 19 | :show-inheritance: 20 | 21 | pysmac.utils.smac_input_readers module 22 | -------------------------------------- 23 | 24 | .. automodule:: pysmac.utils.smac_input_readers 25 | :members: 26 | :undoc-members: 27 | :show-inheritance: 28 | 29 | pysmac.utils.smac_output_readers module 30 | --------------------------------------- 31 | 32 | .. automodule:: pysmac.utils.smac_output_readers 33 | :members: 34 | :undoc-members: 35 | :show-inheritance: 36 | 37 | pysmac.utils.state_merge module 38 | ------------------------------- 39 | 40 | .. automodule:: pysmac.utils.state_merge 41 | :members: 42 | :undoc-members: 43 | :show-inheritance: 44 | 45 | pysmac.utils.pcs_merge module 46 | ------------------------------- 47 | 48 | .. automodule:: pysmac.utils.pcs_merge 49 | :members: 50 | :undoc-members: 51 | :show-inheritance: 52 | -------------------------------------------------------------------------------- /doc/quickstart.rst: -------------------------------------------------------------------------------- 1 | ================ 2 | Quickstart Guide 3 | ================ 4 | 5 | This quickstart guide tries to show the basic mechanisms of how to use pySMAC 6 | to find good input parameters to a python function minimizing the return value. 7 | 8 | To gain familiarity with the workflow, we shall dissect the file "rosenbrock_example.py" 9 | which can be found in the example folder. The full script looks like this: 10 | 11 | .. literalinclude:: ../examples/rosenbrock_example.py 12 | :linenos: 13 | 14 | After the necessary import, the function ''rosenbrock_4d'' is defined. 15 | This function function is well know and often used test function in the 16 | optimization community. Normally, all parameters are continuous, but we 17 | will declare three of them to be integer valued to demonstrate the different 18 | types that (py)SMAC supports. 19 | 20 | The next step is to specify the type, range and default value of every 21 | parameter in the ``pySMAC way``. In our example, this is done by defining 22 | the dictionary 23 | 24 | .. code-block:: python 25 | 26 | parameters=dict(\ 27 | x1=('real', [-5, 5], 5), 28 | x2=('integer', [-5, 5], 5), 29 | x3=('categorical',[5, 2, 0, 1, -1, -2, 4, -3, 3, -5, -4], 5), 30 | x4=('ordinal', [-5,-4,-3,-2,-1,0,1,2,3,4,5] , 5), 31 | ) 32 | 33 | Every entry defines a parameter with its name as the key and a tuple 34 | as the corresponding value. The first entry of the tuple defines the type, 35 | here ``x1`` is a **real**, i.e. a continuous parameter, while ``x2`` is an integer. 36 | **Categorical** types, like ``x3``, can only take a value from a user-provided set. 37 | There is no specific order among the elements, which is why in the example the 38 | order of the values is shuffled. In contrast, **ordinal** parameters posses an 39 | inherent ordering between their values. In the defining list, elements are 40 | assumed to be in increasing order. 41 | 42 | The second entry of the tuple defines the possible value. For numerical parameters, 43 | this has to be a 2-element list containing the smallest and the largest allowed value. 44 | For **categorical** and **ordinal** values this list contains all allowed values. 45 | 46 | The third tuple entry is the default value. This has to be inside the specified 47 | range for **real** and **integer**, or an element of the previous list for 48 | **ordinal** and **categorical**. 49 | Please refer to the section :ref:`parameter_defs` for more detail. 50 | 51 | The example here is cooked up and overly complicated for the actual optimization 52 | problem. For instance, the definitions for ``x2`` and ``x4`` are identical, and 53 | defining ``x3`` as a **categorical** with only integral values is not exactly the 54 | same as a **integer** type. But the purpose of this guide was to introduce pySMAC's 55 | syntax, not solving an interesting problem in the most efficient way possible. 56 | 57 | To start the actual minimization, we instantiate a SMAC_optimizer object, 58 | and call its minimize method with at least 3 argument: 59 | 60 | .. code-block:: python 61 | 62 | opt = pySMAC.SMAC_optimizer() 63 | value, parameters = opt.minimize(rosenbrock_4d, 1000, parameters) 64 | 65 | The arguments of minimze are the function we which to minimize, the budged 66 | of function calls, and the parameter definition. It returns the lowest 67 | function value encountered, and the corresponding parameter configuration 68 | as a dictionary with parameter name - parameter value as key-value pairs. 69 | 70 | The reason why an object is created before a minimization function is called 71 | will become clear in the section :ref:`advanced_configuration`. 72 | 73 | The output of the code could look like this: 74 | 75 | .. code-block:: html 76 | 77 | Lowest function value found: 1.691811 78 | Parameter setting {'x3': '1', 'x1': '0.9327937187899629', 'x4': '1', 'x2': '1'} 79 | 80 | with the true minimum at (1,1,1,1) having a function value of 0. Given 1000 81 | function evaluations, this result is not competitive to continuous optimizers 82 | if we would drop the integral restriction for ``x2``, ``x3``, and ``x4``. Continuous 83 | optimization allows to estimate and exploit gradients which can lead to a much 84 | faster convergence towards a local optimum. But the purpose of this quickstart guide 85 | is solely to introduce how to use pySMAC rather than showing an interesting example. 86 | The strength of pySMAC become more visible in more complicated cases that are usually 87 | infeasible for standard optimizers. 88 | -------------------------------------------------------------------------------- /examples/branin_example.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function, division 2 | 3 | import sys 4 | sys.path.append("..") 5 | 6 | import pysmac 7 | import math 8 | 9 | # To demonstrate the use, we shall look at a slight modification of the well- 10 | # known branin funtcion. To make things a little bit more interesting, we add 11 | # a third parameter (x3). It has to be an integer, which is usually not 12 | # covered by standard global minimizers. 13 | # SMAC will acutally not impress for this function as SMAC's focus is more on 14 | # high dimensional problems with also categorical parameters, and possible 15 | # dependencies between them. This is where the underlying random forest realy 16 | # shines. 17 | def modified_branin(x1, x2, x3): 18 | # enforce that x3 has an integer value 19 | if (int(x3) != x3): 20 | raise ValueError("parameter x3 has to be an integer!") 21 | a = 1 22 | b = 5.1 / (4*math.pi**2) 23 | c = 5 / math.pi 24 | r = 6 25 | s = 10 26 | t = 1 / (8*math.pi) 27 | ret = a*(x2-b*x1**2+c*x1-r)**2+s*(1-t)*math.cos(x1)+s + x3 28 | return ret 29 | 30 | 31 | 32 | # Now we have to define the parameters for the function we like to minimize. 33 | # The representation tries to stay close to the SMAC manual, but deviates 34 | # if necessary. # Because we use a Python dictionary to represent the 35 | # parameters, there are different ways of creating it. The author finds the 36 | # following way most intuitive: 37 | parameter_definition=dict(\ 38 | x1=('real', [-5, 5], 1), # this line means x1 is a float between -5 and 5, with a default of 1 39 | x2=('real', [-5, 5], -1), # same as x1, but the default is -1 40 | x3=('integer', [0, 10], 1), # integer that ranges between 0 and 10, default is 1 41 | ) 42 | 43 | 44 | # Consult the docs for a comprehensive presentation of possibilities. 45 | 46 | 47 | 48 | # The next step is to create a SMAC_optimizer object 49 | opt = pysmac.SMAC_optimizer(debug=False) 50 | 51 | # Then, call its minimize method with at least the three mandatory parameters 52 | value, parameters = opt.minimize(modified_branin, # the function to be minimized 53 | 1000, # the maximum number of function evaluations 54 | parameter_definition) # the parameter dictionary 55 | 56 | 57 | # the return value is a tuple of the lowest function value and a dictionary 58 | # containing corresponding parameter setting. 59 | print(('Lowest function value found: %f'%value)) 60 | print(('Parameter setting %s'%parameters)) 61 | -------------------------------------------------------------------------------- /examples/merge_pcs.py: -------------------------------------------------------------------------------- 1 | import sys 2 | sys.path.append("../../pynisher") 3 | sys.path.append('..') 4 | 5 | import pysmac 6 | 7 | import sklearn.ensemble 8 | import sklearn.neighbors 9 | import sklearn.datasets 10 | import sklearn.cross_validation 11 | 12 | # We use a random classification data set generated by sklearn 13 | # As commonly done, we use a train-test split to avoid overfitting. 14 | X,Y = sklearn.datasets.make_classification(1000, 20) 15 | X_train, X_test, Y_train, Y_test = \ 16 | sklearn.cross_validation.train_test_split(X,Y, test_size=0.33, random_state=1) 17 | 18 | 19 | # training a random forest 20 | def random_forest (n_trees=None, criterion=None, max_features=None, max_depth=None): 21 | predictor = sklearn.ensemble.RandomForestClassifier(n_trees, criterion, max_features, max_depth) 22 | predictor.fit(X_train, Y_train) 23 | return (-predictor.score(X_test, Y_test)) 24 | 25 | # and defining some of its parameters 26 | parameters_trees = dict(\ 27 | max_depth = ("integer", [1,10], 4), 28 | max_features=("integer", [1,20], 10), 29 | n_trees=("integer", [1,100],10 ,'log'), 30 | criterion =("categorical", ['gini', 'entropy'], 'entropy'), 31 | ) 32 | 33 | # training a k-nearest neighbor classifier 34 | def knn (n_neighbors=None, weights=None): 35 | predictor = sklearn.neighbors.KNeighborsClassifier(n_neighbors, weights) 36 | predictor.fit(X_train, Y_train) 37 | return (-predictor.score(X_test, Y_test)) 38 | 39 | # and defining some of its paramers 40 | parameters_knn = dict(\ 41 | n_neighbors = ("integer", [1,100], 10, 'log'), 42 | weights = ("categorical", ['uniform', 'distance'], 'uniform'), 43 | ) 44 | 45 | 46 | 47 | # convenience function 48 | from pysmac.utils.pcs_merge import merge_configuration_spaces 49 | 50 | # returns a parameter config space, the conditionals, forbiddens and two wrapper functions 51 | p,c,f,wrapper_str = merge_configuration_spaces(\ 52 | (random_forest, parameters_trees, [], []), 53 | (knn, parameters_knn, [],[])) 54 | 55 | # workaround to make the generated functions pickable (needed for pySMAC internals): 56 | # they are generated as strings, and instantiated by executing this string 57 | exec(wrapper_str) 58 | 59 | 60 | # create optimizer object 61 | opt = pysmac.SMAC_optimizer( debug = 0, 62 | working_directory = '/tmp/pySMAC_test/', 63 | persistent_files=True, ) 64 | 65 | # perform actual optimization 66 | value, parameters = opt.minimize(pysmac_merged_pcs_wrapper, 67 | #wrapper function generated by merge_configuration_spaces 68 | 50, # number of function evaluations 69 | p, # parameter defintion 70 | conditional_clauses = c, 71 | forbidden_clauses = f) 72 | 73 | print('The highest accuracy found: %f'%(-value)) 74 | print('Parameter setting %s'%parameters) 75 | 76 | 77 | # For very complex configuration spaces, looking at the final values might be hard. 78 | # You can use a function defined in 'wrapper_str' that finds the right callable and 79 | # the corresponding arguments (with their original name). That way, it is more 80 | # human readable. 81 | 82 | func, kwargs = pysmac_merged_pcs_reduce_args(**parameters) 83 | print("The best result was found calling '{}' with the arguments {}".format(func.__name__, kwargs)) 84 | 85 | 86 | 87 | -------------------------------------------------------------------------------- /examples/rosenbrock_example.py: -------------------------------------------------------------------------------- 1 | from __future__ import division, print_function 2 | 3 | import pysmac 4 | 5 | def rosenbrock_4d (x1,x2,x3,x4): 6 | """ The 4 dimensional Rosenbrock function as a toy model 7 | 8 | The Rosenbrock function is well know in the optimization community and 9 | often serves as a toy problem. It can be defined for arbitrary 10 | dimensions. The minimium is always at x_i = 1 with a function value of 11 | zero. All input parameters are continuous, but we will pretent that 12 | x2, x3, and x4 can only take integral values. The search domain for 13 | all x's is the interval [-5, 5]. 14 | """ 15 | 16 | val=( 100*(x2-x1**2)**2 + (x1-1)**2 + 17 | 100*(x3-x2**2)**2 + (x2-1)**2 + 18 | 100*(x4-x3**2)**2 + (x3-1)**2) 19 | return(val) 20 | 21 | 22 | parameters=dict(\ 23 | # x1 is a continuous ('real') parameter between -5 and 5. 24 | # The default value/initial guess is 5. 25 | x1=('real', [-5, 5], 5), 26 | 27 | # x2 can take only integral values, but range and initial 28 | # guess are identical to x1. 29 | x2=('integer', [-5, 5], 5), 30 | 31 | # x3 is encoded as a categorical parameter. Variables of 32 | # this type can only take values from a finite set. 33 | # The actual values can be numeric or strings. 34 | x3=('categorical',[5, 2, 0, 1, -1, -2, 4, -3, 3, -5, -4], 5), 35 | 36 | 37 | # x3 is defined as a so called ordinal parameter. This type 38 | # is similar to 'categorical', but additionally there exists 39 | # an ordering among the elements. 40 | x4=('ordinal', [-5,-4,-3,-2,-1,0,1,2,3,4,5] , 5), 41 | 42 | 43 | ) 44 | # Note: the definition of x3 and x4 is only to demonstrate the different 45 | # types of variables pysmac supports. Here these definitions are overly 46 | # complicated for this toy model. For example, the definitions of x2 and 47 | # x3 are equivalent, but the purpose of this example is not to show a 48 | # realistic use case 49 | 50 | 51 | # The next step is to create a SMAC_optimizer object 52 | opt = pysmac.SMAC_optimizer() 53 | 54 | # Then, call its minimize method with (at least) the three mandatory parameters 55 | value, parameters = opt.minimize( 56 | rosenbrock_4d, # the function to be minimized 57 | 1000, # the number of function calls allowed 58 | parameters) # the parameter dictionary 59 | 60 | 61 | # the return value is a tuple of the lowest function value and a dictionary 62 | # containing corresponding parameter setting. 63 | print(('Lowest function value found: %f'%value)) 64 | print(('Parameter setting %s'%parameters)) 65 | -------------------------------------------------------------------------------- /examples/sklearn_example.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function, division 2 | 3 | import pysmac 4 | 5 | import sklearn.ensemble 6 | import sklearn.datasets 7 | import sklearn.cross_validation 8 | 9 | # First, let us generate some random classification problem. Note that, due to the 10 | # way pysmac implements parallelism, the data is either a global variable, or 11 | # the function loads it itself. Please refere to the python manual about the 12 | # multiprocessing module for limitations. In the future, we might include additional 13 | # parameters to the function, but for now that is not possible. 14 | X,Y = sklearn.datasets.make_classification(1000, 20, random_state=2) # seed yields a mediocre initial accuracy on my machine 15 | X_train, X_test, Y_train, Y_test = sklearn.cross_validation.train_test_split(X,Y, test_size=0.33, random_state=1) 16 | 17 | # The function to be minimezed for this example is the mean accuracy of a random 18 | # forest on the test data set. Note: because SMAC minimizes the objective, we return 19 | # the negative accuracy in order to maximize it. 20 | def random_forest(n_estimators,criterion, max_features, max_depth): 21 | 22 | predictor = sklearn.ensemble.RandomForestClassifier(n_estimators, criterion, max_features, max_depth) 23 | predictor.fit(X_train, Y_train) 24 | 25 | return -predictor.score(X_test, Y_test) 26 | 27 | parameter_definition=dict(\ 28 | max_depth =("integer", [1,10], 4), 29 | max_features=("integer", [1,20], 10), 30 | n_estimators=("integer", [10,100], 10, 'log'), 31 | criterion =("categorical", ['gini', 'entropy'], 'entropy'), 32 | ) 33 | 34 | # a litle bit of explanation: the first two lines define integer parameters 35 | # ranging from 1 to 10/20 with some default values. The third line also defines 36 | # a integer parameter, but the additional 'log' string tells SMAC to vary it 37 | # uniformly on a logarithmic scale. Here it means, that 1<=n_estimators<=10 is 38 | # as likely as 10 and <. 55 | ) 56 | 57 | # here we define the dependencies between the parameters. the notation is 58 | # | in { , ... } 59 | # and means that the child parameter is only active if the parent parameter 60 | # takes one of the value in the listed set. The notation follows the SMAC 61 | # manual one to one. Note there is no checking for correctness beyond 62 | # what SMAC does. I.e., when you have a typo in here, you don't get any 63 | # meaningful output, unless you set debug = True below! 64 | conditionals = [ 'trees_max_depth | classifier in {random_forest, extra_trees}', 65 | 'trees_max_features | classifier in {random_forest} || classifier == extra_trees', 66 | 'trees_n_estimators | classifier != k_nearest_neighbors', 67 | 'trees_criterion | classifier < k_nearest_neighbors', 68 | 'knn_n_neighbors | classifier > extra_trees', 69 | 'knn_weights | classifier == k_nearest_neighbors && classifier != extra_trees && classifier != random_forest' 70 | ] 71 | 72 | # creation of the SMAC_optimizer object. Notice the optional debug flag 73 | opt = pysmac.SMAC_optimizer( debug = 0, 74 | working_directory = '/tmp/pysmac_test/', persistent_files=True, ) 75 | 76 | # first we try the sklearn default, so we can see if SMAC can improve the performance 77 | 78 | predictor = sklearn.ensemble.RandomForestClassifier() 79 | predictor.fit(X_train, Y_train) 80 | print('The default accuracy of the random forest is %f'%predictor.score(X_test, Y_test)) 81 | 82 | predictor = sklearn.ensemble.ExtraTreesClassifier() 83 | predictor.fit(X_train, Y_train) 84 | print('The default accuracy of the extremely randomized trees is %f'%predictor.score(X_test, Y_test)) 85 | 86 | predictor = sklearn.neighbors.KNeighborsClassifier() 87 | predictor.fit(X_train, Y_train) 88 | print('The default accuracy of k-nearest-neighbors is %f'%predictor.score(X_test, Y_test)) 89 | 90 | 91 | # The minimize method also has optional arguments (more on that in the section on advanced configuration). 92 | value, parameters = opt.minimize(choose_classifier, 93 | 500 , parameter_definition, 94 | conditional_clauses = conditionals) 95 | 96 | print('The highest accuracy found: %f'%(-value)) 97 | print('Parameter setting %s'%parameters) 98 | -------------------------------------------------------------------------------- /pysmac/__init__.py: -------------------------------------------------------------------------------- 1 | from .optimizer import * 2 | from .utils import * 3 | -------------------------------------------------------------------------------- /pysmac/analyzer.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function, division, absolute_import 2 | 3 | import os 4 | import glob 5 | import six 6 | import re 7 | 8 | 9 | import numpy as np 10 | try: 11 | import matplotlib.pyplot as plt 12 | except ImportError: 13 | raise ImportError('pySMAC was not installed with analyzer support.') 14 | 15 | import sys 16 | sys.path.append('/home/sfalkner/repositories/github/pysmac/') 17 | 18 | 19 | import pysmac.remote_smac 20 | import pysmac.utils.smac_output_readers as smac_readers 21 | 22 | 23 | class SMAC_analyzer(object): 24 | 25 | # collects smac specific data that goes into the scenario file 26 | def __init__(self, obj): 27 | 28 | if isinstance(obj,pysmac.remote_smac.remote_smac): 29 | self.scenario_fn = os.path.join(obj.working_directory, 'scenario.dat') 30 | self.scenario_fn = str(obj) 31 | 32 | # if it is a string, it can be a directory or a file 33 | if isinstance(obj, six.string_types): 34 | if os.path.isfile(obj): 35 | self.scenario_fn=obj 36 | else: 37 | self.scenario_fn=os.path.join(obj, 'scenario.dat') 38 | 39 | self.validation = False 40 | self.overall_objective = "MEAN" 41 | 42 | # parse scenario file for important information 43 | with open(self.scenario_fn,'r') as fh: 44 | for line in fh.readlines(): 45 | strlist = line.split() 46 | 47 | if strlist[0] in {'output-dir', 'outputDirectory', 'outdir'}: 48 | self.output_dir = strlist[1] 49 | 50 | if strlist[0] in {'pcs-file'}: 51 | self.pcs_fn = strlist[1] 52 | 53 | if strlist[0] == 'validation': 54 | self.validation = bool(strlist[1]) 55 | 56 | if strlist[0] in {'intra-obj', 'intra-instance-obj', 'overall-obj', 'intraInstanceObj', 'overallObj', 'overall_obj','intra_instance_obj'}: 57 | self.overall_objective = strlist[1] 58 | 59 | if strlist[0] in {'algo-cutoff-time','target-run-cputime-limit', 'target_run_cputime_limit', 'cutoff-time', 'cutoffTime', 'cutoff_time'}: 60 | self.cutoff_time = float(strlist[1]) 61 | 62 | # find the number of runs 63 | self.scenario_output_dir = (os.path.join(self.output_dir, 64 | os.path.basename(''.join(self.scenario_fn.split('.')[:-1])))) 65 | 66 | tmp = glob.glob( os.path.join(self.scenario_output_dir, "traj-run-*.txt")) 67 | 68 | # create the data dict for every run index 69 | self.data = {} 70 | for fullname in tmp: 71 | filename = (os.path.basename(fullname)) 72 | run_id = re.match("traj-run-(\d*).txt",filename).group(1) 73 | self.data[int(run_id)]={} 74 | 75 | # for now, we only load the incumbents for each run 76 | 77 | for i in list(self.data.keys()): 78 | try: 79 | # with test instances, the validation runs are loaded 80 | if self.validation: 81 | configs = smac_readers.read_validationCallStrings_file( 82 | os.path.join(self.scenario_output_dir, 83 | "validationCallStrings-traj-run-{}-walltime.csv".format(i))) 84 | test_performances = smac_readers.read_validationObjectiveMatrix_file( 85 | os.path.join(self.scenario_output_dir, 86 | "validationObjectiveMatrix-traj-run-{}-walltime.csv".format(i))) 87 | 88 | # without validation, there are only trajectory files to pase 89 | else: 90 | raise NotImplemented("The handling of cases without validation runs is not yet implemented") 91 | self.data[i]['parameters'] = configs 92 | self.data[i]['test_performances'] = test_performances 93 | except: 94 | print("Failed to load data for run {}. Please make sure it has finished properly.\nDropping it for now.".format(i)) 95 | self.data.pop(i) 96 | 97 | def get_pyfanova_obj(self, improvement_over='DEFAULT', check_scenario_files = True, heap_size=8192): 98 | try: 99 | import pyfanova.fanova 100 | 101 | self.merged_dir = os.path.join(self.output_dir,"merged_run") 102 | 103 | # delete existing merged run folder 104 | if os.path.exists(self.merged_dir): 105 | import shutil 106 | shutil.rmtree(self.merged_dir) 107 | 108 | from pysmac.utils.state_merge import state_merge 109 | 110 | print(os.path.join(self.scenario_output_dir, 'state-run*')) 111 | print(glob.glob(os.path.join(self.scenario_output_dir, 'state-run*'))) 112 | 113 | state_merge(glob.glob(os.path.join(self.scenario_output_dir, 'state-run*')), 114 | self.merged_dir, check_scenario_files = check_scenario_files) 115 | 116 | 117 | return(pyfanova.fanova.Fanova(self.merged_dir, improvement_over=improvement_over,heap_size=heap_size)) 118 | 119 | except ImportError: 120 | raise 121 | raise NotImplementedError('To use this feature, please install the pyfanova package.') 122 | except: 123 | print('Something went during the initialization of the FANOVA.') 124 | raise 125 | 126 | def get_item_all_runs(self, func = lambda d: d['function value']): 127 | return ([list(map(func, run[1:])) for run in self.data_all_runs]) 128 | 129 | def get_item_single_run(self, run_id, func = lambda d: d['function value']): 130 | return list(map(func,self.data_all_runs[run_id][1:])) 131 | 132 | def plot_run_performance(self, runs = None): 133 | 134 | plot = interactive_plot() 135 | 136 | for i in range(len(self.data_all_runs)): 137 | y = self.get_item_single_run(i) 138 | x = list(range(len(y))) 139 | plot.scatter(self.data_all_runs[i][0], x,y, self.get_item_single_run(i, func = lambda d: '\n'.join(['%s=%s'%(k,v) for (k,v) in list(d['parameter settings'].items()) ]) ), color = self.cm[i]) 140 | 141 | plot.add_datacursor() 142 | plot.show() 143 | 144 | 145 | def plot_run_incumbent(self, runs = None): 146 | plot = interactive_plot() 147 | 148 | for i in range(len(self.data_all_runs)): 149 | y = np.minimum.accumulate(self.get_item_single_run(i)) 150 | #x = 151 | _ , indices = np.unique(y, return_index = True) 152 | print(indices) 153 | 154 | indices = np.append(indices[::-1], len(y)-1) 155 | print(indices) 156 | x = np.arange(len(y))[indices] 157 | y = y[indices] 158 | 159 | print(x,y) 160 | print('='*40) 161 | plot.step(self.data_all_runs[i][0], x, y, color = self.cm[i]) 162 | 163 | plot.add_datacursor(formatter = 'iteration {x:.0f}: {y}'.format) 164 | plot.show() 165 | 166 | 167 | def basic_analysis (self): 168 | 169 | fig, ax = plt.subplots() 170 | 171 | ax.set_title('function value vs. number of iterations') 172 | ax.set_xlabel('iteration') 173 | ax.set_ylabel('function value') 174 | 175 | for i in range(len(self.trajectory)): 176 | color='red' if i == self.incumbent_index else 'blue' 177 | ax.scatter( i, self.trajectory[i][0], color=color, label = '\n'.join(['%s = %s' % (k,v) for (k, v) in list(self.trajectory[i][2].items())])) 178 | 179 | datacursor( 180 | bbox=dict(alpha=1), 181 | formatter = 'iteration {x:.0f}: {y}\n{label}'.format, 182 | hover=False, 183 | display='multiple', 184 | draggable=True, 185 | horizontalalignment='center', 186 | hide_button = 3) 187 | 188 | fig, ax = plt.subplots() 189 | incumbents = np.minimum.accumulate(list(map(itemgetter(0), self.trajectory))) 190 | ax.step(list(range(len(incumbents))), incumbents) 191 | 192 | plt.show() 193 | -------------------------------------------------------------------------------- /pysmac/optimizer.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function, division, absolute_import 2 | 3 | import sys 4 | import tempfile 5 | import os 6 | import shutil 7 | import errno 8 | import operator 9 | import multiprocessing 10 | import logging 11 | import csv 12 | 13 | from .utils.smac_output_readers import read_trajectory_file 14 | import pysmac.remote_smac 15 | from .utils.multiprocessing_wrapper import MyPool 16 | from pysmac.utils.java_helper import check_java_version, smac_classpath 17 | 18 | 19 | class SMAC_optimizer(object): 20 | """ 21 | The main class of pysmac instanciated by the user. 22 | 23 | This is the class a user instanciates to use SMAC. Constructing the 24 | object does not start the minimization immediately. The user has to 25 | call the method minimize for the actual optimization. This design 26 | choice enables easy enough usage for novice users, but allows experts 27 | to change many of SMAC's parameters by editing the 'smac_options' dict 28 | """ 29 | 30 | 31 | smac_options = {} 32 | """ A dict associated with the optimizer object that controlls options 33 | mainly for SMAC 34 | """ 35 | 36 | 37 | 38 | # collects smac specific data that go into the scenario file 39 | def __init__(self, t_limit_total_s=None, mem_limit_smac_mb=None, working_directory = None, persistent_files=False, debug = False): 40 | """ 41 | 42 | :param t_limit_total_s: the total time budget (in seconds) for the optimization. None means that no wall clock time constraint is enforced. 43 | :type t_limit_total_s: float 44 | :param mem_limit_smac_mb: memory limit for the Java Runtime Environment in which SMAC will be executed. None means system default. 45 | :type mem_limit_smac_mb: int 46 | :param working_directory: directory where SMACs output files are stored. None means a temporary directory will be created via the tempfile module. 47 | :type working_directory: str 48 | :param persistent_files: whether or note these files persist beyond the runtime of the optimization. 49 | :type persistent_files: bool 50 | :param debug: set this to true for debug information (pysmac and SMAC itself) logged to standard-out. 51 | :type debug: bool 52 | """ 53 | 54 | self.__logger = multiprocessing.log_to_stderr() 55 | if debug: 56 | self.__logger.setLevel(debug) 57 | else: 58 | self.__logger.setLevel(logging.WARNING) 59 | 60 | self.__t_limit_total_s = 0 if t_limit_total_s is None else int(t_limit_total_s) 61 | self.__mem_limit_smac_mb = None if (mem_limit_smac_mb is None) else int(mem_limit_smac_mb) 62 | 63 | self.__persistent_files = persistent_files 64 | 65 | # some basic consistency checks 66 | 67 | if (self.__t_limit_total_s < 0): 68 | raise ValueError('The total time limit cannot be nagative!') 69 | if (( self.__mem_limit_smac_mb is not None) and (self.__mem_limit_smac_mb <= 0)): 70 | raise ValueError('SMAC\'s memory limit has to be either None (no limit) or positive!') 71 | 72 | 73 | # create a temporary directory if none is specified 74 | if working_directory is None: 75 | self.working_directory = tempfile.mkdtemp() 76 | else: 77 | self.working_directory = working_directory 78 | 79 | self.__logger.debug('Writing output into: %s'%self.working_directory) 80 | 81 | # make some subdirs for output and smac internals 82 | self.__exec_dir = os.path.join(self.working_directory, 'exec') 83 | self.__out_dir = os.path.join(self.working_directory, 'out' ) 84 | 85 | for directory in [self.working_directory, self.__exec_dir, self.__out_dir]: 86 | try: 87 | os.makedirs(directory) 88 | except OSError as exception: 89 | if exception.errno != errno.EEXIST: 90 | raise 91 | 92 | 93 | # Set some of smac options 94 | # Most fields contain the standard values (as of SMAC 2.08.00). 95 | # All options from the smac manual can be accessed by 96 | # adding an entry to the dictionary with the appropriate name. 97 | # Some options will however have, at best, no effect, setting 98 | # others may even brake the communication. 99 | self.smac_options = { 100 | 'algo-exec': 'echo 0', 101 | 'run-obj': 'QUALITY', 102 | 'validation': False, 103 | 'cutoff_time': 3600, 104 | 'intensification-percentage': 0.5, 105 | 'numPCA': 7, 106 | 'rf-full-tree-bootstrap': False, 107 | 'rf-ignore-conditionality':False, 108 | 'rf-num-trees': 10, 109 | 'skip-features': True, 110 | 'pcs-file': os.path.join(self.working_directory,'parameters.pcs'), 111 | 'instances': os.path.join(self.working_directory ,'instances.dat'), 112 | 'algo-exec-dir': self.working_directory, 113 | 'output-dir': self.__out_dir, 114 | 'console-log-level': 'OFF', 115 | 'abort-on-first-run-crash': False, 116 | 'overall_obj': 'MEAN', 117 | 'scenario_fn': 'scenario.dat', # NOT a SMAC OPTION, but allows to 118 | # change the standard name (used 119 | # in Spysmac) 120 | 'java_executable': 'java', # NOT a SMAC OPTION; allows to 121 | # specify a different java 122 | # binary and can be abused to 123 | # pass additional arguments to it 124 | 'timeout_quality':2.**127, # not a SMAC option either 125 | # custamize the quality reported 126 | # to SMAC in case of a timeout 127 | } 128 | if debug: 129 | self.smac_options['console-log-level']='INFO' 130 | 131 | def __del__(self): 132 | """ 133 | Destructor cleaning up after SMAC finishes depending on the persistent_files flag. 134 | """ 135 | if not self.__persistent_files: 136 | shutil.rmtree(self.working_directory) 137 | 138 | def minimize(self, func, max_evaluations, parameter_dict, 139 | conditional_clauses = [], forbidden_clauses=[], 140 | deterministic = True, 141 | num_train_instances = None, num_test_instances = None, 142 | train_instance_features = None, 143 | num_runs = 1, num_procs = 1, seed = 0, 144 | mem_limit_function_mb=None, t_limit_function_s= None): 145 | """ 146 | Function invoked to perform the actual minimization given all necessary information. 147 | 148 | :param func: the function to be called 149 | :type func: callable 150 | :param max_evaluations: number of function calls allowed during the optimization (does not include optional validation). 151 | :type max_evaluations: int 152 | :param parameter_dict: parameter configuration space definition, see :doc:`pcs`. 153 | :type parameter_dict: dict 154 | :param conditional_clauses: list of conditional dependencies between parameters, see :doc:`pcs`. 155 | :type parameter_dict: list 156 | :param forbidden_clauses: list of forbidden parameter configurations, see :doc:`pcs`. 157 | :type parameter_dict: list 158 | :param deterministic: whether the function to be minimized contains random components, see :ref:`non-deterministic`. 159 | :type deterministic: bool 160 | :param num_train_instances: number of instances used during the configuration/optimization, see :ref:`training_instances`. 161 | :type num_train_instances: int 162 | :param num_test_instances: number of instances used for testing/validation, see :ref:`validation`. 163 | :type num_test_instances: int 164 | :param num_runs: number of independent SMAC runs. 165 | :type num_runs: int 166 | :param num_procs: number SMAC runs that can be executed in paralell 167 | :type num_procs: int 168 | :param seed: seed for SMAC's Random Number generator. If int, it is used for the first run, additional runs use consecutive numbers. If list, it specifies a seed for every run. 169 | :type seed: int/list of ints 170 | :param mem_limit_function_mb: sets the memory limit for your function (value in MB). ``None`` means no restriction. Be aware that this limit is enforced for each SMAC run separately. So if you have 2 parallel runs, pysmac could use twice that value (and twice the value of mem_limit_smac_mb) in total. Note that due to the creation of the subprocess, the amount of memory available to your function is less than the value specified here. This option exists mainly to prevent a memory usage of 100% which will at least slow the system down. 171 | :type mem_limit_function_mb: int 172 | :param t_limit_function_s: cutoff time for a single function call. ``None`` means no restriction. If optimizing run time, SMAC can choose a shorter cutoff than the provided one for individual runs. If `None` was provided, then there is no cutoff ever! 173 | """ 174 | 175 | self.smac_options['algo-deterministic'] = deterministic 176 | 177 | # adjust the number of training instances 178 | num_train_instances = None if (num_train_instances is None) else int(num_train_instances) 179 | 180 | if (num_train_instances is not None): 181 | if (num_train_instances < 1): 182 | raise ValueError('The number of training instances must be positive!') 183 | # check if instance features are provided 184 | if (train_instance_features is not None): 185 | # make sure it's the right number of instances 186 | if (len(train_instance_features) != num_train_instances): 187 | raise ValueError("You have to provide features for every training instance!") 188 | # and the same number of features 189 | nf = len(train_instance_features[0]) 190 | for feature_vector in train_instance_features: 191 | if (len(feature_vector) != nf): 192 | raise ValueError("You have to specify the same number of features for every instance!") 193 | self.smac_options['feature_file'] = os.path.join(self.working_directory ,'features.dat') 194 | 195 | 196 | 197 | num_procs = int(num_procs) 198 | pcs_string, parser_dict = pysmac.remote_smac.process_parameter_definitions(parameter_dict) 199 | 200 | # adjust the seed variable 201 | if isinstance(seed, int): 202 | seed = list(range(seed, seed+num_runs)) 203 | elif isinstance(seed, list) or isinstance(seed, tuple): 204 | if len(seed) != num_runs: 205 | raise ValueError("You have to specify a seed for every run!") 206 | else: 207 | raise ValueError("The seed variable could not be properly processed!") 208 | 209 | 210 | self.smac_options['runcount-limit'] = max_evaluations 211 | if t_limit_function_s is not None: 212 | self.smac_options['cutoff_time'] = t_limit_function_s 213 | 214 | 215 | # create and fill the pcs file 216 | with open(self.smac_options['pcs-file'], 'w') as fh: 217 | fh.write("\n".join(pcs_string + conditional_clauses + forbidden_clauses)) 218 | 219 | #create and fill the instance files 220 | tmp_num_instances = 1 if num_train_instances is None else num_train_instances 221 | with open(self.smac_options['instances'], 'w') as fh: 222 | for i in range(tmp_num_instances): 223 | fh.write("id_%i\n"%i) 224 | 225 | # create and fill the feature file 226 | if (train_instance_features is not None): 227 | with open(self.smac_options['feature_file'], 'w') as fh: 228 | #write a header 229 | tmp = ['instance_name'] + list(map(lambda i: 'feature{}'.format(i), range(len(train_instance_features[0])))) 230 | fh.write(",".join(tmp)); 231 | fh.write("\n"); 232 | 233 | # and then the actual features 234 | for i in range(len(train_instance_features)): 235 | tmp = ['id_{}'.format(i)] + ["{}".format(f) for f in train_instance_features[i]] 236 | fh.write(",".join(tmp)) 237 | fh.write("\n"); 238 | 239 | 240 | if num_test_instances is not None: 241 | # TODO: honor the users values for validation if set, and maybe show a warning on stdout 242 | self.smac_options['validate-only-last-incumbent'] = True 243 | self.smac_options['validation'] = True 244 | self.smac_options['test-instances'] = os.path.join(self.working_directory, 'test_instances.dat') 245 | with open(self.smac_options['test-instances'],'w') as fh: 246 | for i in range(tmp_num_instances, tmp_num_instances + num_test_instances): 247 | fh.write("id_%i\n"%i) 248 | 249 | # make sure the java executable is callable and up-to-date 250 | java_executable = self.smac_options.pop('java_executable') 251 | check_java_version(java_executable) 252 | 253 | timeout_quality = self.smac_options.pop('timeout_quality') 254 | 255 | 256 | # create and fill the scenario file 257 | scenario_fn = os.path.join(self.working_directory,self.smac_options.pop('scenario_fn')) 258 | 259 | 260 | scenario_options = {'algo', 'algo-exec', 'algoExec', 261 | 'algo-exec-dir', 'exec-dir', 'execDir','execdir', 262 | 'deterministic', 'algo-deterministic', 263 | 'paramfile', 'paramFile', 'pcs-file', 'param-file', 264 | 'run-obj', 'run-objective', 'runObj', 'run_obj', 265 | 'intra-obj', 'intra-instance-obj', 'overall-obj', 'intraInstanceObj', 'overallObj', 'overall_obj', 'intra_instance_obj', 266 | 'algo-cutoff-time', 'target-run-cputime-limit', 'target_run_cputime_limit', 'cutoff-time', 'cutoffTime', 'cutoff_time', 267 | 'cputime-limit', 'cputime_limit', 'tunertime-limit', 'tuner-timeout', 'tunerTimeout', 268 | 'wallclock-limit', 'wallclock_limit', 'runtime-limit', 'runtimeLimit', 'wallClockLimit', 269 | 'output-dir', 'outputDirectory', 'outdir', 270 | 'instances', 'instance-file', 'instance-dir', 'instanceFile', 'i', 'instance_file', 'instance_seed_file', 271 | 'test-instances', 'test-instance-file', 'test-instance-dir', 'testInstanceFile', 'test_instance_file', 'test_instance_seed_file', 272 | 'feature-file', 'instanceFeatureFile', 'feature_file' 273 | } 274 | 275 | additional_options_fn =scenario_fn[:-4]+'.advanced' 276 | with open(scenario_fn,'w') as fh, open(additional_options_fn, 'w') as fg: 277 | for name, value in list(self.smac_options.items()): 278 | if name in scenario_options: 279 | fh.write('%s %s\n'%(name, value)) 280 | else: 281 | fg.write('%s %s\n'%(name,value)) 282 | 283 | # check that all files are actually present, so SMAC has everything to start 284 | assert all(map(os.path.exists, [additional_options_fn, scenario_fn, self.smac_options['pcs-file'], self.smac_options['instances']])), "Something went wrong creating files for SMAC! Try to specify a \'working_directory\' and set \'persistent_files=True\'." 285 | 286 | # create a pool of workers and make'em work 287 | pool = MyPool(num_procs) 288 | argument_lists = [[scenario_fn, additional_options_fn, s, func, parser_dict, self.__mem_limit_smac_mb, smac_classpath(), num_train_instances, mem_limit_function_mb, t_limit_function_s, self.smac_options['algo-deterministic'], java_executable, timeout_quality] for s in seed] 289 | 290 | pool.map(pysmac.remote_smac.remote_smac_function, argument_lists) 291 | 292 | pool.close() 293 | pool.join() 294 | 295 | # find overall incumbent and return it 296 | 297 | scenario_dir = os.path.join(self.__out_dir,'.'.join(scenario_fn.split('/')[-1].split('.')[:-1])) 298 | 299 | run_incumbents = [] 300 | 301 | for s in seed: 302 | fn = os.path.join(scenario_dir, 'traj-run-%i.txt'%s) 303 | run_incumbents.append(read_trajectory_file(fn)[-1]) 304 | 305 | run_incumbents.sort(key = operator.itemgetter("Estimated Training Performance")) 306 | 307 | param_dict = run_incumbents[0]['Configuration'] 308 | 309 | for k in param_dict: 310 | param_dict[k] = parser_dict[k](param_dict[k]) 311 | 312 | return( run_incumbents[0]["Estimated Training Performance"], param_dict) 313 | -------------------------------------------------------------------------------- /pysmac/remote_smac.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function, division, absolute_import 2 | 3 | import sys 4 | import os 5 | import traceback 6 | import socket 7 | import subprocess 8 | import resource 9 | from pkg_resources import resource_filename 10 | from math import ceil 11 | import errno 12 | 13 | import logging 14 | import multiprocessing 15 | 16 | import time 17 | 18 | import pynisher 19 | 20 | 21 | 22 | 23 | SMAC_VERSION = "smac-v2.10.03-master-778" 24 | 25 | try: 26 | str=unicode #Python 2 backward compatibility 27 | except NameError: 28 | pass #Python 3 case 29 | 30 | 31 | 32 | # takes a name and a tuple defining one parameter, registers that with the parser 33 | # and returns the corresponding string for the SMAC pcs file and the type of the 34 | # variable for later casting 35 | def process_single_parameter_definition(name, specification): 36 | """ 37 | A helper function to process a single parameter definition for further communication with SMAC. 38 | """ 39 | 40 | data_type_mapping = {'integer': int, 'real': float} 41 | 42 | assert isinstance(specification, tuple), "The specification \"{}\" for {} is not valid".format(specification,name) 43 | assert len(specification)>1, "The specification \"{}\" for {} is too short".format(specification,name) 44 | 45 | if specification[0] not in {'real', 'integer', 'ordinal', 'categorical'}: 46 | raise ValueError("Type {} for {} not understood".format(specification[0], name)) 47 | 48 | string = '{} {}'.format(name, specification[0]) 49 | 50 | # numerical values 51 | if specification[0] in {'real', 'integer'}: 52 | dtype = data_type_mapping[specification[0]] 53 | if len(specification[1])!= 2: 54 | raise ValueError("Range {} for {} not valid for numerical parameter".format(specification[1], name)) 55 | if specification[1][0] >= specification[1][1]: 56 | raise ValueError("Interval {} not not understood.".format(specification[1])) 57 | if not (specification[1][0] <= specification[2] and specification[2] <= specification[1][1]): 58 | raise ValueError("Default value for {} has to be in the specified range".format(name)) 59 | 60 | if specification[0] == 'integer': 61 | if (type(specification[1][0]) != int) or (type(specification[1][1]) != int) or (type(specification[2]) != int): 62 | raise ValueError("Bounds and default value of integer parameter {} have to be integer types!".format(name)) 63 | 64 | string += " [{0[0]}, {0[1]}] [{1}]".format(specification[1], specification[2]) 65 | 66 | if ((len(specification) == 4) and specification[3] == 'log'): 67 | if specification[1][0] <= 0: 68 | raise ValueError("Range for {} cannot contain non-positive numbers.".format(name)) 69 | string += " log" 70 | 71 | # ordinal and categorical types 72 | if (specification[0] in {'ordinal', 'categorical'}): 73 | 74 | if specification[2] not in specification[1]: 75 | raise ValueError("Default value {} for {} is not valid.".format(specification[2], name)) 76 | 77 | # make sure all elements are of the same type 78 | if (len(set(map(type, specification[1]))) > 1): 79 | raise ValueError("Not all values of {} are of the same type!".format(name)) 80 | 81 | dtype = type(specification[1][0]) 82 | string += " {"+",".join(map(str, specification[1])) + '}' + ('[{}]'.format(specification[2])) 83 | 84 | return string, dtype 85 | 86 | 87 | def process_parameter_definitions(parameter_dict): 88 | """ 89 | A helper function to process all parameter definitions conviniently with just one call. 90 | 91 | This function takes the parametr definitions from the user, converts 92 | them into lines for SMAC's PCS format, and also creates a dictionary 93 | later used in the comunication with the SMAC process. 94 | 95 | :param paramer_dict: The user defined parameter configuration space 96 | 97 | """ 98 | pcs_strings = [] 99 | parser_dict={} 100 | 101 | for k,v in list(parameter_dict.items()): 102 | line, dtype = process_single_parameter_definition(k,v) 103 | parser_dict[k] = dtype 104 | pcs_strings.append(line) 105 | 106 | return (pcs_strings, parser_dict) 107 | 108 | 109 | 110 | class remote_smac(object): 111 | """ 112 | The class responsible for the TCP/IP communication with a SMAC instance. 113 | """ 114 | 115 | udp_timeout=5 116 | """ 117 | The default value for a timeout for the socket 118 | """ 119 | 120 | def __init__(self, scenario_fn, additional_options_fn, seed, class_path, memory_limit, parser_dict, java_executable): 121 | """ 122 | Starts SMAC in IPC mode. SMAC will wait for udp messages to be sent. 123 | """ 124 | self.__parser = parser_dict 125 | self.__subprocess = None 126 | self.__logger = multiprocessing.get_logger() 127 | 128 | # establish a socket 129 | self.__sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 130 | self.__sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) 131 | self.__sock.settimeout(3) 132 | self.__sock.bind(('', 0)) 133 | self.__sock.listen(1) 134 | 135 | self.__port = self.__sock.getsockname()[1] 136 | self.__logger.debug('picked port %i'%self.__port) 137 | 138 | # build the java command 139 | cmds = java_executable.split() 140 | if memory_limit is not None: 141 | cmds += ["-Xmx%im"%memory_limit] 142 | cmds += ["-XX:ParallelGCThreads=4", 143 | "-cp", 144 | class_path, 145 | "ca.ubc.cs.beta.smac.executors.SMACExecutor", 146 | "--scenario-file", scenario_fn, 147 | "--tae", "IPC", 148 | "--ipc-mechanism", "TCP", 149 | "--ipc-remote-port", str(self.__port), 150 | "--seed", str(seed) 151 | ] 152 | 153 | with open(additional_options_fn, 'r') as fh: 154 | for line in fh: 155 | name, value = line.strip().split(' ') 156 | cmds += ['--%s'%name, '%s'%value] 157 | 158 | self.__logger.debug("SMAC command: %s"%(' '.join(cmds))) 159 | 160 | self.__logger.debug("Starting SMAC in ICP mode") 161 | 162 | # connect the output to the logger if the appropriate level has been set 163 | if self.__logger.level < logging.WARNING: 164 | self.__subprocess = subprocess.Popen(cmds, stdout =sys.stdout, stderr = sys.stderr) 165 | else: 166 | with open(os.devnull, "w") as fnull: 167 | self.__subprocess = subprocess.Popen(cmds, stdout = fnull, stderr = fnull) 168 | 169 | def __del__(self): 170 | """ Destructor makes sure that the SMAC process is terminated if necessary. """ 171 | # shut the subprocess down on 'destruction' 172 | if not (self.__subprocess is None): 173 | self.__subprocess.poll() 174 | if self.__subprocess.returncode == None: 175 | self.__subprocess.kill() 176 | self.__logger.debug('SMAC had to be terminated') 177 | else: 178 | self.__logger.debug('SMAC terminated with returncode %i', self.__subprocess.returncode) 179 | 180 | 181 | def next_configuration(self): 182 | """ Method that queries the next configuration from SMAC. 183 | 184 | Connects to the socket, reads the message from SMAC, and 185 | converts into a proper Python representation (using the proper 186 | types). It also checks whether the SMAC subprocess is still alive. 187 | 188 | :returns: either a dictionary with a configuration, or None if SMAC has terminated 189 | """ 190 | 191 | self.__logger.debug('trying to retrieve the next configuration from SMAC') 192 | self.__sock.settimeout(self.udp_timeout) 193 | 194 | while True: 195 | try: 196 | self.__conn, addr = self.__sock.accept() 197 | fconn = self.__conn.makefile('r') 198 | config_str = fconn.readline() 199 | break 200 | except socket.timeout: 201 | # if smac already terminated, there is nothing else to do 202 | if self.__subprocess.poll() is not None: 203 | self.__logger.debug("SMAC subprocess is no longer alive!") 204 | return None 205 | #otherwise there is funny buisiness going on! 206 | else: 207 | self.__logger.debug("SMAC has not responded yet, but is still alive. Will keep waiting!") 208 | continue 209 | except socket.error as e: 210 | # continue 211 | if e.args[0] == errno.EAGAIN: 212 | self.__logger.debug("Socket to SMAC process was empty, will continue to wait.") 213 | time.sleep(1) 214 | continue 215 | else: 216 | raise 217 | except: 218 | raise 219 | 220 | self.__logger.debug("SMAC message: %s"%config_str) 221 | 222 | los = config_str.replace('\'','').split() # name is shorthand for 'list of strings' 223 | config_dict={} 224 | 225 | config_dict['instance'] = int(los[0][3:]) 226 | config_dict['instance_info'] = str(los[1]) 227 | config_dict['cutoff_time'] = float(los[2]) 228 | config_dict['cutoff_length'] = float(los[3]) 229 | config_dict['seed'] = int(los[4]) 230 | 231 | 232 | for i in range(5, len(los), 2): 233 | config_dict[ los[i][1:] ] = self.__parser[ los[i][1:] ]( los[i+1]) 234 | 235 | self.__logger.debug("Our interpretation: %s"%config_dict) 236 | return (config_dict) 237 | 238 | def report_result(self, result_dict): 239 | """Method to report the latest run results back to SMAC. 240 | 241 | This method communicates the results from the last run back to SMAC. 242 | 243 | :param result_dict: dictionary with the keys 'value', 'status', and 'runtime'. 244 | :type result_dic: dict 245 | """ 246 | 247 | # for propper printing, we have to convert the status into unicode 248 | result_dict['status'] = result_dict['status'].decode() 249 | s = 'Result for SMAC: {0[status]}, {0[runtime]}, 0, {0[value]}, 0\ 250 | '.format(result_dict) 251 | self.__logger.debug(s) 252 | self.__conn.sendall(s.encode()) 253 | self.__conn.close(); 254 | 255 | 256 | 257 | def remote_smac_function(only_arg): 258 | """ 259 | The function that every worker from the multiprocessing pool calls 260 | to perform a separate SMAC run. 261 | 262 | This function is not part of the API that users should access, but 263 | rather part of the internals of pysmac. Due to the limitations of the 264 | multiprocessing module, it can only take one argument which is a 265 | list containing important arguments in a very specific order. Check 266 | the source code if you want to learn more. 267 | 268 | """ 269 | try: 270 | scenario_file, additional_options_fn, seed, function, parser_dict,\ 271 | memory_limit_smac_mb, class_path, num_instances, mem_limit_function,\ 272 | t_limit_function, deterministic, java_executable, timeout_quality = only_arg 273 | 274 | logger = multiprocessing.get_logger() 275 | 276 | smac = remote_smac(scenario_file, additional_options_fn, seed, 277 | class_path, memory_limit_smac_mb,parser_dict, java_executable) 278 | 279 | logger.debug('Started SMAC subprocess') 280 | 281 | num_iterations = 0 282 | 283 | while True: 284 | config_dict = smac.next_configuration() 285 | 286 | # method next_configuration checks whether smac is still alive 287 | # if it is None, it means that SMAC has finished (for whatever reason) 288 | if config_dict is None: 289 | break 290 | 291 | # delete the unused variables from the dict 292 | if num_instances is None: 293 | del config_dict['instance'] 294 | 295 | del config_dict['instance_info'] 296 | del config_dict['cutoff_length'] 297 | if deterministic: 298 | del config_dict['seed'] 299 | 300 | current_t_limit = int(ceil(config_dict.pop('cutoff_time'))) 301 | # only restrict the runtime if an initial cutoff was defined 302 | current_t_limit = None if t_limit_function is None else current_t_limit 303 | current_wall_time_limit = None if current_t_limit is None else 10*current_t_limit 304 | 305 | # execute the function and measure the time it takes to evaluate 306 | wrapped_function = pynisher.enforce_limits( 307 | mem_in_mb=mem_limit_function, 308 | cpu_time_in_s=current_t_limit, 309 | wall_time_in_s=current_wall_time_limit, 310 | grace_period_in_s = 1)(function) 311 | 312 | # workaround for the 'Resource temporarily not available' error on 313 | # the BaWue cluster if to many processes were spawned in a short 314 | # period. It now waits a second and tries again for 8 times. 315 | num_try = 1 316 | while num_try <= 8: 317 | try: 318 | start = time.time() 319 | res = wrapped_function(**config_dict) 320 | wall_time = time.time()-start 321 | cpu_time = resource.getrusage(resource.RUSAGE_CHILDREN).ru_utime 322 | break 323 | except OSError as e: 324 | if e.errno == 11: 325 | logger.warning('Resource temporarily not available. Trail {} of 8'.format(num_try)) 326 | time.sleep(1) 327 | else: 328 | raise 329 | except: 330 | raise 331 | finally: 332 | num_try += 1 333 | if num_try == 9: 334 | logger.warning('Configuration {} crashed 8 times, giving up on it.'.format(config_dict)) 335 | res = None 336 | 337 | if res is not None: 338 | try: 339 | logger.debug('iteration %i:function value %s, computed in %s seconds'%(num_iterations, str(res), str(res['runtime']))) 340 | except (TypeError, AttributeError, KeyError, IndexError): 341 | logger.debug('iteration %i:function value %s, computed in %s seconds'%(num_iterations, str(res),cpu_time)) 342 | except: 343 | raise 344 | else: 345 | logger.debug('iteration %i: did not return in time, so it probably timed out'%(num_iterations)) 346 | 347 | 348 | # try to infere the status of the function call: 349 | # if res['status'] exsists, it will be used in 'report_result' 350 | # if there was no return value, it has either crashed or timed out 351 | # for simple function, we just use 'SAT' 352 | 353 | result_dict = { 354 | 'value' : timeout_quality, 355 | 'status': b'CRASHED' if res is None else b'SAT', 356 | 'runtime': cpu_time 357 | } 358 | 359 | if res is not None: 360 | if isinstance(res, dict): 361 | result_dict.update(res) 362 | else: 363 | result_dict['value'] = res 364 | 365 | # account for timeeouts 366 | if not current_t_limit is None: 367 | if ( (result_dict['runtime'] > current_t_limit-2e-2) or 368 | (wall_time >= 10*current_t_limit) ): 369 | result_dict['status']=b'TIMEOUT' 370 | 371 | # set returned quality to default in case of a timeout 372 | if result_dict['status'] == b'TIMEOUT': 373 | result_dict['value'] = result_dict['value'] if timeout_quality is None else timeout_quality 374 | 375 | smac.report_result(result_dict) 376 | num_iterations += 1 377 | except: 378 | traceback.print_exc() # to see the traceback of subprocesses 379 | -------------------------------------------------------------------------------- /pysmac/smac/smac-v2.10.03-master-778/lib/DomainInter.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sfalkner/pySMAC/a8720a011cae970dcfb48cc10de92cf2e61f2e63/pysmac/smac/smac-v2.10.03-master-778/lib/DomainInter.jar -------------------------------------------------------------------------------- /pysmac/smac/smac-v2.10.03-master-778/lib/Jama-1.0.2.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sfalkner/pySMAC/a8720a011cae970dcfb48cc10de92cf2e61f2e63/pysmac/smac/smac-v2.10.03-master-778/lib/Jama-1.0.2.jar -------------------------------------------------------------------------------- /pysmac/smac/smac-v2.10.03-master-778/lib/aeatk-src.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sfalkner/pySMAC/a8720a011cae970dcfb48cc10de92cf2e61f2e63/pysmac/smac/smac-v2.10.03-master-778/lib/aeatk-src.jar -------------------------------------------------------------------------------- /pysmac/smac/smac-v2.10.03-master-778/lib/aeatk.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sfalkner/pySMAC/a8720a011cae970dcfb48cc10de92cf2e61f2e63/pysmac/smac/smac-v2.10.03-master-778/lib/aeatk.jar -------------------------------------------------------------------------------- /pysmac/smac/smac-v2.10.03-master-778/lib/commons-collections-3.2.1-sources.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sfalkner/pySMAC/a8720a011cae970dcfb48cc10de92cf2e61f2e63/pysmac/smac/smac-v2.10.03-master-778/lib/commons-collections-3.2.1-sources.jar -------------------------------------------------------------------------------- /pysmac/smac/smac-v2.10.03-master-778/lib/commons-collections-3.2.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sfalkner/pySMAC/a8720a011cae970dcfb48cc10de92cf2e61f2e63/pysmac/smac/smac-v2.10.03-master-778/lib/commons-collections-3.2.1.jar -------------------------------------------------------------------------------- /pysmac/smac/smac-v2.10.03-master-778/lib/commons-io-2.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sfalkner/pySMAC/a8720a011cae970dcfb48cc10de92cf2e61f2e63/pysmac/smac/smac-v2.10.03-master-778/lib/commons-io-2.1.jar -------------------------------------------------------------------------------- /pysmac/smac/smac-v2.10.03-master-778/lib/commons-math-2.2.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sfalkner/pySMAC/a8720a011cae970dcfb48cc10de92cf2e61f2e63/pysmac/smac/smac-v2.10.03-master-778/lib/commons-math-2.2.jar -------------------------------------------------------------------------------- /pysmac/smac/smac-v2.10.03-master-778/lib/commons-math3-3.3.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sfalkner/pySMAC/a8720a011cae970dcfb48cc10de92cf2e61f2e63/pysmac/smac/smac-v2.10.03-master-778/lib/commons-math3-3.3.jar -------------------------------------------------------------------------------- /pysmac/smac/smac-v2.10.03-master-778/lib/exp4j-0.3.10.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sfalkner/pySMAC/a8720a011cae970dcfb48cc10de92cf2e61f2e63/pysmac/smac/smac-v2.10.03-master-778/lib/exp4j-0.3.10.jar -------------------------------------------------------------------------------- /pysmac/smac/smac-v2.10.03-master-778/lib/exp4j-0.4.3.BETA-3.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sfalkner/pySMAC/a8720a011cae970dcfb48cc10de92cf2e61f2e63/pysmac/smac/smac-v2.10.03-master-778/lib/exp4j-0.4.3.BETA-3.jar -------------------------------------------------------------------------------- /pysmac/smac/smac-v2.10.03-master-778/lib/fastrf-src.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sfalkner/pySMAC/a8720a011cae970dcfb48cc10de92cf2e61f2e63/pysmac/smac/smac-v2.10.03-master-778/lib/fastrf-src.jar -------------------------------------------------------------------------------- /pysmac/smac/smac-v2.10.03-master-778/lib/fastrf.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sfalkner/pySMAC/a8720a011cae970dcfb48cc10de92cf2e61f2e63/pysmac/smac/smac-v2.10.03-master-778/lib/fastrf.jar -------------------------------------------------------------------------------- /pysmac/smac/smac-v2.10.03-master-778/lib/guava-14.0.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sfalkner/pySMAC/a8720a011cae970dcfb48cc10de92cf2e61f2e63/pysmac/smac/smac-v2.10.03-master-778/lib/guava-14.0.1.jar -------------------------------------------------------------------------------- /pysmac/smac/smac-v2.10.03-master-778/lib/jackson-annotations-2.3.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sfalkner/pySMAC/a8720a011cae970dcfb48cc10de92cf2e61f2e63/pysmac/smac/smac-v2.10.03-master-778/lib/jackson-annotations-2.3.1.jar -------------------------------------------------------------------------------- /pysmac/smac/smac-v2.10.03-master-778/lib/jackson-core-2.3.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sfalkner/pySMAC/a8720a011cae970dcfb48cc10de92cf2e61f2e63/pysmac/smac/smac-v2.10.03-master-778/lib/jackson-core-2.3.1.jar -------------------------------------------------------------------------------- /pysmac/smac/smac-v2.10.03-master-778/lib/jackson-databind-2.3.1.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sfalkner/pySMAC/a8720a011cae970dcfb48cc10de92cf2e61f2e63/pysmac/smac/smac-v2.10.03-master-778/lib/jackson-databind-2.3.1.jar -------------------------------------------------------------------------------- /pysmac/smac/smac-v2.10.03-master-778/lib/jcip-annotations-src.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sfalkner/pySMAC/a8720a011cae970dcfb48cc10de92cf2e61f2e63/pysmac/smac/smac-v2.10.03-master-778/lib/jcip-annotations-src.jar -------------------------------------------------------------------------------- /pysmac/smac/smac-v2.10.03-master-778/lib/jcip-annotations.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sfalkner/pySMAC/a8720a011cae970dcfb48cc10de92cf2e61f2e63/pysmac/smac/smac-v2.10.03-master-778/lib/jcip-annotations.jar -------------------------------------------------------------------------------- /pysmac/smac/smac-v2.10.03-master-778/lib/jcommander.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sfalkner/pySMAC/a8720a011cae970dcfb48cc10de92cf2e61f2e63/pysmac/smac/smac-v2.10.03-master-778/lib/jcommander.jar -------------------------------------------------------------------------------- /pysmac/smac/smac-v2.10.03-master-778/lib/jmatharray.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sfalkner/pySMAC/a8720a011cae970dcfb48cc10de92cf2e61f2e63/pysmac/smac/smac-v2.10.03-master-778/lib/jmatharray.jar -------------------------------------------------------------------------------- /pysmac/smac/smac-v2.10.03-master-778/lib/logback-access-1.1.2.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sfalkner/pySMAC/a8720a011cae970dcfb48cc10de92cf2e61f2e63/pysmac/smac/smac-v2.10.03-master-778/lib/logback-access-1.1.2.jar -------------------------------------------------------------------------------- /pysmac/smac/smac-v2.10.03-master-778/lib/logback-classic-1.1.2.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sfalkner/pySMAC/a8720a011cae970dcfb48cc10de92cf2e61f2e63/pysmac/smac/smac-v2.10.03-master-778/lib/logback-classic-1.1.2.jar -------------------------------------------------------------------------------- /pysmac/smac/smac-v2.10.03-master-778/lib/logback-core-1.1.2.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sfalkner/pySMAC/a8720a011cae970dcfb48cc10de92cf2e61f2e63/pysmac/smac/smac-v2.10.03-master-778/lib/logback-core-1.1.2.jar -------------------------------------------------------------------------------- /pysmac/smac/smac-v2.10.03-master-778/lib/numerics4j-1.3.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sfalkner/pySMAC/a8720a011cae970dcfb48cc10de92cf2e61f2e63/pysmac/smac/smac-v2.10.03-master-778/lib/numerics4j-1.3.jar -------------------------------------------------------------------------------- /pysmac/smac/smac-v2.10.03-master-778/lib/opencsv-2.3.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sfalkner/pySMAC/a8720a011cae970dcfb48cc10de92cf2e61f2e63/pysmac/smac/smac-v2.10.03-master-778/lib/opencsv-2.3.jar -------------------------------------------------------------------------------- /pysmac/smac/smac-v2.10.03-master-778/lib/slf4j-api-1.7.5.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sfalkner/pySMAC/a8720a011cae970dcfb48cc10de92cf2e61f2e63/pysmac/smac/smac-v2.10.03-master-778/lib/slf4j-api-1.7.5.jar -------------------------------------------------------------------------------- /pysmac/smac/smac-v2.10.03-master-778/lib/smac-src.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sfalkner/pySMAC/a8720a011cae970dcfb48cc10de92cf2e61f2e63/pysmac/smac/smac-v2.10.03-master-778/lib/smac-src.jar -------------------------------------------------------------------------------- /pysmac/smac/smac-v2.10.03-master-778/lib/smac.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sfalkner/pySMAC/a8720a011cae970dcfb48cc10de92cf2e61f2e63/pysmac/smac/smac-v2.10.03-master-778/lib/smac.jar -------------------------------------------------------------------------------- /pysmac/smac/smac-v2.10.03-master-778/lib/spi-0.2.4.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sfalkner/pySMAC/a8720a011cae970dcfb48cc10de92cf2e61f2e63/pysmac/smac/smac-v2.10.03-master-778/lib/spi-0.2.4.jar -------------------------------------------------------------------------------- /pysmac/smac/smac-v2.10.03-master-778/smac: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | SMAC_MEMORY_INPUT=$SMAC_MEMORY 3 | SMACMEM=1024 4 | test "$SMAC_MEMORY_INPUT" -ge 1 2>&- && SMACMEM=$SMAC_MEMORY_INPUT 5 | EXEC=ca.ubc.cs.beta.smac.executors.SMACExecutor 6 | DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" 7 | if [ ! -d "$DIR/lib" ]; then 8 | DIR="$(dirname "$DIR")" 9 | fi 10 | LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$DIR/lib/native/:$DIR/lib/:$DIR/ 11 | DYLD_FALLBACK_LIBRARY_PATH=$DYLD_FALLBACK_LIBRARY_PATH:$DIR/lib/native/:$DIR/lib/:$DIR/ 12 | 13 | for f in $DIR/lib/*.jar 14 | do 15 | jarconcat=$jarconcat:$f 16 | done 17 | for f in $DIR/*.jar 18 | do 19 | jarconcat=$jarconcat:$f 20 | done 21 | jarconcat=${jarconcat:1} 22 | 23 | exec java -Xmx"$SMACMEM"m -cp "$DIR/conf/:$DIR/patches/:$jarconcat:$DIR/patches/" ca.ubc.cs.beta.aeatk.ant.execscript.Launcher $EXEC "$@" 24 | -------------------------------------------------------------------------------- /pysmac/smac/smac-v2.10.03-master-778/smac-validate: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | SMAC_MEMORY_INPUT=$SMAC_MEMORY 3 | SMACMEM=1024 4 | test "$SMAC_MEMORY_INPUT" -ge 1 2>&- && SMACMEM=$SMAC_MEMORY_INPUT 5 | EXEC=ca.ubc.cs.beta.smac.executors.ValidatorExecutor 6 | DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" 7 | if [ ! -d "$DIR/lib" ]; then 8 | DIR="$(dirname "$DIR")" 9 | fi 10 | LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$DIR/lib/native/:$DIR/lib/:$DIR/ 11 | DYLD_FALLBACK_LIBRARY_PATH=$DYLD_FALLBACK_LIBRARY_PATH:$DIR/lib/native/:$DIR/lib/:$DIR/ 12 | 13 | for f in $DIR/lib/*.jar 14 | do 15 | jarconcat=$jarconcat:$f 16 | done 17 | for f in $DIR/*.jar 18 | do 19 | jarconcat=$jarconcat:$f 20 | done 21 | jarconcat=${jarconcat:1} 22 | 23 | exec java -Xmx"$SMACMEM"m -cp "$DIR/conf/:$DIR/patches/:$jarconcat:$DIR/patches/" ca.ubc.cs.beta.aeatk.ant.execscript.Launcher $EXEC "$@" 24 | -------------------------------------------------------------------------------- /pysmac/smac/smac-v2.10.03-master-778/smac-validate.bat: -------------------------------------------------------------------------------- 1 | @echo off 2 | set SMACMEM=1024 3 | IF NOT "%SMAC_MEMORY%"=="" (set SMACMEM=%SMAC_MEMORY%) 4 | set DIR=%~dp0 5 | IF EXIST "%DIR%\lib\" GOTO USE_LIB 6 | set DIR=%DIR%\..\ 7 | :USE_LIB 8 | 9 | set EXEC=ca.ubc.cs.beta.smac.executors.ValidatorExecutor 10 | set jarconcat= 11 | SETLOCAL ENABLEDELAYEDEXPANSION 12 | for /F "delims=" %%a IN ('dir /b /s "%DIR%\*.jar"') do set jarconcat=%%a;!jarconcat! 13 | for /F "delims=" %%a IN ('dir /b /s "%DIR%\lib\*.jar"') do set jarconcat=%%a;!jarconcat! 14 | java -Xmx%SMACMEM%m -cp "%DIR%conf\;%DIR%patches\;%jarconcat%%DIR%patches\ " ca.ubc.cs.beta.aeatk.ant.execscript.Launcher %EXEC% %* 15 | -------------------------------------------------------------------------------- /pysmac/smac/smac-v2.10.03-master-778/smac.bat: -------------------------------------------------------------------------------- 1 | @echo off 2 | set SMACMEM=1024 3 | IF NOT "%SMAC_MEMORY%"=="" (set SMACMEM=%SMAC_MEMORY%) 4 | set DIR=%~dp0 5 | IF EXIST "%DIR%\lib\" GOTO USE_LIB 6 | set DIR=%DIR%\..\ 7 | :USE_LIB 8 | 9 | set EXEC=ca.ubc.cs.beta.smac.executors.SMACExecutor 10 | set jarconcat= 11 | SETLOCAL ENABLEDELAYEDEXPANSION 12 | for /F "delims=" %%a IN ('dir /b /s "%DIR%\*.jar"') do set jarconcat=%%a;!jarconcat! 13 | for /F "delims=" %%a IN ('dir /b /s "%DIR%\lib\*.jar"') do set jarconcat=%%a;!jarconcat! 14 | java -Xmx%SMACMEM%m -cp "%DIR%conf\;%DIR%patches\;%jarconcat%%DIR%patches\ " ca.ubc.cs.beta.aeatk.ant.execscript.Launcher %EXEC% %* 15 | -------------------------------------------------------------------------------- /pysmac/smac/smac-v2.10.03-master-778/util/algo-test: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | SMAC_MEMORY_INPUT=$SMAC_MEMORY 3 | SMACMEM=128 4 | test "$SMAC_MEMORY_INPUT" -ge 1 2>&- && SMACMEM=$SMAC_MEMORY_INPUT 5 | EXEC=ca.ubc.cs.beta.aeatk.example.tae.TargetAlgorithmEvaluatorRunner 6 | DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" 7 | if [ ! -d "$DIR/lib" ]; then 8 | DIR="$(dirname "$DIR")" 9 | fi 10 | LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$DIR/lib/native/:$DIR/lib/:$DIR/ 11 | DYLD_FALLBACK_LIBRARY_PATH=$DYLD_FALLBACK_LIBRARY_PATH:$DIR/lib/native/:$DIR/lib/:$DIR/ 12 | echo "Starting algo-test with $SMACMEM MB of RAM" 13 | 14 | for f in $DIR/lib/*.jar 15 | do 16 | jarconcat=$jarconcat:$f 17 | done 18 | for f in $DIR/*.jar 19 | do 20 | jarconcat=$jarconcat:$f 21 | done 22 | jarconcat=${jarconcat:1} 23 | 24 | exec java -Xmx"$SMACMEM"m -cp "$DIR/conf/:$DIR/patches/:$jarconcat:$DIR/patches/" ca.ubc.cs.beta.aeatk.ant.execscript.Launcher $EXEC "$@" 25 | -------------------------------------------------------------------------------- /pysmac/smac/smac-v2.10.03-master-778/util/algo-test.bat: -------------------------------------------------------------------------------- 1 | @echo off 2 | set SMACMEM=128 3 | IF NOT "%SMAC_MEMORY%"=="" (set SMACMEM=%SMAC_MEMORY%) 4 | set DIR=%~dp0 5 | IF EXIST "%DIR%\lib\" GOTO USE_LIB 6 | set DIR=%DIR%\..\ 7 | :USE_LIB 8 | 9 | set EXEC=ca.ubc.cs.beta.aeatk.example.tae.TargetAlgorithmEvaluatorRunner 10 | set jarconcat= 11 | SETLOCAL ENABLEDELAYEDEXPANSION 12 | for /F "delims=" %%a IN ('dir /b /s "%DIR%\*.jar"') do set jarconcat=%%a;!jarconcat! 13 | for /F "delims=" %%a IN ('dir /b /s "%DIR%\lib\*.jar"') do set jarconcat=%%a;!jarconcat! 14 | echo Starting algo-test with %SMACMEM% MB of RAM 15 | java -Xmx%SMACMEM%m -cp "%DIR%conf\;%DIR%patches\;%jarconcat%%DIR%patches\ " ca.ubc.cs.beta.aeatk.ant.execscript.Launcher %EXEC% %* 16 | -------------------------------------------------------------------------------- /pysmac/smac/smac-v2.10.03-master-778/util/ipc-client: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | SMAC_MEMORY_INPUT=$SMAC_MEMORY 3 | SMACMEM=1024 4 | test "$SMAC_MEMORY_INPUT" -ge 1 2>&- && SMACMEM=$SMAC_MEMORY_INPUT 5 | EXEC=ca.ubc.cs.beta.aeatk.targetalgorithmevaluator.base.ipc.reversetcpclient.IPCTAEClient 6 | DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" 7 | if [ ! -d "$DIR/lib" ]; then 8 | DIR="$(dirname "$DIR")" 9 | fi 10 | LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$DIR/lib/native/:$DIR/lib/:$DIR/ 11 | DYLD_FALLBACK_LIBRARY_PATH=$DYLD_FALLBACK_LIBRARY_PATH:$DIR/lib/native/:$DIR/lib/:$DIR/ 12 | echo "Starting ipc-client with $SMACMEM MB of RAM" 13 | 14 | for f in $DIR/lib/*.jar 15 | do 16 | jarconcat=$jarconcat:$f 17 | done 18 | for f in $DIR/*.jar 19 | do 20 | jarconcat=$jarconcat:$f 21 | done 22 | jarconcat=${jarconcat:1} 23 | 24 | exec java -Xmx"$SMACMEM"m -cp "$DIR/conf/:$DIR/patches/:$jarconcat:$DIR/patches/" ca.ubc.cs.beta.aeatk.ant.execscript.Launcher $EXEC "$@" 25 | -------------------------------------------------------------------------------- /pysmac/smac/smac-v2.10.03-master-778/util/ipc-client.bat: -------------------------------------------------------------------------------- 1 | @echo off 2 | set SMACMEM=1024 3 | IF NOT "%SMAC_MEMORY%"=="" (set SMACMEM=%SMAC_MEMORY%) 4 | set DIR=%~dp0 5 | IF EXIST "%DIR%\lib\" GOTO USE_LIB 6 | set DIR=%DIR%\..\ 7 | :USE_LIB 8 | 9 | set EXEC=ca.ubc.cs.beta.aeatk.targetalgorithmevaluator.base.ipc.reversetcpclient.IPCTAEClient 10 | set jarconcat= 11 | SETLOCAL ENABLEDELAYEDEXPANSION 12 | for /F "delims=" %%a IN ('dir /b /s "%DIR%\*.jar"') do set jarconcat=%%a;!jarconcat! 13 | for /F "delims=" %%a IN ('dir /b /s "%DIR%\lib\*.jar"') do set jarconcat=%%a;!jarconcat! 14 | echo Starting ipc-client with %SMACMEM% MB of RAM 15 | java -Xmx%SMACMEM%m -cp "%DIR%conf\;%DIR%patches\;%jarconcat%%DIR%patches\ " ca.ubc.cs.beta.aeatk.ant.execscript.Launcher %EXEC% %* 16 | -------------------------------------------------------------------------------- /pysmac/smac/smac-v2.10.03-master-778/util/json-executor: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | SMAC_MEMORY_INPUT=$SMAC_MEMORY 3 | SMACMEM=128 4 | test "$SMAC_MEMORY_INPUT" -ge 1 2>&- && SMACMEM=$SMAC_MEMORY_INPUT 5 | EXEC=ca.ubc.cs.beta.aeatk.example.jsonexecutor.JSONExecutor 6 | DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" 7 | if [ ! -d "$DIR/lib" ]; then 8 | DIR="$(dirname "$DIR")" 9 | fi 10 | LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$DIR/lib/native/:$DIR/lib/:$DIR/ 11 | DYLD_FALLBACK_LIBRARY_PATH=$DYLD_FALLBACK_LIBRARY_PATH:$DIR/lib/native/:$DIR/lib/:$DIR/ 12 | echo "Starting json-executor with $SMACMEM MB of RAM" 13 | 14 | for f in $DIR/lib/*.jar 15 | do 16 | jarconcat=$jarconcat:$f 17 | done 18 | for f in $DIR/*.jar 19 | do 20 | jarconcat=$jarconcat:$f 21 | done 22 | jarconcat=${jarconcat:1} 23 | 24 | exec java -Xmx"$SMACMEM"m -cp "$DIR/conf/:$DIR/patches/:$jarconcat:$DIR/patches/" ca.ubc.cs.beta.aeatk.ant.execscript.Launcher $EXEC "$@" 25 | -------------------------------------------------------------------------------- /pysmac/smac/smac-v2.10.03-master-778/util/json-executor.bat: -------------------------------------------------------------------------------- 1 | @echo off 2 | set SMACMEM=128 3 | IF NOT "%SMAC_MEMORY%"=="" (set SMACMEM=%SMAC_MEMORY%) 4 | set DIR=%~dp0 5 | IF EXIST "%DIR%\lib\" GOTO USE_LIB 6 | set DIR=%DIR%\..\ 7 | :USE_LIB 8 | 9 | set EXEC=ca.ubc.cs.beta.aeatk.example.jsonexecutor.JSONExecutor 10 | set jarconcat= 11 | SETLOCAL ENABLEDELAYEDEXPANSION 12 | for /F "delims=" %%a IN ('dir /b /s "%DIR%\*.jar"') do set jarconcat=%%a;!jarconcat! 13 | for /F "delims=" %%a IN ('dir /b /s "%DIR%\lib\*.jar"') do set jarconcat=%%a;!jarconcat! 14 | echo Starting json-executor with %SMACMEM% MB of RAM 15 | java -Xmx%SMACMEM%m -cp "%DIR%conf\;%DIR%patches\;%jarconcat%%DIR%patches\ " ca.ubc.cs.beta.aeatk.ant.execscript.Launcher %EXEC% %* 16 | -------------------------------------------------------------------------------- /pysmac/smac/smac-v2.10.03-master-778/util/pcs-check: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | SMAC_MEMORY_INPUT=$SMAC_MEMORY 3 | SMACMEM=128 4 | test "$SMAC_MEMORY_INPUT" -ge 1 2>&- && SMACMEM=$SMAC_MEMORY_INPUT 5 | EXEC=ca.ubc.cs.beta.aeatk.example.pcscheck.PCSCheckExecutor 6 | DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" 7 | if [ ! -d "$DIR/lib" ]; then 8 | DIR="$(dirname "$DIR")" 9 | fi 10 | LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$DIR/lib/native/:$DIR/lib/:$DIR/ 11 | DYLD_FALLBACK_LIBRARY_PATH=$DYLD_FALLBACK_LIBRARY_PATH:$DIR/lib/native/:$DIR/lib/:$DIR/ 12 | echo "Starting pcs-check with $SMACMEM MB of RAM" 13 | 14 | for f in $DIR/lib/*.jar 15 | do 16 | jarconcat=$jarconcat:$f 17 | done 18 | for f in $DIR/*.jar 19 | do 20 | jarconcat=$jarconcat:$f 21 | done 22 | jarconcat=${jarconcat:1} 23 | 24 | exec java -Xmx"$SMACMEM"m -cp "$DIR/conf/:$DIR/patches/:$jarconcat:$DIR/patches/" ca.ubc.cs.beta.aeatk.ant.execscript.Launcher $EXEC "$@" 25 | -------------------------------------------------------------------------------- /pysmac/smac/smac-v2.10.03-master-778/util/pcs-check.bat: -------------------------------------------------------------------------------- 1 | @echo off 2 | set SMACMEM=128 3 | IF NOT "%SMAC_MEMORY%"=="" (set SMACMEM=%SMAC_MEMORY%) 4 | set DIR=%~dp0 5 | IF EXIST "%DIR%\lib\" GOTO USE_LIB 6 | set DIR=%DIR%\..\ 7 | :USE_LIB 8 | 9 | set EXEC=ca.ubc.cs.beta.aeatk.example.pcscheck.PCSCheckExecutor 10 | set jarconcat= 11 | SETLOCAL ENABLEDELAYEDEXPANSION 12 | for /F "delims=" %%a IN ('dir /b /s "%DIR%\*.jar"') do set jarconcat=%%a;!jarconcat! 13 | for /F "delims=" %%a IN ('dir /b /s "%DIR%\lib\*.jar"') do set jarconcat=%%a;!jarconcat! 14 | echo Starting pcs-check with %SMACMEM% MB of RAM 15 | java -Xmx%SMACMEM%m -cp "%DIR%conf\;%DIR%patches\;%jarconcat%%DIR%patches\ " ca.ubc.cs.beta.aeatk.ant.execscript.Launcher %EXEC% %* 16 | -------------------------------------------------------------------------------- /pysmac/smac/smac-v2.10.03-master-778/util/sat-check: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | SMAC_MEMORY_INPUT=$SMAC_MEMORY 3 | SMACMEM=1024 4 | test "$SMAC_MEMORY_INPUT" -ge 1 2>&- && SMACMEM=$SMAC_MEMORY_INPUT 5 | EXEC=ca.ubc.cs.beta.aeatk.example.satisfiabilitychecker.SatisfiabilityChecker 6 | DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" 7 | if [ ! -d "$DIR/lib" ]; then 8 | DIR="$(dirname "$DIR")" 9 | fi 10 | LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$DIR/lib/native/:$DIR/lib/:$DIR/ 11 | DYLD_FALLBACK_LIBRARY_PATH=$DYLD_FALLBACK_LIBRARY_PATH:$DIR/lib/native/:$DIR/lib/:$DIR/ 12 | echo "Starting sat-check with $SMACMEM MB of RAM" 13 | 14 | for f in $DIR/lib/*.jar 15 | do 16 | jarconcat=$jarconcat:$f 17 | done 18 | for f in $DIR/*.jar 19 | do 20 | jarconcat=$jarconcat:$f 21 | done 22 | jarconcat=${jarconcat:1} 23 | 24 | exec java -Xmx"$SMACMEM"m -cp "$DIR/conf/:$DIR/patches/:$jarconcat:$DIR/patches/" ca.ubc.cs.beta.aeatk.ant.execscript.Launcher $EXEC "$@" 25 | -------------------------------------------------------------------------------- /pysmac/smac/smac-v2.10.03-master-778/util/sat-check.bat: -------------------------------------------------------------------------------- 1 | @echo off 2 | set SMACMEM=1024 3 | IF NOT "%SMAC_MEMORY%"=="" (set SMACMEM=%SMAC_MEMORY%) 4 | set DIR=%~dp0 5 | IF EXIST "%DIR%\lib\" GOTO USE_LIB 6 | set DIR=%DIR%\..\ 7 | :USE_LIB 8 | 9 | set EXEC=ca.ubc.cs.beta.aeatk.example.satisfiabilitychecker.SatisfiabilityChecker 10 | set jarconcat= 11 | SETLOCAL ENABLEDELAYEDEXPANSION 12 | for /F "delims=" %%a IN ('dir /b /s "%DIR%\*.jar"') do set jarconcat=%%a;!jarconcat! 13 | for /F "delims=" %%a IN ('dir /b /s "%DIR%\lib\*.jar"') do set jarconcat=%%a;!jarconcat! 14 | echo Starting sat-check with %SMACMEM% MB of RAM 15 | java -Xmx%SMACMEM%m -cp "%DIR%conf\;%DIR%patches\;%jarconcat%%DIR%patches\ " ca.ubc.cs.beta.aeatk.ant.execscript.Launcher %EXEC% %* 16 | -------------------------------------------------------------------------------- /pysmac/smac/smac-v2.10.03-master-778/util/state-merge: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | SMAC_MEMORY_INPUT=$SMAC_MEMORY 3 | SMACMEM=1024 4 | test "$SMAC_MEMORY_INPUT" -ge 1 2>&- && SMACMEM=$SMAC_MEMORY_INPUT 5 | EXEC=ca.ubc.cs.beta.aeatk.example.statemerge.StateMergeExecutor 6 | DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" 7 | if [ ! -d "$DIR/lib" ]; then 8 | DIR="$(dirname "$DIR")" 9 | fi 10 | LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$DIR/lib/native/:$DIR/lib/:$DIR/ 11 | DYLD_FALLBACK_LIBRARY_PATH=$DYLD_FALLBACK_LIBRARY_PATH:$DIR/lib/native/:$DIR/lib/:$DIR/ 12 | echo "Starting state-merge with $SMACMEM MB of RAM" 13 | 14 | for f in $DIR/lib/*.jar 15 | do 16 | jarconcat=$jarconcat:$f 17 | done 18 | for f in $DIR/*.jar 19 | do 20 | jarconcat=$jarconcat:$f 21 | done 22 | jarconcat=${jarconcat:1} 23 | 24 | exec java -Xmx"$SMACMEM"m -cp "$DIR/conf/:$DIR/patches/:$jarconcat:$DIR/patches/" ca.ubc.cs.beta.aeatk.ant.execscript.Launcher $EXEC "$@" 25 | -------------------------------------------------------------------------------- /pysmac/smac/smac-v2.10.03-master-778/util/state-merge.bat: -------------------------------------------------------------------------------- 1 | @echo off 2 | set SMACMEM=1024 3 | IF NOT "%SMAC_MEMORY%"=="" (set SMACMEM=%SMAC_MEMORY%) 4 | set DIR=%~dp0 5 | IF EXIST "%DIR%\lib\" GOTO USE_LIB 6 | set DIR=%DIR%\..\ 7 | :USE_LIB 8 | 9 | set EXEC=ca.ubc.cs.beta.aeatk.example.statemerge.StateMergeExecutor 10 | set jarconcat= 11 | SETLOCAL ENABLEDELAYEDEXPANSION 12 | for /F "delims=" %%a IN ('dir /b /s "%DIR%\*.jar"') do set jarconcat=%%a;!jarconcat! 13 | for /F "delims=" %%a IN ('dir /b /s "%DIR%\lib\*.jar"') do set jarconcat=%%a;!jarconcat! 14 | echo Starting state-merge with %SMACMEM% MB of RAM 15 | java -Xmx%SMACMEM%m -cp "%DIR%conf\;%DIR%patches\;%jarconcat%%DIR%patches\ " ca.ubc.cs.beta.aeatk.ant.execscript.Launcher %EXEC% %* 16 | -------------------------------------------------------------------------------- /pysmac/smac/smac-v2.10.03-master-778/util/tae-evaluator: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | SMAC_MEMORY_INPUT=$SMAC_MEMORY 3 | SMACMEM=1024 4 | test "$SMAC_MEMORY_INPUT" -ge 1 2>&- && SMACMEM=$SMAC_MEMORY_INPUT 5 | EXEC=ca.ubc.cs.beta.aeatk.example.evaluator.TAEEvaluator 6 | DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" 7 | if [ ! -d "$DIR/lib" ]; then 8 | DIR="$(dirname "$DIR")" 9 | fi 10 | LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$DIR/lib/native/:$DIR/lib/:$DIR/ 11 | DYLD_FALLBACK_LIBRARY_PATH=$DYLD_FALLBACK_LIBRARY_PATH:$DIR/lib/native/:$DIR/lib/:$DIR/ 12 | echo "Starting tae-evaluator with $SMACMEM MB of RAM" 13 | 14 | for f in $DIR/lib/*.jar 15 | do 16 | jarconcat=$jarconcat:$f 17 | done 18 | for f in $DIR/*.jar 19 | do 20 | jarconcat=$jarconcat:$f 21 | done 22 | jarconcat=${jarconcat:1} 23 | 24 | exec java -Xmx"$SMACMEM"m -cp "$DIR/conf/:$DIR/patches/:$jarconcat:$DIR/patches/" ca.ubc.cs.beta.aeatk.ant.execscript.Launcher $EXEC "$@" 25 | -------------------------------------------------------------------------------- /pysmac/smac/smac-v2.10.03-master-778/util/tae-evaluator.bat: -------------------------------------------------------------------------------- 1 | @echo off 2 | set SMACMEM=1024 3 | IF NOT "%SMAC_MEMORY%"=="" (set SMACMEM=%SMAC_MEMORY%) 4 | set DIR=%~dp0 5 | IF EXIST "%DIR%\lib\" GOTO USE_LIB 6 | set DIR=%DIR%\..\ 7 | :USE_LIB 8 | 9 | set EXEC=ca.ubc.cs.beta.aeatk.example.evaluator.TAEEvaluator 10 | set jarconcat= 11 | SETLOCAL ENABLEDELAYEDEXPANSION 12 | for /F "delims=" %%a IN ('dir /b /s "%DIR%\*.jar"') do set jarconcat=%%a;!jarconcat! 13 | for /F "delims=" %%a IN ('dir /b /s "%DIR%\lib\*.jar"') do set jarconcat=%%a;!jarconcat! 14 | echo Starting tae-evaluator with %SMACMEM% MB of RAM 15 | java -Xmx%SMACMEM%m -cp "%DIR%conf\;%DIR%patches\;%jarconcat%%DIR%patches\ " ca.ubc.cs.beta.aeatk.ant.execscript.Launcher %EXEC% %* 16 | -------------------------------------------------------------------------------- /pysmac/smac/smac-v2.10.03-master-778/util/verify-scenario: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | SMAC_MEMORY_INPUT=$SMAC_MEMORY 3 | SMACMEM=1024 4 | test "$SMAC_MEMORY_INPUT" -ge 1 2>&- && SMACMEM=$SMAC_MEMORY_INPUT 5 | EXEC=ca.ubc.cs.beta.aeatk.example.verifyscenario.VerifyScenarioExecutor 6 | DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" 7 | if [ ! -d "$DIR/lib" ]; then 8 | DIR="$(dirname "$DIR")" 9 | fi 10 | LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$DIR/lib/native/:$DIR/lib/:$DIR/ 11 | DYLD_FALLBACK_LIBRARY_PATH=$DYLD_FALLBACK_LIBRARY_PATH:$DIR/lib/native/:$DIR/lib/:$DIR/ 12 | echo "Starting verify-scenario with $SMACMEM MB of RAM" 13 | 14 | for f in $DIR/lib/*.jar 15 | do 16 | jarconcat=$jarconcat:$f 17 | done 18 | for f in $DIR/*.jar 19 | do 20 | jarconcat=$jarconcat:$f 21 | done 22 | jarconcat=${jarconcat:1} 23 | 24 | exec java -Xmx"$SMACMEM"m -cp "$DIR/conf/:$DIR/patches/:$jarconcat:$DIR/patches/" ca.ubc.cs.beta.aeatk.ant.execscript.Launcher $EXEC "$@" 25 | -------------------------------------------------------------------------------- /pysmac/smac/smac-v2.10.03-master-778/util/verify-scenario.bat: -------------------------------------------------------------------------------- 1 | @echo off 2 | set SMACMEM=1024 3 | IF NOT "%SMAC_MEMORY%"=="" (set SMACMEM=%SMAC_MEMORY%) 4 | set DIR=%~dp0 5 | IF EXIST "%DIR%\lib\" GOTO USE_LIB 6 | set DIR=%DIR%\..\ 7 | :USE_LIB 8 | 9 | set EXEC=ca.ubc.cs.beta.aeatk.example.verifyscenario.VerifyScenarioExecutor 10 | set jarconcat= 11 | SETLOCAL ENABLEDELAYEDEXPANSION 12 | for /F "delims=" %%a IN ('dir /b /s "%DIR%\*.jar"') do set jarconcat=%%a;!jarconcat! 13 | for /F "delims=" %%a IN ('dir /b /s "%DIR%\lib\*.jar"') do set jarconcat=%%a;!jarconcat! 14 | echo Starting verify-scenario with %SMACMEM% MB of RAM 15 | java -Xmx%SMACMEM%m -cp "%DIR%conf\;%DIR%patches\;%jarconcat%%DIR%patches\ " ca.ubc.cs.beta.aeatk.ant.execscript.Launcher %EXEC% %* 16 | -------------------------------------------------------------------------------- /pysmac/utils/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/sfalkner/pySMAC/a8720a011cae970dcfb48cc10de92cf2e61f2e63/pysmac/utils/__init__.py -------------------------------------------------------------------------------- /pysmac/utils/java_helper.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | import pysmac.remote_smac 4 | 5 | def check_java_version(java_executable="java"): 6 | """ 7 | Small function to ensure that Java (version >= 7) was found. 8 | 9 | As SMAC requires a Java Runtime Environment (JRE), pysmac checks that a 10 | adequate version (>7) has been found. It raises a RuntimeError 11 | exception if no JRE or an out-dated version was found. 12 | 13 | :param java_executable: callable Java binary. It is possible to pass additional options via this argument to the JRE, e.g. "java -Xmx128m" is a valid argument. 14 | :type java_executable: str 15 | :raises: RuntimeError 16 | """ 17 | import re 18 | from subprocess import STDOUT, check_output 19 | 20 | error_msg = "" 21 | error = False 22 | 23 | out = check_output(java_executable.split() + ["-version"], stderr=STDOUT).strip().split(b"\n") 24 | if len(out) < 1: 25 | error_msg = "Failed checking Java version. Make sure Java version 7 or greater is installed." 26 | error = True 27 | m = re.match(b'.*version "\d+.(\d+)..*', out[0]) 28 | if m is None or len(m.groups()) < 1: 29 | error_msg = ("Failed checking Java version. Make sure Java version 7 or greater is installed.") 30 | error = True 31 | else: 32 | java_version = int(m.group(1)) 33 | if java_version < 7: 34 | error_msg = "Found Java version %d, but Java version 7 or greater is required." % java_version 35 | error = True 36 | if error: 37 | raise RuntimeError(error_msg) 38 | 39 | 40 | def smac_classpath(): 41 | """ 42 | Small function gathering all information to build the java class path. 43 | 44 | :returns: string representing the Java classpath for SMAC 45 | 46 | """ 47 | import multiprocessing 48 | from pkg_resources import resource_filename 49 | 50 | logger = multiprocessing.get_logger() 51 | 52 | smac_folder = resource_filename("pysmac", 'smac/%s' % pysmac.remote_smac.SMAC_VERSION) 53 | 54 | smac_conf_folder = os.path.join(smac_folder, "conf") 55 | smac_patches_folder = os.path.join(smac_folder, "patches") 56 | smac_lib_folder = os.path.join(smac_folder, "lib") 57 | 58 | 59 | classpath = [fname for fname in os.listdir(smac_lib_folder) if fname.endswith(".jar")] 60 | classpath = [os.path.join(smac_lib_folder, fname) for fname in classpath] 61 | classpath = [os.path.abspath(fname) for fname in classpath] 62 | classpath.append(os.path.abspath(smac_conf_folder)) 63 | classpath.append(os.path.abspath(smac_patches_folder)) 64 | 65 | # For Windows compability 66 | classpath = (os.pathsep).join(classpath) 67 | 68 | logger.debug("SMAC classpath: %s", classpath) 69 | 70 | return classpath 71 | 72 | -------------------------------------------------------------------------------- /pysmac/utils/multiprocessing_wrapper.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: UTF-8 -*- 3 | 4 | import multiprocessing 5 | import multiprocessing.pool 6 | 7 | class NoDaemonProcess(multiprocessing.Process): 8 | """ 9 | A subclass to avoid the subprocesses used for the individual SMAC runs to be deamons. 10 | 11 | As it turns out, the Java processes running SMAC cannot be deamons. 12 | To change the default behavior of the multiprocessing module, one has 13 | to derive a subclass and overwrite the _get_deamon, _set_deamon methods 14 | appropriately. 15 | """ 16 | def _get_daemon(self): 17 | return False 18 | def _set_daemon(self, value): 19 | pass 20 | daemon = property(_get_daemon, _set_daemon) 21 | 22 | class MyPool(multiprocessing.pool.Pool): 23 | """Subclass to use the NoDeamonProcesses as workers in a Pool.""" 24 | Process = NoDaemonProcess 25 | -------------------------------------------------------------------------------- /pysmac/utils/pcs_merge.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | def merge_configuration_spaces(*args, **kwargs): 4 | """ 5 | Convenience function to merge several algorithms with their respective config spaces into a single one. 6 | 7 | Using pySMAC to optimize the parameters of a single function/algorithm 8 | is a very important usecase, but finding the best algorithm and its 9 | configuration across multiple choices. For example, when multiple different 10 | algorithms can be used to solve the same problem, and it is unclear 11 | which one will be the best choice. 12 | 13 | The arguments to this function is a number of tuples, each with the 14 | following content: (callable, pcs, conditionals, forbiddens). The 15 | callable is a valid python function in the current namespace. The 16 | Parameter Configuration Space (pcs) is the definition of its 17 | parameters, while conditionals and forbiddens express dependencies and 18 | restrictions within that space. 19 | 20 | :returns: the merged configuration space, a list of conditionals, a list of forbiddens, and a string that defines two functions (see :ref:`merge_pcs`). 21 | """ 22 | 23 | names = [] 24 | parameters = {} 25 | conditionals = [] 26 | forbiddens = [] 27 | 28 | # go through all the provided arguments 29 | for (callabl, params, conds, forbs) in args: 30 | # store callable's name 31 | name = callabl.__name__ 32 | names.append(name) 33 | 34 | # modify the parameter names 35 | for p in params: 36 | parameters[name + '_' + p] = params[p] 37 | 38 | # modify existing conditionals 39 | already_conditioned = set() 40 | for c in conds: 41 | c = c.strip(' ') 42 | already_conditioned.update( (c.split('|')[0].strip(' '),)) 43 | 44 | for p in params: 45 | c = (re.subn( p, name + '_' + p , c)[0]) 46 | 47 | conditionals.append( c.rstrip() + ' && algorithm == '+name) 48 | 49 | # add new conditionals 50 | for p in params: 51 | if p not in already_conditioned: 52 | conditionals.append(name + '_' + p + ' | algorithm == ' + name) 53 | 54 | for f in forbs: 55 | f = f.strip() 56 | for p in params: 57 | f = (re.subn( p, name + '_' + p , f)[0]) 58 | forbiddens.append(f) 59 | parameters['algorithm'] = ('categorical', names, names[0]) 60 | 61 | wrapper_str="""import re 62 | 63 | def pysmac_merged_pcs_reduce_args(algorithm=None, *args, **kwds): 64 | # create a set of algorithm names to filter out the inactive parameters 65 | names = %s"""%(names) + '\n\tcallables = [' + ",".join(names) + """] 66 | 67 | # remove unused arguments 68 | new_kwds = {} 69 | for p in kwds: 70 | is_algorithm_parameter = False 71 | for a in names: 72 | l = re.split(a+'_', p, maxsplit=1) 73 | if len(l) == 2: 74 | is_algorithm_parameter = True 75 | if a == algorithm: 76 | new_kwds[l[1]] = kwds[p] 77 | break 78 | if not is_algorithm_parameter: 79 | new_kwds[p] = kwds[p] 80 | 81 | i = names.index(algorithm) 82 | return((callables[i], new_kwds)) 83 | 84 | 85 | def pysmac_merged_pcs_wrapper(algorithm=None, *args, **kwds): 86 | 87 | call, args = pysmac_merged_pcs_reduce_args(algorithm = algorithm, *args, **kwds) 88 | 89 | return(call(**args))""" 90 | 91 | return(parameters, conditionals, forbiddens, wrapper_str) 92 | -------------------------------------------------------------------------------- /pysmac/utils/smac_input_readers.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | def read_pcs(filename): 4 | ''' Function to read a SMAC pcs file (format according to version 2.08). 5 | 6 | :param filename: name of the pcs file to be read 7 | :type filename: str 8 | :returns: tuple -- (parameters as a dict, conditionals as a list, forbiddens as a list) 9 | ''' 10 | 11 | num_regex = "[+\-]?(?:0|[1-9]\d*)(?:\.\d*)?(?:[eE][+\-]?\d+)?" 12 | FLOAT_REGEX = re.compile("^[ ]*(?P[^ ]+)[ ]*\[(?P%s)[ ]*,[ ]*(?P%s)\][ ]*\[(?P[^#]*)\](?P.*)$" %(num_regex,num_regex)) 13 | CAT_REGEX = re.compile("^[ ]*(?P[^ ]+)[ ]*{(?P.+)}[ ]*\[(?P[^#]*)\](?P.*)$") 14 | COND_REGEX = re.compile("^[ ]*(?P[^ ]+)[ ]*\|[ ]*(?P[^ ]+)[ ]*in[ ]*{(?P.+)}(?P.*)$") 15 | FORBIDDEN_REGEX = re.compile("^[ ]*{(?P.+)}(?P.*)$") 16 | 17 | param_dict = {} # name -> ([begin, end], default, flags) 18 | conditions = [] 19 | forbiddens = [] 20 | 21 | with open(filename) as fp: 22 | for line in fp: 23 | #remove line break and white spaces 24 | line = line.strip("\n").strip(" ") 25 | 26 | #remove comments 27 | if line.find("#") > -1: 28 | line = line[:line.find("#")] # remove comments 29 | 30 | # skip empty lines 31 | if line == "": 32 | continue 33 | 34 | # categorial parameter 35 | cat_match = CAT_REGEX.match(line) 36 | if cat_match: 37 | name = cat_match.group("name") 38 | values = set([x.strip(" ") for x in cat_match.group("values").split(",")]) 39 | default = cat_match.group("default") 40 | 41 | #logging.debug("CATEGORIAL: %s %s {%s} (%s)" %(name, default, ",".join(map(str, values)), type_)) 42 | param_dict[name] = (values, default) 43 | 44 | float_match = FLOAT_REGEX.match(line) 45 | if float_match: 46 | name = float_match.group("name") 47 | values = [float(float_match.group("range_start")), float(float_match.group("range_end"))] 48 | default = float(float_match.group("default")) 49 | 50 | #logging.debug("PARAMETER: %s %f [%s] (%s)" %(name, default, ",".join(map(str, values)), type_)) 51 | param_dict[name] = (values, default) 52 | if "i" in float_match.group("misc"): 53 | param_dict[name] += ('int',) 54 | if "l" in float_match.group("misc"): 55 | param_dict[name] += ('log',) 56 | 57 | cond_match = COND_REGEX.match(line) 58 | if cond_match: 59 | #logging.debug("CONDITIONAL: %s | %s in {%s}" %(cond, head, ",".join(values))) 60 | conditions.append(line) 61 | 62 | forbidden_match = FORBIDDEN_REGEX.match(line) 63 | if forbidden_match: 64 | #logging.debug("FORBIDDEN: {%s}" %(values)) 65 | forbiddens.append(line) 66 | 67 | return param_dict, conditions, forbiddens 68 | 69 | def write_pcs(pcs_filename, parameters, forbiddens, conditionals): 70 | ''' Function to write a SMAC PCS file''' 71 | with open(pcs_filename, 'w') as out: 72 | # Parameters 73 | out.write("# Parameters\n") 74 | for param, info in parameters.iteritems(): 75 | if param == 'algorithm': # Handle this specially because merge_configuration_spaces doesn't return a set 76 | values = set(info[1]) 77 | default = info[2] 78 | else: 79 | values = info[0] 80 | default = info[1] 81 | if isinstance(values, set): # Categorical 82 | line = "%(param)s {%(values)s} [%(default)s]" % dict(param=param, values=",".join(values), default=default) 83 | else: 84 | _type = '' if len(info) == 2 else info[2][0] 85 | if _type == 'i': 86 | values = map(int, info[0]) 87 | default = int(info[1]) 88 | line = "%(param)s %(values)s [%(default)s] %(_type)s" % dict(param=param, values=values, default=default, _type=_type) 89 | out.write(line +'\n') 90 | 91 | # Conditionals 92 | out.write("# Conditionals\n") 93 | for conditional in conditionals: 94 | out.write(conditional +'\n') 95 | 96 | out.write("# Forbidden\n") 97 | # Forbidden 98 | for forbidden in forbiddens: 99 | out.write(forbidden +'\n') 100 | 101 | def read_scenario_file(fn): 102 | """ Small helper function to read a SMAC scenario file. 103 | 104 | :returns : dict -- (key, value) pairs are (variable name, variable value) 105 | """ 106 | 107 | # translate the difference option names to a canonical name 108 | scenario_option_names = {'algo-exec' : 'algo', 109 | 'algoExec': 'algo', 110 | 'algo-exec-dir': 'execdir', 111 | 'exec-dir' : 'execdir', 112 | 'execDir' : 'execdir', 113 | 'algo-deterministic' : 'deterministic', 114 | 'paramFile' : 'paramfile', 115 | 'pcs-file' :'paramfile', 116 | 'param-file' : 'paramfile', 117 | 'run-obj' : 'run_obj', 118 | 'run-objective' : 'run_obj', 119 | 'runObj' : 'run_obj', 120 | 'overall_obj' : 'overall_obj', 121 | 'intra-obj' : 'overall_obj', 122 | 'intra-instance-obj' : 'overall_obj', 123 | 'overall-obj' : 'overall_obj', 124 | 'intraInstanceObj' : 'overall_obj', 125 | 'overallObj' : 'overall_obj', 126 | 'intra_instance_obj' : 'overall_obj', 127 | 'algo-cutoff-time' : 'cutoff_time', 128 | 'target-run-cputime-limit' : 'cutoff_time', 129 | 'target_run_cputime_limit' : 'cutoff_time', 130 | 'cutoff-time' : 'cutoff_time', 131 | 'cutoffTime' : 'cutoff_time', 132 | 'cputime-limit' : 'tunerTimeout', 133 | 'cputime_limit' : 'tunerTimeout', 134 | 'tunertime-limit' : 'tunerTimeout', 135 | 'tuner-timeout' : 'tunerTimeout', 136 | 'tunerTimeout' : 'tunerTimeout', 137 | 'wallclock_limit' : 'wallclock-limit', 138 | 'runtime-limit' : 'wallclock-limit', 139 | 'runtimeLimit' : 'wallclock-limit', 140 | 'wallClockLimit' : 'wallclock-limit', 141 | 'output-dir' : 'outdir', 142 | 'outputDirectory' : 'outdir', 143 | 'instances' : 'instance_file', 144 | 'instance-file' : 'instance_file' , 145 | 'instance-dir' : 'instance_file', 146 | 'instanceFile' : 'instance_file', 147 | 'i' : 'instance_file', 148 | 'instance_seed_file' : 'instance_file', 149 | 'test-instances' : 'test_instance_file', 150 | 'test-instance-file' : 'test_instance_file', 151 | 'test-instance-dir' : 'test_instance_file', 152 | 'testInstanceFile' : 'test_instance_file', 153 | 'test_instance_file' : 'test_instance_file', 154 | 'test_instance_seed_file' : 'test_instance_file', 155 | 'feature-file' : 'feature_file', 156 | 'instanceFeatureFile' : 'feature_file', 157 | 'feature_file' : 'feature_file' 158 | } 159 | 160 | scenario_dict = {} 161 | with open(fn, 'r') as fh: 162 | for line in fh.readlines(): 163 | #remove comments 164 | if line.find("#") > -1: 165 | line = line[:line.find("#")] 166 | 167 | # skip empty lines 168 | if line == "": 169 | continue 170 | if "=" in line: 171 | tmp = line.split("=") 172 | tmp = [' '.join(s.split()) for s in tmp] 173 | else: 174 | tmp = line.split() 175 | scenario_dict[scenario_option_names.get(tmp[0],tmp[0])] = " ".join(tmp[1:]) 176 | return(scenario_dict) 177 | -------------------------------------------------------------------------------- /pysmac/utils/smac_output_readers.py: -------------------------------------------------------------------------------- 1 | import json 2 | import functools 3 | import re 4 | import operator 5 | 6 | import numpy as np 7 | 8 | from pysmac.remote_smac import process_parameter_definitions 9 | 10 | 11 | def convert_param_dict_types(param_dict, pcs): 12 | _, parser_dict = process_parameter_definitions(pcs) 13 | for k in param_dict: 14 | param_dict[k] = parser_dict[k](param_dict[k]) 15 | return(param_dict) 16 | 17 | 18 | 19 | def json_parse(fileobj, decoder=json.JSONDecoder(), buffersize=2048): 20 | """ Small function to parse a file containing JSON objects separated by a new line. This format is used in the live-rundata-xx.json files produces by SMAC. 21 | 22 | taken from http://stackoverflow.com/questions/21708192/how-do-i-use-the-json-module-to-read-in-one-json-object-at-a-time/21709058#21709058 23 | """ 24 | buffer = '' 25 | for chunk in iter(functools.partial(fileobj.read, buffersize), ''): 26 | buffer += chunk 27 | buffer = buffer.strip(' \n') 28 | while buffer: 29 | try: 30 | result, index = decoder.raw_decode(buffer) 31 | yield result 32 | buffer = buffer[index:] 33 | except ValueError: 34 | # Not enough data to decode, read more 35 | break 36 | 37 | 38 | def read_runs_and_results_file(fn): 39 | """ Converting a runs_and_results file into a numpy array. 40 | 41 | Almost all entries in a runs_and_results file are numeric to begin with. 42 | Only the 14th column contains the status which is encoded as ints by SAT = 1, 43 | UNSAT = 0, TIMEOUT = -1, everything else = -2. 44 | \n 45 | +-------+----------------+ 46 | | Value | Representation | 47 | +=======+================+ 48 | |SAT | 2 | 49 | +-------+----------------+ 50 | |UNSAT | 1 | 51 | +-------+----------------+ 52 | |TIMEOUT| 0 | 53 | +-------+----------------+ 54 | |Others | -1 | 55 | +-------+----------------+ 56 | 57 | 58 | :returns: numpy_array(dtype = double) -- the data 59 | """ 60 | # to convert everything into floats, the run result needs to be mapped 61 | def map_run_result(res): 62 | if b'TIMEOUT' in res: return(0) 63 | if b'UNSAT' in res: return(1) # note UNSAT before SAT, b/c UNSAT contains SAT! 64 | if b'SAT' in res: return(2) 65 | return(-1) # covers ABORT, CRASHED, but that shouldn't happen 66 | 67 | return(np.loadtxt(fn, skiprows=1, delimiter=',', 68 | usecols = list(range(1,14))+[15], # skip empty 'algorithm run data' column 69 | converters={13:map_run_result}, ndmin=2)) 70 | 71 | 72 | def read_paramstrings_file(fn): 73 | """ Function to read a paramstring file. 74 | Every line in this file corresponds to a full configuration. Everything is 75 | stored as strings and without knowledge about the pcs, converting that into 76 | any other type would involve guessing, which we shall not do here. 77 | 78 | :param fn: the name of the paramstring file 79 | :type fn: str 80 | :returns: dict -- with key-value pairs 'parameter name'-'value as string' 81 | 82 | """ 83 | param_dict_list = [] 84 | with open(fn,'r') as fh: 85 | for line in fh.readlines(): 86 | # remove run id and single quotes 87 | line = line[line.find(':')+1:].replace("'","") 88 | pairs = [s.strip().split("=") for s in line.split(',')] 89 | param_dict_list.append({k:v for [k, v] in pairs}) 90 | return(param_dict_list) 91 | 92 | 93 | def read_validationCallStrings_file(fn): 94 | """Reads a validationCallString file into a list of dictionaries. 95 | 96 | :returns: list of dicts -- each dictionary contains 'parameter name' and 'parameter value as string' key-value pairs 97 | """ 98 | param_dict_list = [] 99 | with open(fn,'r') as fh: 100 | for line in fh.readlines()[1:]: # skip header line 101 | config_string = line.split(",")[1].strip('"') 102 | config_string = config_string.split(' ') 103 | tmp_dict = {} 104 | for i in range(0,len(config_string),2): 105 | tmp_dict[config_string[i].lstrip('-')] = config_string[i+1].strip("'") 106 | param_dict_list.append(tmp_dict) 107 | return(param_dict_list) 108 | 109 | 110 | def read_validationObjectiveMatrix_file(fn): 111 | """ reads the run data of a validation run performed by SMAC. 112 | 113 | For cases with instances, not necessarily every instance is used during the 114 | configuration phase to estimate a configuration's performance. If validation 115 | is enabled, SMAC reruns parameter settings (usually just the final incumbent) 116 | on the whole instance set/a designated test set. The data from those runs 117 | is stored in separate files. This function reads one of these files. 118 | 119 | :param fn: the name of the validationObjectiveMatrix file 120 | :type fn: str 121 | 122 | :returns: dict -- configuration ids as keys, list of performances on each instance as values. 123 | 124 | .. todo:: 125 | testing of validation runs where more than the final incumbent is validated 126 | """ 127 | values = {} 128 | 129 | with open(fn,'r') as fh: 130 | header = fh.readline().split(",") 131 | num_configs = len(header)-2 132 | re_string = '\w?,\w?'.join(['"id\_(\d*)"', '"(\d*)"'] + ['"([0-9.]*)"']*num_configs) 133 | for line in fh.readlines(): 134 | match = (re.match(re_string, line)) 135 | values[int(match.group(1))] = list(map(float,list(map(match.group, list(range(3,3+num_configs)))))) 136 | return(values) 137 | 138 | 139 | def read_trajectory_file(fn): 140 | """Reads a trajectory file and returns a list of dicts with all the information. 141 | 142 | Due to the way SMAC stores every parameter's value as a string, the configuration returned by this function also has every value stored as a string. All other values, like "Estimated Training Preformance" and so on are floats, though. 143 | 144 | :param fn: name of file to read 145 | :type fn: str 146 | 147 | :returns: list of dicts -- every dict contains the keys: "CPU Time Used","Estimated Training Performance","Wallclock Time","Incumbent ID","Automatic Configurator (CPU) Time","Configuration" 148 | """ 149 | return_list = [] 150 | 151 | with open(fn,'r') as fh: 152 | header = list(map(lambda s: s.strip('"'), fh.readline().split(","))) 153 | l_info = len(header)-1 154 | for line in fh.readlines(): 155 | tmp = line.split(",") 156 | tmp_dict = {} 157 | for i in range(l_info): 158 | tmp_dict[header[i]] = float(tmp[i]) 159 | tmp_dict['Configuration'] = {} 160 | for i in range(l_info, len(tmp)): 161 | name, value = tmp[i].strip().split("=") 162 | tmp_dict['Configuration'][name] = value.strip("'").strip('"') 163 | return_list.append(tmp_dict) 164 | return(return_list) 165 | 166 | def read_instances_file(fn): 167 | """Reads the instance names from an instace file 168 | 169 | :param fn: name of file to read 170 | :type fn: str 171 | :returns: list -- each element is a list where the first element is the instance name followed by additional information for the specific instance. 172 | """ 173 | with open(fn,'r') as fh: 174 | instance_names = fh.readlines() 175 | return([s.strip().split() for s in instance_names]) 176 | 177 | 178 | def read_instance_features_file(fn): 179 | """Function to read a instance_feature file. 180 | 181 | :returns: tuple -- first entry is a list of the feature names, second one is a dict with 'instance name' - 'numpy array containing the features' key-value pairs 182 | """ 183 | instances = {} 184 | with open(fn,'r') as fh: 185 | lines = fh.readlines() 186 | for line in lines[1:]: 187 | tmp = line.strip().split(",") 188 | instances[tmp[0]] = np.array(tmp[1:],dtype=np.double) 189 | return(lines[0].split(",")[1:], instances) 190 | -------------------------------------------------------------------------------- /pysmac/utils/state_merge.py: -------------------------------------------------------------------------------- 1 | import os 2 | import glob 3 | import operator 4 | import errno 5 | import filecmp 6 | import shutil 7 | import numpy 8 | 9 | 10 | from .smac_output_readers import * 11 | 12 | 13 | 14 | def find_largest_file (glob_pattern): 15 | """ Function to find the largest file matching a glob pattern. 16 | 17 | Old SMAC version keep several versions of files as back-ups. This 18 | helper can be used to find the largest file (which should contain the 19 | final output). One could also go for the most recent file, but that 20 | might fail when the data is copied. 21 | 22 | :param glob_pattern: a UNIX style pattern to apply 23 | :type glob_pattern: string 24 | 25 | :returns: string -- largest file matching the pattern 26 | """ 27 | fns = glob.glob(glob_pattern) 28 | 29 | if len(fns) == 0: 30 | raise RuntimeError("No file matching pattern \'{}\' found!".format(glob_pattern)) 31 | 32 | f_name = "" 33 | f_size = -1 34 | 35 | for fn in fns: 36 | s = os.lstat(fn).st_size 37 | if (s > f_size): 38 | f_size = s 39 | f_name = fn 40 | return(f_name) 41 | 42 | 43 | def read_sate_run_folder(directory, rar_fn = "runs_and_results-it*.csv",inst_fn = "instances.txt" , feat_fn = "instance-features.txt" , ps_fn = "paramstrings-it*.txt"): 44 | """ Helper function that can reads all information from a state_run folder. 45 | 46 | To get all information of a SMAC run, several different files have 47 | to be read. This function provides a short notation for gathering 48 | all data at once. 49 | 50 | :param directory: the location of the state_run_folder 51 | :type directory: str 52 | :param rar_fn: pattern to find the runs_and_results file 53 | :type rar_fn: str 54 | :param inst_fn: name of the instance file 55 | :type inst_fn: str 56 | :param feat_fn: name of the instance feature file. If this file is not found, pysmac assumes no instance features. 57 | :type feat_fn: str 58 | :param ps_fn: name of the paramstrings file 59 | :type ps_fn: str 60 | 61 | :returns: tuple -- (configurations returned by read_paramstring_file,\n 62 | instance names returned by read_instance_file,\n 63 | instance features returned by read_instance_features_file,\n 64 | actual run data returned by read_runs_and_results_file) 65 | """ 66 | print(("reading {}".format(directory))) 67 | configs = read_paramstrings_file(find_largest_file(os.path.join(directory,ps_fn))) 68 | instance_names = read_instances_file(find_largest_file(os.path.join(directory,inst_fn))) 69 | runs_and_results = read_runs_and_results_file(find_largest_file(os.path.join(directory, rar_fn))) 70 | 71 | full_feat_fn = glob.glob(os.path.join(directory,feat_fn)) 72 | if len(full_feat_fn) == 1: 73 | instance_features = read_instance_features_file(full_feat_fn[0]) 74 | else: 75 | instance_features = None 76 | 77 | return (configs, instance_names, instance_features, runs_and_results) 78 | 79 | 80 | 81 | def state_merge(state_run_directory_list, destination, 82 | check_scenario_files = True, drop_duplicates = False, 83 | instance_subset = None): 84 | """ Function to merge multiple state_run directories into a single 85 | run to be used in, e.g., the fANOVA. 86 | 87 | To take advantage of the data gathered in multiple independent runs, 88 | the state_run folders have to be merged into a single directory that 89 | resemble the same structure. This allows easy application of the 90 | pyfANOVA on all run_and_results files. 91 | 92 | :param state_run_directory_list: list of state_run folders to be merged 93 | :type state_run_directory_list: list of str 94 | :param destination: a directory to store the merged data. The folder is created if needed, and already existing data in that location is silently overwritten. 95 | :type destination: str 96 | :param check_scenario_files: whether to ensure that all scenario files in all state_run folders are identical. This helps to avoid merging runs with different settings. Note: Command-line options given to SMAC are not compared here! 97 | :type check_scenario_files: bool 98 | :param drop_duplicates: Defines how to handle runs with identical configurations. For deterministic algorithms the function's response should be the same, so dropping duplicates is safe. Keep in mind that every duplicate effectively puts more weight on a configuration when estimating parameter importance. 99 | :type drop_duplicates: bool 100 | :param instance_subset: Defines a list of instances that are used for the merge. All other instances are ignored. (Default: None, all instances are used) 101 | :type instance_subset: list 102 | """ 103 | 104 | configurations = {} 105 | instances = {} 106 | runs_and_results = {} 107 | ff_header= set() 108 | 109 | i_confs = 1; 110 | i_insts = 1; 111 | 112 | 113 | # make sure all pcs files are the same 114 | pcs_files = [os.path.join(d,'param.pcs') for d in state_run_directory_list] 115 | if not all([filecmp.cmp(fn, pcs_files[0]) for fn in pcs_files[1:]]): 116 | raise RuntimeError("The pcs files of the different runs are not identical!") 117 | 118 | #check the scenario files if desired 119 | scenario_files = [os.path.join(d,'scenario.txt') for d in state_run_directory_list] 120 | if check_scenario_files and not all([filecmp.cmp(fn, scenario_files[0]) for fn in scenario_files[1:]]): 121 | raise RuntimeError("The scenario files of the different runs are not identical!") 122 | 123 | for directory in state_run_directory_list: 124 | try: 125 | confs, inst_names, tmp , rars = read_sate_run_folder(directory) 126 | (header_feats, inst_feats) = tmp if tmp is not None else (None,None) 127 | 128 | except: 129 | print(("Something went wrong while reading {}. Skipping it.".format(directory))) 130 | continue 131 | 132 | # confs is a list of dicts, but dicts are not hashable, so they are 133 | # converted into a tuple of (key, value) pairs and then sorted 134 | confs = [tuple(sorted(d.items())) for d in confs] 135 | 136 | # merge the configurations 137 | for conf in confs: 138 | if not conf in configurations: 139 | configurations[conf] = {'index': i_confs} 140 | i_confs += 1 141 | # merge the instances 142 | ignored_instance_ids = [] 143 | for i in range(len(inst_names)): 144 | 145 | if instance_subset is not None and inst_names[i][0] not in instance_subset: 146 | ignored_instance_ids.append(i) 147 | continue 148 | 149 | if not inst_names[i][0] in instances: 150 | instances[inst_names[i][0]] = {'index': i_insts} 151 | instances[inst_names[i][0]]['features'] = inst_feats[inst_names[i][0]] if inst_feats is not None else None 152 | instances[inst_names[i][0]]['additional info'] = ' '.join(inst_names[i][1:]) if len(inst_names[i]) > 1 else None 153 | i_insts += 1 154 | else: 155 | if (inst_feats is None): 156 | if not (instances[inst_names[i][0]]['features'] is None): 157 | raise ValueError("The data contains the same instance name ({}) twice, but once with and without features!".format(inst_names[i])) 158 | elif not numpy.all(instances[inst_names[i][0]]['features'] == inst_feats[inst_names[i][0]]): 159 | raise ValueError("The data contains the same instance name ({}) twice, but with different features!".format(inst_names[i])) 160 | pass 161 | 162 | # store the feature file header: 163 | if header_feats is not None: 164 | ff_header.add(",".join(header_feats)) 165 | 166 | if len(ff_header) != 1: 167 | raise RuntimeError("Feature Files not consistent across runs!\n{}".format(header_feats)) 168 | 169 | 170 | if len(rars.shape) == 1: 171 | rars = numpy.array([rars]) 172 | 173 | for run in rars: 174 | # get the local configuration and instance id 175 | lcid, liid = int(run[0])-1, int(run[1])-1 176 | 177 | if liid in ignored_instance_ids: 178 | continue 179 | 180 | # translate them into the global ones 181 | gcid = configurations[confs[lcid]]['index'] 182 | giid = instances[inst_names[liid][0]]['index'] 183 | 184 | # check for duplicates and skip if necessary 185 | if (gcid, giid) in runs_and_results: 186 | if drop_duplicates: 187 | #print('dropped duplicate: configuration {} on instace {}'.format(gcid, giid)) 188 | continue 189 | else: 190 | runs_and_results[(gcid, giid)].append(run[2:]) 191 | else: 192 | runs_and_results[(gcid, giid)] = [run[2:]] 193 | 194 | # create output directory 195 | try: 196 | os.makedirs(destination) 197 | except OSError as e: 198 | if e.errno == errno.EEXIST: 199 | pass 200 | else: 201 | raise 202 | 203 | # create all files, overwriting existing ones 204 | shutil.copy(pcs_files[0], destination) 205 | shutil.copy(scenario_files[0], destination) 206 | 207 | 208 | with open(os.path.join(destination, 'instances.txt'),'w') as fh: 209 | sorted_instances = [] 210 | for name in instances: 211 | if instances[name]['additional info'] is not None: 212 | sorted_instances.append( (instances[name]['index'], name + ' ' + instances[name]['additional info']) ) 213 | else: 214 | sorted_instances.append( (instances[name]['index'], name) ) 215 | 216 | sorted_instances.sort() 217 | fh.write('\n'.join(map(operator.itemgetter(1), sorted_instances))) 218 | fh.write('\n') 219 | 220 | with open(os.path.join(destination, 'runs_and_results-it0.csv'),'w') as fh: 221 | cumulative_runtime = 0.0 222 | 223 | fh.write("Run Number,Run History Configuration ID,Instance ID," 224 | "Response Value (y),Censored?,Cutoff Time Used," 225 | "Seed,Runtime,Run Length," 226 | "Run Result Code,Run Quality,SMAC Iteration," 227 | "SMAC Cumulative Runtime,Run Result," 228 | "Additional Algorithm Run Data,Wall Clock Time,\n") 229 | run_i = 1 230 | for ((conf,inst),res) in list(runs_and_results.items()): 231 | for r in res: 232 | fh.write('{},{},{},'.format(run_i, conf, inst)) 233 | fh.write('{},{},{},'.format(r[0], int(r[1]), r[2])) 234 | fh.write('{},{},{},'.format(int(r[3]), r[4], r[5])) 235 | fh.write('{},{},{},'.format(int(r[6]), r[7], 0)) 236 | 237 | cumulative_runtime += r[4] 238 | if r[10] == 2: 239 | tmp = 'SAT' 240 | if r[10] == 1: 241 | tmp = 'UNSAT' 242 | if r[10] == 0: 243 | tmp = 'TIMEOUT' 244 | if r[10] == -1: 245 | tmp = 'CRASHED' 246 | 247 | fh.write('{},{},,{},'.format(cumulative_runtime,tmp, r[11])) 248 | fh.write('\n') 249 | run_i += 1 250 | 251 | with open(os.path.join(destination, 'paramstrings-it0.txt'),'w') as fh: 252 | sorted_confs = [(configurations[k]['index'],k) for k in list(configurations.keys())] 253 | sorted_confs.sort() 254 | for conf in sorted_confs: 255 | fh.write("{}: ".format(conf[0])) 256 | fh.write(", ".join(["{}='{}'".format(p[0],p[1]) for p in conf[1]])) 257 | fh.write('\n') 258 | 259 | 260 | #print(instances.values()) 261 | 262 | 263 | if header_feats is not None: 264 | with open(os.path.join(destination, 'instance-features.txt'),'w') as fh: 265 | fh.write("instance," + ff_header.pop()) 266 | sorted_features = [(instances[inst]['index'], inst + ',' + ",".join(list(map(str, instances[inst]['features']))) ) for inst in instances] 267 | sorted_features.sort() 268 | fh.write('\n'.join([ t[1] for t in sorted_features])) 269 | 270 | return(configurations, instances, runs_and_results, sorted_instances, sorted_confs, inst_feats) 271 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup, find_packages 2 | 3 | setup( 4 | name = 'pysmac', 5 | version = '0.9.1', 6 | packages = find_packages(), 7 | install_requires = ['docutils>=0.3', 'setuptools', 'numpy', 'pynisher'], 8 | author = "Stefan Falkner and Tobias Domhan (python wrapper). Frank Hutter, Holger Hoos, Kevin Leyton-Brown, Kevin Murphy and Steve Ramage (SMAC)", 9 | author_email = "sfalkner@informatik.uni-freiburg.de", 10 | description = "python interface to the hyperparameter optimization tool SMAC.", 11 | include_package_data = True, 12 | keywords = "hyperparameter parameter optimization hyperopt bayesian smac global", 13 | license = "SMAC is free for academic & non-commercial usage. Please contact Frank Hutter(fh@informatik.uni-freiburg.de) to discuss obtaining a license for commercial purposes.", 14 | url = "http://www.cs.ubc.ca/labs/beta/Projects/SMAC/", 15 | download_url = 'https://github.com/sfalkner/pysmac/tarball/0.9', 16 | extras_require={ 17 | 'analyzer': ['matplotlib'], 18 | }, 19 | ) 20 | --------------------------------------------------------------------------------