├── LICENSE
├── README.md
├── doc.go
├── example
├── README.md
├── ackley
│ └── ackley_test.go
├── queens
│ └── queens_test.go
└── tsp
│ └── tsp_test.go
├── integer
├── cross.go
└── int_test.go
├── interface.go
├── perm
├── cross.go
├── doc.go
├── mutation.go
├── perm.go
└── perm_test.go
├── pop
├── gen
│ └── generational.go
└── graph
│ └── graph.go
├── real
├── cross.go
├── distributions.go
├── evostrat.go
├── real_test.go
└── vector.go
├── sel
├── doc.go
├── elite.go
├── interface.go
├── round_robin.go
├── sel_test.go
└── tournament.go
├── stats.go
└── stats_test.go
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 | {one line to give the program's name and a brief idea of what it does.}
635 | Copyright (C) {year} {name of author}
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | {project} Copyright (C) {year} {fullname}
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
676 |
677 | GNU LESSER GENERAL PUBLIC LICENSE
678 | Version 3, 29 June 2007
679 |
680 | Copyright (C) 2007 Free Software Foundation, Inc.
681 | Everyone is permitted to copy and distribute verbatim copies
682 | of this license document, but changing it is not allowed.
683 |
684 |
685 | This version of the GNU Lesser General Public License incorporates
686 | the terms and conditions of version 3 of the GNU General Public
687 | License, supplemented by the additional permissions listed below.
688 |
689 | 0. Additional Definitions.
690 |
691 | As used herein, "this License" refers to version 3 of the GNU Lesser
692 | General Public License, and the "GNU GPL" refers to version 3 of the GNU
693 | General Public License.
694 |
695 | "The Library" refers to a covered work governed by this License,
696 | other than an Application or a Combined Work as defined below.
697 |
698 | An "Application" is any work that makes use of an interface provided
699 | by the Library, but which is not otherwise based on the Library.
700 | Defining a subclass of a class defined by the Library is deemed a mode
701 | of using an interface provided by the Library.
702 |
703 | A "Combined Work" is a work produced by combining or linking an
704 | Application with the Library. The particular version of the Library
705 | with which the Combined Work was made is also called the "Linked
706 | Version".
707 |
708 | The "Minimal Corresponding Source" for a Combined Work means the
709 | Corresponding Source for the Combined Work, excluding any source code
710 | for portions of the Combined Work that, considered in isolation, are
711 | based on the Application, and not on the Linked Version.
712 |
713 | The "Corresponding Application Code" for a Combined Work means the
714 | object code and/or source code for the Application, including any data
715 | and utility programs needed for reproducing the Combined Work from the
716 | Application, but excluding the System Libraries of the Combined Work.
717 |
718 | 1. Exception to Section 3 of the GNU GPL.
719 |
720 | You may convey a covered work under sections 3 and 4 of this License
721 | without being bound by section 3 of the GNU GPL.
722 |
723 | 2. Conveying Modified Versions.
724 |
725 | If you modify a copy of the Library, and, in your modifications, a
726 | facility refers to a function or data to be supplied by an Application
727 | that uses the facility (other than as an argument passed when the
728 | facility is invoked), then you may convey a copy of the modified
729 | version:
730 |
731 | a) under this License, provided that you make a good faith effort to
732 | ensure that, in the event an Application does not supply the
733 | function or data, the facility still operates, and performs
734 | whatever part of its purpose remains meaningful, or
735 |
736 | b) under the GNU GPL, with none of the additional permissions of
737 | this License applicable to that copy.
738 |
739 | 3. Object Code Incorporating Material from Library Header Files.
740 |
741 | The object code form of an Application may incorporate material from
742 | a header file that is part of the Library. You may convey such object
743 | code under terms of your choice, provided that, if the incorporated
744 | material is not limited to numerical parameters, data structure
745 | layouts and accessors, or small macros, inline functions and templates
746 | (ten or fewer lines in length), you do both of the following:
747 |
748 | a) Give prominent notice with each copy of the object code that the
749 | Library is used in it and that the Library and its use are
750 | covered by this License.
751 |
752 | b) Accompany the object code with a copy of the GNU GPL and this license
753 | document.
754 |
755 | 4. Combined Works.
756 |
757 | You may convey a Combined Work under terms of your choice that,
758 | taken together, effectively do not restrict modification of the
759 | portions of the Library contained in the Combined Work and reverse
760 | engineering for debugging such modifications, if you also do each of
761 | the following:
762 |
763 | a) Give prominent notice with each copy of the Combined Work that
764 | the Library is used in it and that the Library and its use are
765 | covered by this License.
766 |
767 | b) Accompany the Combined Work with a copy of the GNU GPL and this license
768 | document.
769 |
770 | c) For a Combined Work that displays copyright notices during
771 | execution, include the copyright notice for the Library among
772 | these notices, as well as a reference directing the user to the
773 | copies of the GNU GPL and this license document.
774 |
775 | d) Do one of the following:
776 |
777 | 0) Convey the Minimal Corresponding Source under the terms of this
778 | License, and the Corresponding Application Code in a form
779 | suitable for, and under terms that permit, the user to
780 | recombine or relink the Application with a modified version of
781 | the Linked Version to produce a modified Combined Work, in the
782 | manner specified by section 6 of the GNU GPL for conveying
783 | Corresponding Source.
784 |
785 | 1) Use a suitable shared library mechanism for linking with the
786 | Library. A suitable mechanism is one that (a) uses at run time
787 | a copy of the Library already present on the user's computer
788 | system, and (b) will operate properly with a modified version
789 | of the Library that is interface-compatible with the Linked
790 | Version.
791 |
792 | e) Provide Installation Information, but only if you would otherwise
793 | be required to provide such information under section 6 of the
794 | GNU GPL, and only to the extent that such information is
795 | necessary to install and execute a modified version of the
796 | Combined Work produced by recombining or relinking the
797 | Application with a modified version of the Linked Version. (If
798 | you use option 4d0, the Installation Information must accompany
799 | the Minimal Corresponding Source and Corresponding Application
800 | Code. If you use option 4d1, you must provide the Installation
801 | Information in the manner specified by section 6 of the GNU GPL
802 | for conveying Corresponding Source.)
803 |
804 | 5. Combined Libraries.
805 |
806 | You may place library facilities that are a work based on the
807 | Library side by side in a single library together with other library
808 | facilities that are not Applications and are not covered by this
809 | License, and convey such a combined library under terms of your
810 | choice, if you do both of the following:
811 |
812 | a) Accompany the combined library with a copy of the same work based
813 | on the Library, uncombined with any other library facilities,
814 | conveyed under the terms of this License.
815 |
816 | b) Give prominent notice with the combined library that part of it
817 | is a work based on the Library, and explaining where to find the
818 | accompanying uncombined form of the same work.
819 |
820 | 6. Revised Versions of the GNU Lesser General Public License.
821 |
822 | The Free Software Foundation may publish revised and/or new versions
823 | of the GNU Lesser General Public License from time to time. Such new
824 | versions will be similar in spirit to the present version, but may
825 | differ in detail to address new problems or concerns.
826 |
827 | Each version is given a distinguishing version number. If the
828 | Library as you received it specifies that a certain numbered version
829 | of the GNU Lesser General Public License "or any later version"
830 | applies to it, you have the option of following the terms and
831 | conditions either of that published version or of any later version
832 | published by the Free Software Foundation. If the Library as you
833 | received it does not specify a version number of the GNU Lesser
834 | General Public License, you may choose any version of the GNU Lesser
835 | General Public License ever published by the Free Software Foundation.
836 |
837 | If the Library as you received it specifies that a proxy can decide
838 | whether future versions of the GNU Lesser General Public License shall
839 | apply, that proxy's public statement of acceptance of any version is
840 | permanent authorization for you to choose that version for the
841 | Library.
842 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Evo
2 |
3 | Evo is a framework for implementing evolutionary algorithms in Go.
4 |
5 | ```
6 | go get github.com/cbarrick/evo
7 | ```
8 |
9 |
10 | ## Documentation
11 |
12 | https://godoc.org/github.com/cbarrick/evo
13 |
14 |
15 | ## Status & Contributing
16 |
17 | Evo is a general framework for developing genetic algorithms and more. It began life in fall 2015 as I studied evolutionary algorithms as an undergrad.
18 |
19 | Contributions are welcome! I am currently a student and inexperienced maintainer, so please bear with me as I learn. The focus of the project thus far has been on the API design and less on performance. I am particularly interested in hearing about use-cases that are not well covered and success stories of where Evo excels. Testing, code reviews, and performance audits are always welcome and needed.
20 |
21 |
22 | ## Examples
23 |
24 | You can browse example problems in the [example subpackage]. The examples are maintained as a development tool rather than to provide optimal solutions to the problems they tackle. Reading the examples should give you a good idea of how easy it is to write code with Evo.
25 |
26 | [example subpackage]: https://github.com/cbarrick/evo/tree/master/example
27 |
28 |
29 | ## License (LGPL)
30 |
31 | This program is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
32 |
33 | This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
34 |
35 | You should have received a copy of the GNU Lesser General Public License along with this program. If not, see .
36 |
--------------------------------------------------------------------------------
/doc.go:
--------------------------------------------------------------------------------
1 | // Evo is a framework for implementing evolutionary algorithms in Go.
2 | //
3 | // Evo exposes a clean and flexible API oriented around two interfaces: `Genome`
4 | // and `Population`. Genomes represent both the function being optimized and the
5 | // representation of solutions. Populations represent the architecture under
6 | // which genomes are evolved. Multiple population types are provided by Evo to
7 | // enable the construction of both common and novel architectures.
8 | //
9 | // The body of the evolutionary loop is defined by an evolve function. For each
10 | // genome in a population, the evolve function is called, receiving some subset
11 | // of the population, called the suitors, as arguments. The evolve function then
12 | // applies the user's variation operators (selection, mutation, etc) and returns
13 | // a genome for the next iteration. common operators for a variety of
14 | // representations are provided as subpackages of Evo.
15 | //
16 | // Populations model the evolution patterns of genomes. A few different
17 | // population types are provided by Evo under the package `evo/pop`. Populations
18 | // themselves implement the Genome interface, making them composeable. Migration
19 | // functions are provided to be used in this context, allowing go novel
20 | // architectures like the island model.
21 | package evo
22 |
23 | // TODO: Keep this in sync with the readme
24 |
--------------------------------------------------------------------------------
/example/README.md:
--------------------------------------------------------------------------------
1 | # Evo Examples
2 |
3 | This package contains examples of Evo being used on well know problems. The goal of the examples is not to be the best at solving the particular problem but instead to highlight various use-cases of Evo. Each example is implemented as a unit test and can be easily run with the `go test` command. For example, to run the `ackley` example from the source root:
4 |
5 | go test ./example/ackley -v
6 |
7 | ## Descriptions
8 |
9 | - `ackley`: This example minimizes the Ackley function, a standard benchmark function for real-valued optimization. The problem is highly multimodal with a global minimum of 0 at the origin. The example minimizes the function in 30 dimensions with a self-adaptive (40/2,280)-evolution strategy.
10 |
11 | - `queens`: This example solves the 128-queens problem by minimizing the number of conflicts on the board. The example highlights nested populations by implementing an island model where the population is divided among several sub-populations, called islands, and each island is evolved independently and in parallel. Occasionally migrations of individuals occur between the islands to serve as sources of new genes.
12 |
13 | - `tsp`: This example searches for a minimal tour of the capitals of the 48 contiguous American states (dataset ATT48 of [TSPLIB]). The example uses a diffusion model, where is population is arranged in a hypercube and individuals breed only with their neighbors. The example also highlights hybridization with local search by using a 2-opt hillclimber as a mutation.
14 |
15 | [TSPLIB]: http://comopt.ifi.uni-heidelberg.de/software/TSPLIB95/
16 |
--------------------------------------------------------------------------------
/example/ackley/ackley_test.go:
--------------------------------------------------------------------------------
1 | package ackley
2 |
3 | import (
4 | "fmt"
5 | "math"
6 | "math/rand"
7 | "sync"
8 | "testing"
9 |
10 | "github.com/cbarrick/evo"
11 | "github.com/cbarrick/evo/pop/gen"
12 | "github.com/cbarrick/evo/real"
13 | "github.com/cbarrick/evo/sel"
14 | )
15 |
16 | // Tuneables
17 | const (
18 | dim = 30 // Dimension of the problem.
19 | bounds = 30 // Bounds of object parameters.
20 | precision = 1e-16 // Desired precision.
21 | )
22 |
23 | // Global objects
24 | var (
25 | // Count of the number of fitness evaluations.
26 | count struct {
27 | sync.Mutex
28 | n int
29 | }
30 |
31 | // Each of the 40 members of the population generates 7 children and adds
32 | // them to this pool. This pool returns to each member a different one of
33 | // most fit to be their replacement in the next generation.
34 | selector = sel.ElitePool(40, 280)
35 | )
36 |
37 | // The ackley type specifies our genome. We evolve a real-valued vector that
38 | // optimizes the ackley function. Each genome also contains a vector of strategy
39 | // parameters used with a self-adaptive evolution strategy.
40 | type ackley struct {
41 | gene real.Vector // the object vector to optimize
42 | steps real.Vector // strategy parameters for mutation
43 | fit float64 // the ackley function of the gene
44 | once sync.Once // used to compute fitness lazily
45 | }
46 |
47 | // Returns the fitness as a string.
48 | func (ack *ackley) String() string {
49 | return fmt.Sprint(-ack.Fitness())
50 | }
51 |
52 | // Fitness returns the ackley function of the gene. We are trying to solve a
53 | // minimization problem, so we return the negative of the traditional formula.
54 | // The fitness of a genome is only computed once across all calls to Fitness by
55 | // using a sync.Once.
56 | func (ack *ackley) Fitness() float64 {
57 | const a, b = 20, 0.2
58 | ack.once.Do(func() {
59 | var sum1, sum2 float64
60 | n := float64(dim)
61 | for _, x := range ack.gene {
62 | sum1 += x * x
63 | sum2 += math.Cos(2 * math.Pi * x)
64 | }
65 |
66 | ack.fit -= a
67 | ack.fit *= math.Exp(-b * math.Sqrt(sum1/n))
68 | ack.fit -= math.Exp(sum2 / n)
69 | ack.fit += a
70 | ack.fit += math.E
71 | ack.fit *= -1
72 |
73 | count.Lock()
74 | count.n++
75 | count.Unlock()
76 | })
77 | return ack.fit
78 | }
79 |
80 | // Evolve implements the inner loop of the evolutionary algorithm.
81 | // The population calls the Evolve method of each genome, in parallel. Then,
82 | // each receiver returns a value to replace it in the next generation. A global
83 | // selector object synchronises replacement among the parallel parents.
84 | func Evolve(ack evo.Genome, suitors []evo.Genome) evo.Genome {
85 | for i := 0; i < 7; i++ {
86 | // Creation:
87 | // We create the child genome from recycled memory when we can.
88 | var child ackley
89 | child.gene = make(real.Vector, dim)
90 | child.steps = make(real.Vector, dim)
91 |
92 | // Crossover:
93 | // Select two parents at random.
94 | // Uniform crossover of object parameters.
95 | // Arithmetic crossover of strategy parameters.
96 | mom := suitors[rand.Intn(len(suitors))].(*ackley)
97 | dad := suitors[rand.Intn(len(suitors))].(*ackley)
98 | real.UniformX(child.gene, mom.gene, dad.gene)
99 | real.ArithX(1, child.steps, mom.steps, dad.steps)
100 |
101 | // Mutation: Evolution Strategy
102 | // Lognormal scaling of strategy parameters.
103 | // Gausian perturbation of object parameters.
104 | child.steps.Adapt()
105 | child.steps.LowBound(precision)
106 | child.gene.Step(child.steps)
107 | child.gene.HighBound(bounds)
108 | child.gene.LowBound(-bounds)
109 |
110 | // Replacement: (40,280)
111 | // Each child is added to the global selection pool.
112 | selector.Put(&child)
113 | }
114 |
115 | // Finally, block until all parallel calls have added their children to the
116 | // selection pool and return one of the selected replacements.
117 | return selector.Get()
118 | }
119 |
120 | func TestAckley(t *testing.T) {
121 | fmt.Printf("Minimize the Ackley function with n=%d\n", dim)
122 |
123 | // Setup:
124 | // We initialize a set of 40 random solutions,
125 | // then add them to a generational population.
126 | seed := make([]evo.Genome, 40)
127 | for i := range seed {
128 | seed[i] = &ackley{
129 | gene: real.Random(dim, 30),
130 | steps: real.Random(dim, 1),
131 | }
132 | }
133 | var pop gen.Population
134 | pop.Evolve(seed, Evolve)
135 |
136 | // Continuously print statistics while the optimization runs.
137 | pop.Poll(0, func() bool {
138 | count.Lock()
139 | n := count.n
140 | count.Unlock()
141 | stats := pop.Stats()
142 |
143 | // "\x1b[2K" is the escape code to clear the line
144 | // The fitness of minimization problems is negative
145 | fmt.Printf("\x1b[2K\rCount: %7d | Max: %8.3g | Mean: %8.3g | Min: %8.3g | RSD: %9.2e",
146 | n,
147 | -stats.Min(),
148 | -stats.Mean(),
149 | -stats.Max(),
150 | -stats.RSD())
151 |
152 | return false
153 | })
154 |
155 | // Terminate after 200,000 fitness evaluations.
156 | pop.Poll(0, func() bool {
157 | count.Lock()
158 | n := count.n
159 | count.Unlock()
160 | return n > 200000
161 | })
162 |
163 | // Terminate if the standard deviation is low.
164 | pop.Poll(0, func() bool {
165 | stats := pop.Stats()
166 | return stats.SD() < precision
167 | })
168 |
169 | pop.Wait()
170 | selector.Close()
171 | best := seed[0]
172 | bestFit := seed[0].Fitness()
173 | for i := range seed {
174 | fit := seed[i].Fitness()
175 | if fit > bestFit {
176 | best = seed[i]
177 | bestFit = fit
178 | }
179 | }
180 | fmt.Println("\nSolution:", best)
181 | }
182 |
--------------------------------------------------------------------------------
/example/queens/queens_test.go:
--------------------------------------------------------------------------------
1 | package queens
2 |
3 | import (
4 | "fmt"
5 | "math/rand"
6 | "sync"
7 | "testing"
8 | "time"
9 |
10 | "github.com/cbarrick/evo"
11 | "github.com/cbarrick/evo/perm"
12 | "github.com/cbarrick/evo/pop/gen"
13 | "github.com/cbarrick/evo/pop/graph"
14 | "github.com/cbarrick/evo/sel"
15 | )
16 |
17 | // Tuneables
18 | const (
19 | dim = 128 // the dimension of the problem
20 | size = dim * 4 // the size of the population
21 | isl = 4 // the number of islands in which to divide the population
22 |
23 | migration = size / isl / 8 // the size of migrations
24 | delay = 1 * time.Second // the delay between migrations
25 | )
26 |
27 | // Global objects
28 | var (
29 | // counts the number of fitness evaluations
30 | count struct {
31 | sync.Mutex
32 | n int
33 | }
34 | )
35 |
36 | // The queens type is our genome. We evolve a permuation of [0,n)
37 | // representing the position of queens on an n x n board
38 | type queens struct {
39 | gene []int // permutation representation of an n-queens solution
40 | fitness float64 // the negative of the number of conflicts in the solution
41 | once sync.Once // used to compute fitness lazily
42 | }
43 |
44 | // String returns the gene contents and number of conflicts.
45 | func (q *queens) String() string {
46 | return fmt.Sprintf("%v@%v", q.gene, -q.Fitness())
47 | }
48 |
49 | // Fitness returns the negative of the number of conflicts in the solution.
50 | // The fitness of a genome is only computed once across all calls to Fitness by
51 | // using a sync.Once.
52 | func (q *queens) Fitness() float64 {
53 | q.once.Do(func() {
54 | for i := range q.gene {
55 | for j, k := 1, i-1; k >= 0; j, k = j+1, k-1 {
56 | if q.gene[k] == q.gene[i]+j || q.gene[k] == q.gene[i]-j {
57 | q.fitness--
58 | }
59 | }
60 | for j, k := 1, i+1; k < len(q.gene); j, k = j+1, k+1 {
61 | if q.gene[k] == q.gene[i]+j || q.gene[k] == q.gene[i]-j {
62 | q.fitness--
63 | }
64 | }
65 | }
66 | q.fitness /= 2
67 |
68 | count.Lock()
69 | count.n++
70 | count.Unlock()
71 | })
72 | return q.fitness
73 | }
74 |
75 | // Evolution implements the body of the evolution loop.
76 | func Evolution(q evo.Genome, suitors []evo.Genome) evo.Genome {
77 | // Crossover:
78 | // We're implementing a diffusion model. For each member of the population,
79 | // we receive a small mating pool containing only our neighbors. We choose
80 | // a mate using a random binary tournament and create a child with
81 | // partially mapped crossover.
82 | mom := q.(*queens)
83 | dad := sel.BinaryTournament(suitors...).(*queens)
84 | child := &queens{gene: make([]int, len(mom.gene))}
85 | perm.PMX(child.gene, mom.gene, dad.gene)
86 |
87 | // Mutation:
88 | // Perform n random swaps where n is taken from an exponential distribution.
89 | // mutationCount := math.Ceil(rand.ExpFloat64() - 0.5)
90 | for i := float64(0); i < 5; i++ {
91 | j := rand.Intn(len(child.gene))
92 | k := rand.Intn(len(child.gene))
93 | child.gene[j], child.gene[k] = child.gene[k], child.gene[j]
94 | }
95 |
96 | // Replacement:
97 | // Only replace if the child is better or equal.
98 | if q.Fitness() > child.Fitness() {
99 | return q
100 | }
101 | return child
102 | }
103 |
104 | func TestQueens(t *testing.T) {
105 | fmt.Printf("Find a solution to %d-queens\n", dim)
106 |
107 | // Setup:
108 | // We create an initial set of random candidates and divide them into "islands".
109 | // Each island is evolved independently in a generational population.
110 | // The islands are then linked together into a graph population with
111 | seed := make([]evo.Genome, size)
112 | for i := range seed {
113 | seed[i] = &queens{gene: perm.New(dim)}
114 | }
115 | islands := make([]evo.Genome, isl)
116 | islSize := size / isl
117 | for i := range islands {
118 | var island gen.Population
119 | island.Evolve(seed[i*islSize:(i+1)*islSize], Evolution)
120 | islands[i] = &island
121 | }
122 | pop := graph.Ring(isl)
123 | pop.Evolve(islands, gen.Migrate(migration, delay))
124 |
125 | // Continuously print statistics while the optimization runs.
126 | pop.Poll(0, func() bool {
127 | count.Lock()
128 | n := count.n
129 | count.Unlock()
130 | stats := pop.Stats()
131 |
132 | // "\x1b[2K" is the xterm escape code to clear the line
133 | // Because this is a minimization problem, the fitness is negative.
134 | // Thus we update the statistics accordingly.
135 | fmt.Printf("\x1b[2K\rCount: %7d | Max: %3.0f | Mean: %3.0f | Min: %3.0f | RSD: %9.2e",
136 | n,
137 | -stats.Min(),
138 | -stats.Mean(),
139 | -stats.Max(),
140 | -stats.RSD())
141 |
142 | return false
143 | })
144 |
145 | // Terminate when we've found the solution (when max is 0)
146 | pop.Poll(0, func() bool {
147 | stats := pop.Stats()
148 | return stats.Max() == 0
149 | })
150 |
151 | // Terminate if We've converged to a deviation is less than 0.01
152 | pop.Poll(0, func() bool {
153 | stats := pop.Stats()
154 | return stats.SD() < 1e-2
155 | })
156 |
157 | // Terminate after 2,000,000 fitness evaluations.
158 | pop.Poll(0, func() bool {
159 | count.Lock()
160 | n := count.n
161 | count.Unlock()
162 | return n > 2e6
163 | })
164 |
165 | pop.Wait()
166 | best := seed[0]
167 | bestFit := seed[0].Fitness()
168 | for i := range seed {
169 | fit := seed[i].Fitness()
170 | if fit > bestFit {
171 | best = seed[i]
172 | bestFit = fit
173 | }
174 | }
175 | fmt.Println("\nSolution:", best)
176 | }
177 |
--------------------------------------------------------------------------------
/example/tsp/tsp_test.go:
--------------------------------------------------------------------------------
1 | package tsp
2 |
3 | import (
4 | "fmt"
5 | "math"
6 | "math/rand"
7 | "sync"
8 | "testing"
9 |
10 | "github.com/cbarrick/evo"
11 | "github.com/cbarrick/evo/perm"
12 | "github.com/cbarrick/evo/pop/graph"
13 | "github.com/cbarrick/evo/sel"
14 | )
15 |
16 | // Constants
17 | const (
18 | dim = len(cities) // the dimension of the problem
19 | size = 256 // the size of the population
20 | )
21 |
22 | // Global objects
23 | var (
24 | // The evolutionary loop managed by the population
25 | pop evo.Population
26 |
27 | // Count of the number of fitness evaluations.
28 | count struct {
29 | sync.Mutex
30 | n int
31 | }
32 |
33 | // A free-list used to recycle memory.
34 | pool = sync.Pool{
35 | New: func() interface{} {
36 | return rand.Perm(dim)
37 | },
38 | }
39 | )
40 |
41 | // A city is a coordinate pair giving the position of the city.
42 | type city struct {
43 | x, y float64
44 | }
45 |
46 | // Dist returns the pseudo-euclidian distance between two cities. This is the
47 | // distance function used in the literature on this problem instance.
48 | // http://comopt.ifi.uni-heidelberg.de/software/TSPLIB95/DOC.PS
49 | func dist(a, b city) float64 {
50 | xd := a.x - b.x
51 | yd := a.y - b.y
52 | d := math.Sqrt(xd*xd/10 + yd*yd/10)
53 | return math.Ceil(d)
54 | }
55 |
56 | // The tsp type is our genome type.
57 | type tsp struct {
58 | gene []int // permutation representation of a tour
59 | fitness float64 // the negative length of the tour
60 | once sync.Once // used to compute fitness lazily
61 | }
62 |
63 | // String returns the gene contents and length of the tour.
64 | func (t *tsp) String() string {
65 | return fmt.Sprintf("%v@%v", t.gene, -t.Fitness())
66 | }
67 |
68 | // Close recycles the memory of this genome to be use for new genomes.
69 | func (t *tsp) Close() {
70 | pool.Put(t.gene)
71 | t.gene = nil
72 | }
73 |
74 | // Fitness returns the negative length of the tour represented by a tsp genome.
75 | // The fitness is negative because TSP is a minimization problem, but the Evo
76 | // API is phrased in terms of maximization. As a consequence, fitness statistics
77 | // (i.e. the result of pop.Stats()) are also negative: the shortest know path
78 | // would be -stats.Max().
79 | func (t *tsp) Fitness() float64 {
80 | t.once.Do(func() {
81 | t.fitness = 0
82 | for i := range t.gene {
83 | a := cities[t.gene[i]]
84 | b := cities[t.gene[(i+1)%dim]]
85 | t.fitness -= dist(a, b)
86 | }
87 |
88 | count.Lock()
89 | count.n++
90 | count.Unlock()
91 | })
92 | return t.fitness
93 | }
94 |
95 | // TwoOpt performs a 2-opt local search for improvement of the gene. The first
96 | // edge is selected at random and inversions between all other edges are
97 | // evaluated in random order. Even if an improvement is not found, the gene will
98 | // be rotated by an uniform-random amount. We use this search as a form of
99 | // mutation.
100 | func (t *tsp) TwoOpt() {
101 | t.once = sync.Once{}
102 | perm.Rotate(t.gene, rand.Intn(dim))
103 | for _, i := range rand.Perm(dim) {
104 | if i < 2 {
105 | continue
106 | }
107 | a := cities[t.gene[0]]
108 | b := cities[t.gene[i-1]]
109 | y := cities[t.gene[i]]
110 | z := cities[t.gene[dim-1]]
111 | before := dist(b, y) + dist(z, a)
112 | after := dist(a, y) + dist(z, b)
113 | if after < before {
114 | perm.Reverse(t.gene[:i])
115 | return
116 | }
117 | }
118 | }
119 |
120 | // Evolve implements the inner loop of the evolutionary algorithm.
121 | // The population calls the Evolve method of each genome, in parallel. Then,
122 | // each receiver returns a value to replace it in the next generation.
123 | func Evolve(current evo.Genome, matingPool []evo.Genome) evo.Genome {
124 | // Selection:
125 | // Select each parent using a simple random binary tournament
126 | mom := sel.BinaryTournament(matingPool...).(*tsp)
127 | dad := sel.BinaryTournament(matingPool...).(*tsp)
128 |
129 | // Crossover:
130 | // Edge recombination
131 | child := &tsp{gene: pool.Get().([]int)}
132 | perm.EdgeX(child.gene, mom.gene, dad.gene)
133 |
134 | // Mutation:
135 | // There is an n% chance for the gene to have n random swaps
136 | // and an n% chance to undergo n steps of a greedy 2-opt hillclimber
137 | for rand.Float64() < 0.1 {
138 | perm.RandSwap(child.gene)
139 | }
140 | for rand.Float64() < 0.1 {
141 | child.TwoOpt()
142 | }
143 |
144 | // Replacement:
145 | // Only replace if the child is better or equal
146 | if current.Fitness() > child.Fitness() {
147 | return current
148 | }
149 | return child
150 | }
151 |
152 | func TestTSP(t *testing.T) {
153 | fmt.Println("Minimize tour of US capitals - optimal is", best)
154 |
155 | // Setup:
156 | // We create a random initial population
157 | // and evolve it using a generational model.
158 | seed := make([]evo.Genome, size)
159 | for i := range seed {
160 | seed[i] = &tsp{gene: pool.Get().([]int)}
161 | }
162 | pop = graph.Hypercube(size)
163 | pop.Evolve(seed, Evolve)
164 |
165 | // Continuously print statistics while the optimization runs.
166 | pop.Poll(0, func() bool {
167 | count.Lock()
168 | n := count.n
169 | count.Unlock()
170 | stats := pop.Stats()
171 |
172 | // "\x1b[2K" is the escape code to clear the line
173 | // The fitness of minimization problems is negative
174 | fmt.Printf("\x1b[2K\rCount: %7d | Max: %6.0f | Mean: %6.0f | Min: %6.0f | RSD: %7.2e",
175 | n,
176 | -stats.Min(),
177 | -stats.Mean(),
178 | -stats.Max(),
179 | -stats.RSD())
180 |
181 | return false
182 | })
183 |
184 | // Stop when we get close. Finding the true minimum could take a while.
185 | pop.Poll(0, func() bool {
186 | stats := pop.Stats()
187 | return -stats.Max() < best*1.1
188 | })
189 |
190 | // Terminate after 2,000,000 fitness evaluations.
191 | pop.Poll(0, func() bool {
192 | count.Lock()
193 | n := count.n
194 | count.Unlock()
195 | return n > 2e6
196 | })
197 |
198 | pop.Wait()
199 | best := seed[0]
200 | bestFit := seed[0].Fitness()
201 | for i := range seed {
202 | fit := seed[i].Fitness()
203 | if fit > bestFit {
204 | best = seed[i]
205 | bestFit = fit
206 | }
207 | }
208 | fmt.Println("\nTour:", best)
209 | }
210 |
211 | // Best is the minimum tour of the cities.
212 | const best = 10628
213 |
214 | // Cities is a list of the capitals of the 48 contiguous American states. The
215 | // minimum tour length is 10628. This is dataset ATT48 from TSPLIB, a collection
216 | // of traveling salesman problem datasets maintained by Dr. Gerhard Reinelt:
217 | // "http://comopt.ifi.uni-heidelberg.de/software/TSPLIB95/"
218 | var cities = [48]city{
219 | {6734, 1453},
220 | {2233, 10},
221 | {5530, 1424},
222 | {401, 841},
223 | {3082, 1644},
224 | {7608, 4458},
225 | {7573, 3716},
226 | {7265, 1268},
227 | {6898, 1885},
228 | {1112, 2049},
229 | {5468, 2606},
230 | {5989, 2873},
231 | {4706, 2674},
232 | {4612, 2035},
233 | {6347, 2683},
234 | {6107, 669},
235 | {7611, 5184},
236 | {7462, 3590},
237 | {7732, 4723},
238 | {5900, 3561},
239 | {4483, 3369},
240 | {6101, 1110},
241 | {5199, 2182},
242 | {1633, 2809},
243 | {4307, 2322},
244 | {675, 1006},
245 | {7555, 4819},
246 | {7541, 3981},
247 | {3177, 756},
248 | {7352, 4506},
249 | {7545, 2801},
250 | {3245, 3305},
251 | {6426, 3173},
252 | {4608, 1198},
253 | {23, 2216},
254 | {7248, 3779},
255 | {7762, 4595},
256 | {7392, 2244},
257 | {3484, 2829},
258 | {6271, 2135},
259 | {4985, 140},
260 | {1916, 1569},
261 | {7280, 4899},
262 | {7509, 3239},
263 | {10, 2676},
264 | {6807, 2993},
265 | {5185, 3258},
266 | {3023, 1942},
267 | }
268 |
--------------------------------------------------------------------------------
/integer/cross.go:
--------------------------------------------------------------------------------
1 | package integer
2 |
3 | import "math/rand"
4 |
5 | // UniformX performs a uniform crossover of some parents into a child.
6 | func UniformX(child []int, parents ...[]int) {
7 | n := len(parents)
8 | for i := range child {
9 | child[i] = parents[rand.Intn(n)][i]
10 | }
11 | }
12 |
13 | // PointX performs n-point crossover of two parents into a child.
14 | func PointX(n int, child, mom, dad []int) {
15 | if rand.Intn(2) == 0 {
16 | mom, dad = dad, mom
17 | }
18 | for 0 < n {
19 | i := rand.Intn(len(child)-n) + 1
20 | copy(child, mom[:i])
21 | child = child[i:]
22 | mom, dad = dad[i:], mom[i:]
23 | n--
24 | }
25 | copy(child, mom)
26 | }
27 |
--------------------------------------------------------------------------------
/integer/int_test.go:
--------------------------------------------------------------------------------
1 | package integer_test
2 |
3 | import (
4 | "testing"
5 |
6 | "github.com/cbarrick/evo/integer"
7 | )
8 |
9 | // cross.go
10 | // -------------------------
11 |
12 | func TestUniformX(t *testing.T) {
13 | mom := make([]int, 8)
14 | dad := make([]int, 8)
15 | for i := range mom {
16 | mom[i] = 1
17 | }
18 | for i := range dad {
19 | dad[i] = 2
20 | }
21 | child := make([]int, 8)
22 | integer.UniformX(child, mom, dad)
23 | for i := range child {
24 | if child[i] != mom[i] && child[i] != dad[i] {
25 | t.Fail()
26 | }
27 | }
28 | }
29 |
30 | func TestPointX(t *testing.T) {
31 | mom := make([]int, 8)
32 | dad := make([]int, 8)
33 | for i := range mom {
34 | mom[i] = 1
35 | }
36 | for i := range dad {
37 | dad[i] = 2
38 | }
39 | child := make([]int, 8)
40 | integer.PointX(7, child, mom, dad)
41 | for i := range child {
42 | if child[i] != mom[i] && child[i] != dad[i] {
43 | t.Fail()
44 | }
45 | }
46 | }
47 |
--------------------------------------------------------------------------------
/interface.go:
--------------------------------------------------------------------------------
1 | package evo
2 |
3 | import "time"
4 |
5 | // A ConditionFn describes a termination condition.
6 | type ConditionFn func() bool
7 |
8 | // An EvolveFn describes an iteration of the evolution loop. The evolve function
9 | // is called once for each member of the population, possibly in parrallel, and
10 | // is responsible for producing new Genomes given some subset of the population,
11 | // called the suitors. The replacement Genome replaces the current Genome within
12 | // the population.
13 | type EvolveFn func(current Genome, suitors []Genome) (replacement Genome)
14 |
15 | // A Genome describes the function being optimized and the representation of
16 | // solutions. Genomes are provided by the user, and Evo provides convenience
17 | // packages for common representations.
18 | type Genome interface {
19 | // The Fitness method is the function being maximized.
20 | // For minimization problems, return the negative or the inverse.
21 | Fitness() float64
22 | }
23 |
24 | // A Population models the interaction between Genomes during evolution. In
25 | // practice, this determines the kind of parallelism and number of suitors
26 | // during the optimization.
27 | //
28 | // Populations implement Genome, making them composable. For example, an island
29 | // model can be built by composing generational populations into a graph
30 | // population.
31 | type Population interface {
32 | // Fitness returns the maximum fitness of the population.
33 | Fitness() float64
34 |
35 | // Evolve starts the evolution of the population in a separate goroutine.
36 | // Genomes are evolved in place; it is not safe to access the genome slice
37 | // while the evolution is running.
38 | Evolve([]Genome, EvolveFn)
39 |
40 | // Stop terminates the optimization.
41 | Stop()
42 |
43 | // Poll executes a function at some frequency for the duration of the
44 | // current optimization. If the function returns true, the current
45 | // optimization is halted. Use a frequency of 0 for continuous polling.
46 | Poll(freq time.Duration, cond ConditionFn)
47 |
48 | // Wait blocks until the evolution terminates.
49 | Wait()
50 |
51 | // Stats returns various statistics about the population.
52 | Stats() Stats
53 | }
54 |
--------------------------------------------------------------------------------
/perm/cross.go:
--------------------------------------------------------------------------------
1 | package perm
2 |
3 | import (
4 | "math/rand"
5 | )
6 |
7 | // OrderX performs order crossover. Order crossover is a good choice when you
8 | // want to inherit the relative order of values.
9 | func OrderX(child, mom, dad []int) {
10 | if rand.Float64() < 0.5 {
11 | mom, dad = dad, mom
12 | }
13 | sub, left, right := RandSlice(mom)
14 | copy(child[left:right], sub)
15 | i, j := right, right
16 | for i < left || right <= i {
17 | if Search(sub, dad[j]) == -1 {
18 | child[i] = dad[j]
19 | i = (i + 1) % len(child)
20 | }
21 | j = (j + 1) % len(child)
22 | }
23 | }
24 |
25 | // PMX performs partially mapped crossover. PMX inherits a random slice of one
26 | // parent. The position of the other values is more random when there is greater
27 | // difference between the parents.
28 | func PMX(child, mom, dad []int) {
29 | if rand.Float64() < 0.5 {
30 | mom, dad = dad, mom
31 | }
32 | _, left, right := RandSlice(mom)
33 |
34 | for i := range child {
35 | child[i] = -1
36 | }
37 | copy(child[left:right], mom[left:right])
38 |
39 | for i := left; i < right; i++ {
40 | if Search(child, dad[i]) == -1 {
41 | j := i
42 | for left <= j && j < right {
43 | j = Search(dad, mom[j])
44 | }
45 | child[j] = dad[i]
46 | }
47 | }
48 |
49 | for i := range child {
50 | if child[i] == -1 {
51 | child[i] = dad[i]
52 | }
53 | }
54 | }
55 |
56 | // CycleX performs cycle crossover. Cycle crossover is a good choice when you
57 | // want to inherit the absolute position of values.
58 | func CycleX(child, mom, dad []int) {
59 | if rand.Float64() < 0.5 {
60 | mom, dad = dad, mom
61 | }
62 | var cycles [][]int
63 | taken := make([]bool, len(mom))
64 | for i := range mom {
65 | if !taken[i] {
66 | var cycle []int
67 | for j := i; !taken[j]; {
68 | taken[j] = true
69 | cycle = append(cycle, j)
70 | j = Search(mom, dad[j])
71 | }
72 | cycles = append(cycles, cycle)
73 | }
74 | }
75 |
76 | var who bool
77 | for i := range cycles {
78 | var parent []int
79 | if who {
80 | parent = mom
81 | } else {
82 | parent = dad
83 | }
84 | for _, j := range cycles[i] {
85 | child[j] = parent[j]
86 | }
87 | if len(cycles[i]) > 1 {
88 | who = !who
89 | }
90 | }
91 | }
92 |
93 | // EdgeX performs edge recombination. Edge recombination is a good choice when
94 | // you want to inherit adjacency information.
95 | func EdgeX(child, mom, dad []int) {
96 | dim := len(mom)
97 | child = child[0:0]
98 |
99 | if rand.Float64() < 0.5 {
100 | mom, dad = dad, mom
101 | }
102 |
103 | // build the table
104 | // doubles are marked by negating the entry
105 | table := make([][]int, dim)
106 | for i := range table {
107 | table[i] = make([]int, 0, 4)
108 | }
109 | for i := range table {
110 | var j int
111 |
112 | var mnext, mprev int
113 | j = Search(mom, i)
114 | if j == 0 {
115 | mnext = 1
116 | mprev = dim - 1
117 | } else if j == dim-1 {
118 | mnext = 0
119 | mprev = dim - 2
120 | } else {
121 | mnext = j + 1
122 | mprev = j - 1
123 | }
124 | table[i] = append(table[i], mom[mnext], mom[mprev])
125 |
126 | var dnext, dprev int
127 | j = Search(dad, i)
128 | if j == 0 {
129 | dnext = 1
130 | dprev = dim - 1
131 | } else if j == dim-1 {
132 | dnext = 0
133 | dprev = dim - 2
134 | } else {
135 | dnext = j + 1
136 | dprev = j - 1
137 | }
138 | if table[i][0] == dad[dnext] {
139 | table[i][0] = -table[i][0]
140 | } else if table[i][1] == dad[dnext] {
141 | table[i][1] = -table[i][1]
142 | } else {
143 | table[i] = append(table[i], dad[dnext])
144 | }
145 | if table[i][0] == dad[dprev] {
146 | table[i][0] = -table[i][0]
147 | } else if table[i][1] == dad[dprev] {
148 | table[i][1] = -table[i][1]
149 | } else {
150 | table[i] = append(table[i], dad[dprev])
151 | }
152 | }
153 |
154 | // clear removes all occurences of x in the table
155 | clear := func(x int) {
156 | for i := range table {
157 | newrow := table[i][0:0]
158 | pos := Search(table[i], x)
159 | neg := Search(table[i], -x)
160 | for j := range table[i] {
161 | if j != pos && j != neg {
162 | newrow = append(newrow, table[i][j])
163 | }
164 | }
165 | table[i] = newrow
166 | }
167 | }
168 |
169 | // main loop
170 | var reversed bool
171 | current := rand.Intn(dim)
172 | child = append(child, current)
173 | clear(current)
174 | for len(child) < dim {
175 | next := -1
176 | shortest := 5
177 | row := table[current]
178 | if len(row) == 0 {
179 | if !reversed {
180 | Reverse(child)
181 | reversed = true
182 | current = child[len(child)-1]
183 | continue
184 | } else {
185 | for next == -1 || Search(child, next) != -1 {
186 | next = rand.Intn(len(table))
187 | }
188 | }
189 | } else {
190 | for i := range row {
191 | if row[i] < 0 {
192 | next = -row[i]
193 | break
194 | } else if len(table[row[i]]) < shortest {
195 | shortest = len(table[row[i]])
196 | next = row[i]
197 | } else if len(table[row[i]]) == shortest {
198 | if rand.Float32() < 0.5 {
199 | next = row[i]
200 | }
201 | }
202 | }
203 | }
204 | reversed = false
205 | child = append(child, next)
206 | clear(next)
207 | current = next
208 | }
209 | }
210 |
--------------------------------------------------------------------------------
/perm/doc.go:
--------------------------------------------------------------------------------
1 | // Package perm provides common operators and helpers for integer permutations.
2 | //
3 | // The crossover operators each take 3 integer slices: the "mother" and "father"
4 | // slices provide the genetic material to be filled into the "child" slice.
5 | // This requires the child slice be allocated by the caller.
6 | package perm
7 |
--------------------------------------------------------------------------------
/perm/mutation.go:
--------------------------------------------------------------------------------
1 | package perm
2 |
3 | import (
4 | "math/rand"
5 | )
6 |
7 | // RandInvert reverses a random slice of the argument.
8 | func RandInvert(gene []int) {
9 | slice, _, _ := RandSlice(gene)
10 | Reverse(slice)
11 | }
12 |
13 | // RandSwap swaps two random elements of the argument.
14 | func RandSwap(gene []int) {
15 | size := len(gene)
16 | i := rand.Intn(size)
17 | j := i
18 | for j == i {
19 | j = rand.Intn(size)
20 | }
21 | gene[i], gene[j] = gene[j], gene[i]
22 | }
23 |
--------------------------------------------------------------------------------
/perm/perm.go:
--------------------------------------------------------------------------------
1 | package perm
2 |
3 | import (
4 | "math/rand"
5 | )
6 |
7 | // New returns a pseudo-random permutation of the integers [0,n). This function
8 | // is an alias for math/rand.Perm.
9 | func New(n int) []int {
10 | return rand.Perm(n)
11 | }
12 |
13 | // RandSlice returns a random slice of the argument along with the boundaries.
14 | // That is to say:
15 | // sub == slice[left:right]
16 | func RandSlice(slice []int) (sub []int, left, right int) {
17 | left = rand.Intn(len(slice))
18 | right = left
19 | for right == left {
20 | right = rand.Intn(len(slice))
21 | }
22 | if right < left {
23 | left, right = right, left
24 | }
25 | return slice[left:right], left, right
26 | }
27 |
28 | // Search searches an int slice for a particular value and returns the index.
29 | // If the value is not found, Search returns -1.
30 | func Search(slice []int, val int) (idx int) {
31 | for idx = range slice {
32 | if slice[idx] == val {
33 | return idx
34 | }
35 | }
36 | return -1
37 | }
38 |
39 | // Reverse reverses an int slice.
40 | func Reverse(slice []int) {
41 | i := 0
42 | j := len(slice) - 1
43 | for i < j {
44 | slice[i], slice[j] = slice[j], slice[i]
45 | i++
46 | j--
47 | }
48 | }
49 |
50 | // Rotate rotates a slice by n positions
51 | func Rotate(slice []int, n int) {
52 | size := len(slice)
53 | for n < 0 {
54 | n += size
55 | }
56 | for n >= size {
57 | n -= size
58 | }
59 | Reverse(slice)
60 | Reverse(slice[:n])
61 | Reverse(slice[n:])
62 | }
63 |
64 | // Validate panics if the argument is not a permutation.
65 | // This can be useful when testing custom operators.
66 | func Validate(slice []int) {
67 | n := len(slice)
68 | for i := 0; i < n; i++ {
69 | if Search(slice, i) == -1 {
70 | panic("invalid permutation")
71 | }
72 | }
73 | }
74 |
--------------------------------------------------------------------------------
/perm/perm_test.go:
--------------------------------------------------------------------------------
1 | package perm_test
2 |
3 | import (
4 | "math/rand"
5 | "testing"
6 |
7 | "github.com/cbarrick/evo/perm"
8 | )
9 |
10 | // validate fails the test if perm is not a permutation
11 | func validate(t *testing.T, perm []int) {
12 | n := len(perm)
13 | for i := 0; i < n; i++ {
14 | found := false
15 | for j := range perm {
16 | if perm[j] == i {
17 | found = true
18 | break
19 | }
20 | }
21 | if !found {
22 | t.Fail()
23 | }
24 | }
25 | }
26 |
27 | // cross.go
28 | // -------------------------
29 |
30 | func TestOrderX(t *testing.T) {
31 | mom := rand.Perm(8)
32 | dad := rand.Perm(8)
33 | child := make([]int, 8)
34 | perm.OrderX(child, mom, dad)
35 | validate(t, child)
36 | }
37 |
38 | func TestPMX(t *testing.T) {
39 | mom := rand.Perm(8)
40 | dad := rand.Perm(8)
41 | child := make([]int, 8)
42 | perm.PMX(child, mom, dad)
43 | validate(t, child)
44 | }
45 |
46 | func TestCycleX(t *testing.T) {
47 | mom := rand.Perm(8)
48 | dad := rand.Perm(8)
49 | child := make([]int, 8)
50 | perm.CycleX(child, mom, dad)
51 | validate(t, child)
52 | }
53 |
54 | func TestEdgeX(t *testing.T) {
55 | mom := rand.Perm(8)
56 | dad := rand.Perm(8)
57 | child := make([]int, 8)
58 | perm.EdgeX(child, mom, dad)
59 | validate(t, child)
60 | }
61 |
62 | // mutation.go
63 | // -------------------------
64 |
65 | func TestRandInvert(t *testing.T) {
66 | a := rand.Perm(8)
67 | b := make([]int, 8)
68 | copy(b, a)
69 | perm.RandInvert(b)
70 | flipped := false
71 | i, j := 0, 7
72 | for {
73 | if j <= i {
74 | if !flipped {
75 | t.Fail()
76 | }
77 | return
78 | } else if a[i] == b[i] {
79 | i++
80 | } else if a[j] == b[j] {
81 | j--
82 | } else {
83 | if flipped {
84 | t.Fail()
85 | return
86 | }
87 | perm.Reverse(b[i : j+1])
88 | flipped = true
89 | }
90 | }
91 | }
92 |
93 | func TestRandSwap(t *testing.T) {
94 | a := rand.Perm(8)
95 | b := make([]int, 8)
96 | copy(b, a)
97 | perm.RandSwap(b)
98 | swapped := false
99 | i, j := 0, 7
100 | for {
101 | if j <= i {
102 | if !swapped {
103 | t.Fail()
104 | }
105 | return
106 | } else if a[i] == b[i] {
107 | i++
108 | } else if a[j] == b[j] {
109 | j--
110 | } else {
111 | if swapped {
112 | t.Fail()
113 | return
114 | }
115 | b[i], b[j] = b[j], b[i]
116 | swapped = true
117 | }
118 | }
119 | }
120 |
121 | // util.go
122 | // -------------------------
123 |
124 | func TestRandSlice(t *testing.T) {
125 | slice := make([]int, 8)
126 | sub, left, right := perm.RandSlice(slice)
127 | sub[0] = 1
128 | sub[len(sub)-1] = 1
129 | if slice[left] != 1 || slice[right-1] != 1 {
130 | t.Fail()
131 | }
132 | }
133 |
134 | func TestSearch(t *testing.T) {
135 | slice := []int{0, 1, 2, 3, 4, 5, 6, 7}
136 | if perm.Search(slice, 7) != 7 {
137 | t.Fail()
138 | }
139 | if perm.Search(slice, 8) != -1 {
140 | t.Fail()
141 | }
142 | }
143 |
144 | func TestReverse(t *testing.T) {
145 | slice := rand.Perm(8)
146 | rev := make([]int, 8)
147 | copy(rev, slice)
148 | perm.Reverse(rev)
149 | for i, j := 0, 7; i < j; i, j = i+1, j-1 {
150 | if slice[i] != rev[j] {
151 | t.Fail()
152 | }
153 | }
154 | }
155 |
156 | func TestValidate(t *testing.T) {
157 | defer func() {
158 | if recover() == nil {
159 | t.Fail()
160 | }
161 | perm.Validate([]int{0, 1, 2, 3})
162 | }()
163 | perm.Validate([]int{0, 0, 1, 2})
164 | }
165 |
--------------------------------------------------------------------------------
/pop/gen/generational.go:
--------------------------------------------------------------------------------
1 | // Package gen provides a traditional generational population.
2 | //
3 | // Generational populations evolve their genomes in generations. Each genome
4 | // is given the entire population as suitors to evolve the next generation. Once
5 | // the new generation is constructed, the old generation is replaced. Each
6 | // genome is evolved in parallel, similar to the textbook master-slave
7 | // parallelism.
8 | package gen
9 |
10 | import (
11 | "math/rand"
12 | "sync"
13 | "time"
14 |
15 | "github.com/cbarrick/evo"
16 | )
17 |
18 | type Population struct {
19 | members []evo.Genome // the individuals, not safe to touch while running
20 | getc chan chan int // used to access members while running
21 | setc chan chan int // used to mutate members while running
22 | valuec chan evo.Genome // sends/receives genomes for get/set
23 | statsc chan chan evo.Stats // used to get stats while running
24 | stopc chan chan struct{} // used to stop the goroutine
25 | }
26 |
27 | // Evolve initiates the optimization in a separate goroutine.
28 | func (pop *Population) Evolve(members []evo.Genome, body evo.EvolveFn) {
29 | pop.members = members
30 | pop.statsc = make(chan chan evo.Stats)
31 | pop.setc = make(chan chan int)
32 | pop.getc = make(chan chan int)
33 | pop.valuec = make(chan evo.Genome)
34 | pop.stopc = make(chan chan struct{}, 1)
35 | go run(*pop, body)
36 | }
37 |
38 | // Stop terminates the evolution loop.
39 | func (pop *Population) Stop() {
40 | ch := make(chan struct{})
41 | pop.stopc <- ch
42 | <-ch
43 | close(pop.statsc)
44 | close(pop.setc)
45 | close(pop.getc)
46 | close(pop.valuec)
47 | }
48 |
49 | // Poll executes a function at some frequency for the duration of the
50 | // current optimization. If the function returns true, the current optimization
51 | // is halted.
52 | func (pop *Population) Poll(freq time.Duration, cond evo.ConditionFn) {
53 | done := pop.stopc
54 | go func() {
55 | for {
56 | select {
57 | case <-time.After(freq):
58 | if cond() {
59 | pop.Stop()
60 | return
61 | }
62 | case ch := <-done:
63 | done <- ch
64 | return
65 | }
66 | }
67 | }()
68 | }
69 |
70 | // Wait blocks until the evolution terminates.
71 | func (pop *Population) Wait() {
72 | pop.stopc <- <-pop.stopc
73 | }
74 |
75 | // Stats returns statistics on the fitness of genomes in the population.
76 | func (pop *Population) Stats() (s evo.Stats) {
77 | statsc := <-pop.statsc
78 | if statsc == nil {
79 | for i := range pop.members {
80 | s = s.Put(pop.members[i].Fitness())
81 | }
82 | return s
83 | }
84 | return <-statsc
85 | }
86 |
87 | // Fitness returns the maximum fitness within the population.
88 | func (pop *Population) Fitness() float64 {
89 | return pop.Stats().Max()
90 | }
91 |
92 | // get returns the ith member of the population.
93 | func (pop *Population) get(i int) (val evo.Genome) {
94 | getter := <-pop.getc
95 | if getter == nil {
96 | val = pop.members[i]
97 | } else {
98 | getter <- i
99 | val = <-pop.valuec
100 | }
101 | return val
102 | }
103 |
104 | // set sets the ith member of the population.
105 | func (pop *Population) set(i int, val evo.Genome) {
106 | setter := <-pop.setc
107 | if setter == nil {
108 | pop.members[i] = val
109 | } else {
110 | setter <- i
111 | pop.valuec <- val
112 | }
113 | }
114 |
115 | // Migrate returns an EvolveFn for using generational populations as genomes.
116 | // The returned migration function exchanges n individuals between the target
117 | // population and one neighboring population. Migration can be slowed down by
118 | // a delay period that occurs before the migration is performed.
119 | //
120 | // The returned migration function can be used to implement an island population
121 | // model where the individuals are divided between some number of generational
122 | // populations, which are themselves linked together into a graph population.
123 | // The generational populations evolve using the user's EvolveFn while the graph
124 | // population evolves using a migration function.
125 | //
126 | // var evolution evo.EvolveFn // the body of the evolution
127 | // var seed []evo.Genome // the initial solutions
128 | // var islands []evo.Genome // the islands
129 | // n := len(seed) / len(islands) // number of solutions per island
130 | //
131 | // for i := range islands {
132 | // var island gen.Population
133 | // island.Evolve(seed[i*n:(i+1)*n], evolution)
134 | // islands[i] = &island
135 | // }
136 | // pop := graph.Ring(len(islands))
137 | // pop.Evolve(islands, gen.Migrate(5, 1*time.Second))
138 | func Migrate(n int, delay time.Duration) evo.EvolveFn {
139 | return func(current evo.Genome, suitors []evo.Genome) evo.Genome {
140 | <-time.After(delay)
141 | var a, b *Population
142 | a = current.(*Population)
143 | for b = a; b == a; {
144 | b = suitors[rand.Intn(len(suitors))].(*Population)
145 | }
146 | for i := 0; i < n; i++ {
147 | ai := rand.Intn(len(a.members))
148 | bi := rand.Intn(len(b.members))
149 | av := a.get(ai)
150 | bv := b.get(bi)
151 | a.set(ai, bv)
152 | b.set(bi, av)
153 | }
154 | return current
155 | }
156 | }
157 |
158 | // run implements the main goroutine.
159 | func run(pop Population, body evo.EvolveFn) {
160 | var (
161 | // drives the main loop
162 | loop = make(chan struct{}, 1)
163 |
164 | // receives the results of evolutions
165 | nextgen = make(chan evo.Genome, len(pop.members))
166 |
167 | // synchronizes pending evolutions
168 | pending sync.WaitGroup
169 |
170 | // used to access/mutate pop.members
171 | getter = make(chan int)
172 | setter = make(chan int)
173 | statsc = make(chan evo.Stats)
174 | )
175 |
176 | for i := range pop.members {
177 | nextgen <- pop.members[i]
178 | }
179 | loop <- struct{}{}
180 |
181 | for {
182 | select {
183 | case <-loop:
184 | for i := range pop.members {
185 | pop.members[i] = <-nextgen
186 | }
187 | pending.Add(len(pop.members))
188 | for i := range pop.members {
189 | val := pop.members[i]
190 | go func() {
191 | nextgen <- body(val, pop.members)
192 | pending.Done()
193 | }()
194 | }
195 | go func() {
196 | pending.Wait()
197 | loop <- struct{}{}
198 | }()
199 |
200 | case pop.getc <- getter:
201 | i := <-getter
202 | pop.valuec <- pop.members[i]
203 |
204 | case pop.setc <- setter:
205 | i := <-setter
206 | pop.members[i] = <-pop.valuec
207 |
208 | case pop.statsc <- statsc:
209 | var s evo.Stats
210 | for i := range pop.members {
211 | s = s.Put(pop.members[i].Fitness())
212 | }
213 | statsc <- s
214 |
215 | case ch := <-pop.stopc:
216 | pending.Wait()
217 | for i := range pop.members {
218 | if subpop, ok := pop.members[i].(evo.Population); ok {
219 | subpop.Stop()
220 | }
221 | }
222 | ch <- struct{}{}
223 | pop.stopc <- ch
224 | return
225 | }
226 | }
227 | }
228 |
--------------------------------------------------------------------------------
/pop/graph/graph.go:
--------------------------------------------------------------------------------
1 | // Package graph provides a spatial population for diffusion and island models.
2 | //
3 | // Graph populations map genomes to nodes in a graph. Each node is evolved in
4 | // parallel, and only sees neighboring nodes as suitors. When used as a
5 | // meta-population, this technique is known as the island model. When used as a
6 | // regular population, it is known as the diffusion model.
7 | package graph
8 |
9 | import (
10 | "time"
11 |
12 | "github.com/cbarrick/evo"
13 | )
14 |
15 | type Graph []node
16 |
17 | type node struct {
18 | val *evo.Genome
19 | peers []*node
20 | getc chan chan evo.Genome
21 | setc chan chan evo.Genome
22 | closec chan chan struct{}
23 | done chan struct{}
24 | }
25 |
26 | // Grid creates a new graph population arranged as a 2D grid.
27 | func Grid(size int) Graph {
28 | width := size << 1
29 | layout := make([][]int, size)
30 | for i := range layout {
31 | layout[i] = make([]int, 4)
32 | layout[i][0] = (i + 1 + size) % size
33 | layout[i][1] = (i - 1 + size) % size
34 | layout[i][2] = (i + width + size) % size
35 | layout[i][3] = (i - width + size) % size
36 | }
37 | return Custom(layout)
38 | }
39 |
40 | // Hypercube creates a new graph population arranged as a hypercube.
41 | func Hypercube(size int) Graph {
42 | var dim uint
43 | for size > (1 << dim) {
44 | dim++
45 | }
46 | layout := make([][]int, size)
47 | for i := 0; i < size; i++ {
48 | layout[i] = make([]int, dim)
49 | for j := range layout[i] {
50 | layout[i][j] = (i ^ (1 << uint(j))) % size
51 | }
52 | }
53 | return Custom(layout)
54 | }
55 |
56 | // Ring creates a new graph population arranged as a ring.
57 | func Ring(size int) Graph {
58 | layout := make([][]int, size)
59 | for i := 0; i < size; i++ {
60 | layout[i] = make([]int, 2)
61 | layout[i][0] = (i - 1 + size) % size
62 | layout[i][0] = (i + 1) % size
63 | }
64 | return Custom(layout)
65 | }
66 |
67 | // Custom creates a new graph population with a custom layout.
68 | // The layout is specified as an adjacency list.
69 | func Custom(layout [][]int) Graph {
70 | g := make([]node, len(layout))
71 | for i := range g {
72 | peers := make([]*node, len(layout[i]))
73 | for j := range layout[i] {
74 | peers[j] = &g[j]
75 | }
76 | g[i].peers = peers
77 | }
78 | return g
79 | }
80 |
81 | // Stats returns statistics on the fitness of genomes in the population.
82 | func (g Graph) Stats() (s evo.Stats) {
83 | for i := range g {
84 | s = s.Put(g[i].get().Fitness())
85 | }
86 | return s
87 | }
88 |
89 | // Fitness returns the maximum fitness within the population.
90 | func (g Graph) Fitness() float64 {
91 | return g.Stats().Max()
92 | }
93 |
94 | // Evolve starts the optimization in a separate goroutine.
95 | func (g Graph) Evolve(members []evo.Genome, body evo.EvolveFn) {
96 | for i := range g {
97 | g[i].val = &members[i]
98 | g[i].getc = make(chan chan evo.Genome)
99 | g[i].setc = make(chan chan evo.Genome)
100 | g[i].closec = make(chan chan struct{}, 1)
101 | }
102 | for i := range g {
103 | go g[i].run(body)
104 | }
105 | }
106 |
107 | // Stop terminates the optimization.
108 | func (g Graph) Stop() {
109 | ch := make(chan struct{})
110 | for i := range g {
111 | g[i].closec <- ch
112 | <-ch
113 | close(g[i].getc)
114 | close(g[i].setc)
115 | }
116 | }
117 |
118 | // Poll executes a function at some frequency for the duration of the
119 | // current optimization. If the function returns true, the current optimization
120 | // is halted.
121 | func (g Graph) Poll(freq time.Duration, cond evo.ConditionFn) {
122 | done := g[0].closec
123 | go func() {
124 | for {
125 | select {
126 | case <-time.After(freq):
127 | if cond() {
128 | g.Stop()
129 | return
130 | }
131 | case ch := <-done:
132 | done <- ch
133 | return
134 | }
135 | }
136 | }()
137 | }
138 |
139 | // Wait blocks until the evolution terminates.
140 | func (g Graph) Wait() {
141 | for i := range g {
142 | g[i].wait()
143 | }
144 | }
145 |
146 | func (n node) wait() {
147 | n.closec <- <-n.closec
148 | }
149 |
150 | // get returns the genome underlying the node.
151 | func (n node) get() evo.Genome {
152 | getter := <-n.getc
153 | if getter == nil {
154 | return *n.val
155 | }
156 | return <-getter
157 | }
158 |
159 | // The main goroutine.
160 | func (n node) run(body evo.EvolveFn) {
161 | var (
162 | // drives the main loop
163 | loop = make(chan struct{}, 1)
164 |
165 | // used to access/mutate the value
166 | getter = make(chan evo.Genome)
167 | setter = make(chan evo.Genome)
168 | )
169 |
170 | loop <- struct{}{}
171 |
172 | for {
173 | select {
174 | case <-loop:
175 | go func() {
176 | suiters := make([]evo.Genome, len(n.peers))
177 | for i := range n.peers {
178 | suiters[i] = n.peers[i].get()
179 | }
180 | setter <- body(*n.val, suiters)
181 | loop <- struct{}{}
182 | }()
183 |
184 | case n.getc <- getter:
185 | getter <- *n.val
186 |
187 | case *n.val = <-setter:
188 |
189 | case ch := <-n.closec:
190 | if subpop, ok := (*n.val).(evo.Population); ok {
191 | subpop.Stop()
192 | }
193 | ch <- struct{}{}
194 | n.closec <- ch
195 | return
196 | }
197 | }
198 | }
199 |
--------------------------------------------------------------------------------
/real/cross.go:
--------------------------------------------------------------------------------
1 | package real
2 |
3 | import (
4 | "math/rand"
5 | )
6 |
7 | // UniformX performs a uniform crossover of some parents into a child.
8 | func UniformX(child Vector, parents ...Vector) {
9 | n := len(parents)
10 | for i := range child {
11 | child[i] = parents[rand.Intn(n)][i]
12 | }
13 | }
14 |
15 | // ArithX performs arithmetic crossover. When the scale is 1, a child is chosen
16 | // uniformly at random from the line segment between the parents. The scale
17 | // affects the length of the segment about the midpoint. Thus when the scale is
18 | // 0, the child is always the midpoint.
19 | func ArithX(scale float64, child, mom, dad Vector) {
20 | // special case when scale == 0, we can find the midpoint in constant space
21 | if scale == 0 {
22 | copy(child, mom)
23 | child.Subtract(dad)
24 | child.Scale(0.5)
25 | child.Add(dad)
26 | return
27 | }
28 |
29 | copy(child, mom)
30 | child.Subtract(dad)
31 | mid := child.Copy()
32 | mid.Scale(0.5)
33 | child.Scale(scale*rand.Float64() - scale/2)
34 | child.Add(dad)
35 | child.Add(mid)
36 | }
37 |
--------------------------------------------------------------------------------
/real/distributions.go:
--------------------------------------------------------------------------------
1 | package real
2 |
3 | import (
4 | "math"
5 | "math/rand"
6 | )
7 |
8 | func Normal(stdv float64) float64 {
9 | return stdv * rand.NormFloat64()
10 | }
11 |
12 | func Lognormal(rate float64) float64 {
13 | return math.Exp(Normal(rate))
14 | }
15 |
--------------------------------------------------------------------------------
/real/evostrat.go:
--------------------------------------------------------------------------------
1 | package real
2 |
3 | import (
4 | "math"
5 | )
6 |
7 | // Adapt performs a lognormal scaling of the vector using a global learning
8 | // rate of 1/sqrt(n) and a local learning rate of 1/sqrt(2*sqrt(n)). This is
9 | // commonly used in evolution strategies to learn the strategy parameters.
10 | func (v Vector) Adapt() {
11 | n := float64(len(v))
12 | globalrate := 1 / math.Sqrt(n)
13 | localrate := 1 / math.Sqrt(2*math.Sqrt(n))
14 | global := Lognormal(globalrate)
15 | for i := range v {
16 | v[i] *= Lognormal(localrate) * global
17 | }
18 | }
19 |
20 | // Step performs a gausian purterbation of the vector using position-wise
21 | // step-sizes. This is commonly used in evolution strategies to mutate the
22 | // object parameters, using the strategy parameters as the step-sizes.
23 | func (v Vector) Step(steps Vector) {
24 | for i := range v {
25 | v[i] += Normal(steps[i])
26 | }
27 | }
28 |
--------------------------------------------------------------------------------
/real/real_test.go:
--------------------------------------------------------------------------------
1 | package real_test
2 |
3 | import (
4 | "math"
5 | "testing"
6 |
7 | "github.com/cbarrick/evo"
8 | "github.com/cbarrick/evo/real"
9 | )
10 |
11 | // cross.go
12 | // -------------------------
13 |
14 | func TestUniformX(t *testing.T) {
15 | mom := real.Random(8, 1)
16 | dad := real.Random(8, 1)
17 | child := make([]float64, 8)
18 | real.UniformX(child, mom, dad)
19 | for i := range child {
20 | if child[i] != mom[i] && child[i] != dad[i] {
21 | t.Fail()
22 | }
23 | }
24 | }
25 |
26 | func TestArithX(t *testing.T) {
27 | mom := []float64{0, 0}
28 | dad := []float64{1, -1}
29 | child := []float64{0, 0}
30 | real.ArithX(1, child, mom, dad)
31 | a := 0 < child[0] && child[0] < 1
32 | b := -1 < child[1] && child[1] < 0
33 | c := child[0] == -child[1]
34 | if !a || !b || !c {
35 | t.Fail()
36 | }
37 | }
38 |
39 | // distributions.go
40 | // -------------------------
41 |
42 | func TestNormal(t *testing.T) {
43 | var s evo.Stats
44 | for i := 0; i < 65536; i++ {
45 | x := real.Normal(1e-3)
46 | s = s.Put(x)
47 | }
48 | mean := s.Mean()
49 | if mean < -1e-3 || 1e-3 < mean || math.IsNaN(mean) {
50 | t.Fail()
51 | }
52 | }
53 |
54 | func TestLognormal(t *testing.T) {
55 | var s evo.Stats
56 | for i := 0; i < 65536; i++ {
57 | x := math.Log(real.Lognormal(1e-3))
58 | s = s.Put(x)
59 | }
60 | mean := s.Mean()
61 | if mean < -1e-3 || 1e-3 < mean || math.IsNaN(mean) {
62 | t.Fail()
63 | }
64 | }
65 |
66 | // evostrat.go
67 | // -------------------------
68 |
69 | func TestAdapt(t *testing.T) {
70 | x := real.Random(8, 1)
71 | y := x.Copy()
72 | y.Adapt()
73 | for i := range x {
74 | if x[i] == y[i] {
75 | t.Fail()
76 | }
77 | }
78 | }
79 |
80 | func TestStep(t *testing.T) {
81 | x := make(real.Vector, 8)
82 | x.Step(real.Vector{1, 1, 1, 1, 1, 1, 1, 1})
83 | for i := range x {
84 | if x[i] < -3 || 3 < x[i] {
85 | t.Fail()
86 | }
87 | }
88 | }
89 |
90 | // vector.go
91 | // -------------------------
92 |
93 | func TestRandom(t *testing.T) {
94 | x := real.Random(8, 1)
95 | if len(x) != 8 {
96 | t.Fail()
97 | return
98 | }
99 | for i := range x {
100 | if x[i] < 0 || 1 < x[i] {
101 | t.Fail()
102 | }
103 | }
104 | }
105 |
106 | func TestCopy(t *testing.T) {
107 | x := real.Random(8, 1)
108 | y := x.Copy()
109 | for i := range x {
110 | if x[i] != y[i] {
111 | t.Fail()
112 | }
113 | }
114 | x[0] = 0
115 | if x[0] == y[0] {
116 | t.Fail()
117 | }
118 | }
119 |
120 | func TestAdd(t *testing.T) {
121 | x := real.Random(8, 1)
122 | y := real.Random(8, 1)
123 | z := x.Copy()
124 | z.Add(y)
125 | for i := range z {
126 | if z[i] != x[i]+y[i] {
127 | t.Fail()
128 | }
129 | }
130 | }
131 |
132 | func TestSubtract(t *testing.T) {
133 | x := real.Random(8, 1)
134 | y := real.Random(8, 1)
135 | z := x.Copy()
136 | z.Subtract(y)
137 | for i := range z {
138 | if z[i] != x[i]-y[i] {
139 | t.Fail()
140 | }
141 | }
142 | }
143 |
144 | func TestScale(t *testing.T) {
145 | x := real.Random(8, 1)
146 | y := x.Copy()
147 | y.Scale(3)
148 | for i := range y {
149 | if y[i] != x[i]*3 {
150 | t.Fail()
151 | }
152 | }
153 | }
154 |
155 | func TestHighBound(t *testing.T) {
156 | x := real.Vector{1, 3}
157 | x.HighBound(2)
158 | if x[0] != 1 || x[1] != 2 {
159 | t.Fail()
160 | }
161 | }
162 |
163 | func TestLowBound(t *testing.T) {
164 | x := real.Vector{1, 3}
165 | x.LowBound(2)
166 | if x[0] != 2 || x[1] != 3 {
167 | t.Fail()
168 | }
169 | }
170 |
171 | func TestBound(t *testing.T) {
172 | x := real.Vector{1, 4}
173 | x.Bound(real.Vector{2, 2}, real.Vector{3, 3})
174 | if x[0] != 2 || x[1] != 3 {
175 | t.Fail()
176 | }
177 | }
178 |
--------------------------------------------------------------------------------
/real/vector.go:
--------------------------------------------------------------------------------
1 | package real
2 |
3 | import (
4 | "math/rand"
5 | )
6 |
7 | type Vector []float64
8 |
9 | // Random generates a random vector of length n. Values are taken uniformly
10 | // between [0,scale).
11 | func Random(n int, scale float64) (v Vector) {
12 | v = make(Vector, n)
13 | for i := range v {
14 | v[i] = rand.Float64() * scale
15 | }
16 | return v
17 | }
18 |
19 | func (v Vector) Copy() Vector {
20 | w := make(Vector, len(v))
21 | copy(w, v)
22 | return w
23 | }
24 |
25 | func (v Vector) Add(w Vector) Vector {
26 | for i := range v {
27 | v[i] += w[i]
28 | }
29 | return v
30 | }
31 |
32 | func (v Vector) Subtract(w Vector) Vector {
33 | for i := range v {
34 | v[i] -= w[i]
35 | }
36 | return v
37 | }
38 |
39 | func (v Vector) Scale(s float64) Vector {
40 | for i := range v {
41 | v[i] *= s
42 | }
43 | return v
44 | }
45 |
46 | func (v Vector) LowBound(min float64) Vector {
47 | for i := range v {
48 | if v[i] < min {
49 | v[i] = min
50 | }
51 | }
52 | return v
53 | }
54 |
55 | func (v Vector) HighBound(max float64) Vector {
56 | for i := range v {
57 | if v[i] > max {
58 | v[i] = max
59 | }
60 | }
61 | return v
62 | }
63 |
64 | func (v Vector) Bound(lower, upper Vector) Vector {
65 | for i := range v {
66 | if v[i] > upper[i] {
67 | v[i] = upper[i]
68 | }
69 | if v[i] < lower[i] {
70 | v[i] = lower[i]
71 | }
72 | }
73 | return v
74 | }
75 |
--------------------------------------------------------------------------------
/sel/doc.go:
--------------------------------------------------------------------------------
1 | // Package sel provides helpers for different selection techniques.
2 | //
3 | // Selection helpers come in two varieties, function selectors and pool
4 | // selectors. Function selectors are simply functions that take some number of
5 | // genomes as "competitors" and return one or more "winners" from the input.
6 | //
7 | // Pool selectors allow many goroutines to contribute competitors and for the
8 | // winners to be retrieved individually. Once all the winners are retrieved,
9 | // the pool is reset for another round of competition.
10 | package sel
11 |
--------------------------------------------------------------------------------
/sel/elite.go:
--------------------------------------------------------------------------------
1 | package sel
2 |
3 | import (
4 | "sort"
5 |
6 | "github.com/cbarrick/evo"
7 | )
8 |
9 | // An elcomp competes in an elite tournament.
10 | type elcomp struct {
11 | evo.Genome
12 | fit float64
13 | }
14 |
15 | // Elcomps implements the sort interface in descending order by fitness.
16 | type elcomps []elcomp
17 |
18 | func (h elcomps) Len() int { return len(h) }
19 | func (h elcomps) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
20 | func (h elcomps) Less(i, j int) bool { return h[i].fit > h[j].fit }
21 |
22 | // Sort (re)evaluates the fitness of each competitor and sorts them.
23 | // Fitness evaluation is probably expensive, so we do it in parallel.
24 | func (pool elcomps) sort() {
25 | done := make(chan struct{})
26 | for i := range pool {
27 | go func(i int) {
28 | pool[i].fit = pool[i].Genome.Fitness()
29 | done <- struct{}{}
30 | }(i)
31 | }
32 | for _ = range pool {
33 | <-done
34 | }
35 | sort.Sort(pool)
36 | }
37 |
38 | // Elite returns the µ genomes with the best fitness.
39 | func Elite(µ int, genomes ...evo.Genome) (winners []evo.Genome) {
40 | winners = make([]evo.Genome, µ)
41 | pool := make(elcomps, len(genomes))
42 | for i := range genomes {
43 | pool[i] = elcomp{genomes[i], 0}
44 | }
45 | pool.sort()
46 | for i := range winners {
47 | winners[i] = pool[i].Genome
48 | }
49 | return winners
50 | }
51 |
52 | // ElitePool creates an elite pool selector. Once λ competitors have been put
53 | // into the pool, they are sorted by fitness. The best µ competitors must then
54 | // be retrieved from the pool. Once the winners are retrieved, the pool starts
55 | // accepting competitors for another tournamnent.
56 | func ElitePool(µ, λ int) Pool {
57 | var p Pool
58 | p.in = make(chan evo.Genome)
59 | p.out = make(chan evo.Genome, µ)
60 | p.close = make(chan chan struct{})
61 |
62 | go func() {
63 | // the competitors, memory shared accross iterations
64 | pool := make(elcomps, 0, λ)
65 |
66 | for {
67 | // wait to receive all competitors
68 | for len(pool) < λ {
69 | select {
70 | case ch := <-p.close:
71 | ch <- struct{}{}
72 | return
73 |
74 | case val := <-p.in:
75 | // we only add the competitor to the pool
76 | // we do _not_ compute the fitness yet
77 | pool = append(pool, elcomp{val, 0})
78 | }
79 | }
80 |
81 | // we sort the pool by fitness
82 | // this evaluates the fitness of each member for the first time
83 | pool.sort()
84 |
85 | // send out the most fit µ genomes
86 | pool = pool[:µ]
87 | for i := range pool {
88 | select {
89 | case ch := <-p.close:
90 | ch <- struct{}{}
91 | return
92 |
93 | case p.out <- pool[i].Genome:
94 | }
95 | }
96 | pool = pool[:0]
97 | }
98 | }()
99 |
100 | return p
101 | }
102 |
--------------------------------------------------------------------------------
/sel/interface.go:
--------------------------------------------------------------------------------
1 | package sel
2 |
3 | import (
4 | "github.com/cbarrick/evo"
5 | )
6 |
7 | // Pool selectors allow many goroutines to contribute competitors to a selection
8 | // process. Pool selectors reset after each competition and must be closed when
9 | // they are no longer needed.
10 | type Pool struct {
11 | in chan evo.Genome
12 | out chan evo.Genome
13 | close chan chan struct{}
14 | }
15 |
16 | // Put adds a competitor to the pool.
17 | // Put blocks until all winners of the previous competition have been retrieved.
18 | func (p Pool) Put(val evo.Genome) {
19 | p.in <- val
20 | }
21 |
22 | // Get retrieves a winner from the most current competition.
23 | // Get blocks until all competitors have been added.
24 | func (p Pool) Get() (val evo.Genome) {
25 | val = <-p.out
26 | return val
27 | }
28 |
29 | // Close stops the pool selector.
30 | func (p Pool) Close() {
31 | ch := make(chan struct{})
32 | p.close <- ch
33 | <-ch
34 | }
35 |
--------------------------------------------------------------------------------
/sel/round_robin.go:
--------------------------------------------------------------------------------
1 | package sel
2 |
3 | import (
4 | "math"
5 | "math/rand"
6 | "sort"
7 |
8 | "github.com/cbarrick/evo"
9 | )
10 |
11 | // A dummy is used as the opponent in the bye of an odd tournament
12 | type dummy struct{}
13 |
14 | func (d dummy) Evolve(_ ...evo.Genome) evo.Genome { return dummy{} }
15 | func (d dummy) Fitness() float64 { return math.Inf(-1) }
16 | func (d dummy) Close() {}
17 |
18 | // An rrcomp competes in a round-robin tournament.
19 | type rrcomp struct {
20 | evo.Genome
21 | wins int
22 | }
23 |
24 | // rrcomps implements the sort interface in descending order by wins
25 | type rrcomps []rrcomp
26 |
27 | func (h rrcomps) Len() int { return len(h) }
28 | func (h rrcomps) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
29 | func (h rrcomps) Less(i, j int) bool { return h[i].wins > h[j].wins }
30 |
31 | // tourney performs a concurrent round-robin tournament.
32 | // pool becomes sorted by score.
33 | func (pool rrcomps) tourney(rounds int) {
34 | var (
35 | size = len(pool) // the size of the tournament
36 | half = size / 2 // half that
37 | tcount = rounds * half // number of tournaments
38 | sched = rand.Perm(len(pool)) // the tournamnent schedule
39 | winners = make(chan int) // communicates the winners
40 | )
41 |
42 | if size%2 != 0 {
43 | panic("odd size round-robin")
44 | }
45 |
46 | // run returns the best competitor among indices i and j
47 | // sends the index of the winner over winners
48 | run := func(i, j int) {
49 | if pool[i].Fitness() < pool[j].Fitness() {
50 | winners <- j
51 | } else {
52 | winners <- i
53 | }
54 | }
55 |
56 | // for each round, start the tournament according to the schedule
57 | // then rotate the schedule, keeping one element in place, and repeat
58 | for round := 0; round < rounds; round++ {
59 | for i := 0; i < half; i++ {
60 | go run(sched[i], sched[size-1-i])
61 | }
62 | carry := sched[0]
63 | for i := range sched[:size-1] {
64 | sched[i] = sched[i+1]
65 | }
66 | sched[size-2] = carry
67 | }
68 |
69 | // wait for all competitions to end and keep score
70 | for i := 0; i < tcount; i++ {
71 | j := <-winners
72 | pool[j].wins++
73 | }
74 |
75 | // finally, sort by score
76 | sort.Sort(pool)
77 | }
78 |
79 | // RoundRobin returns the µ best genomes after some rounds of a tournament.
80 | func RoundRobin(µ, rounds int, genomes ...evo.Genome) (winners []evo.Genome) {
81 | pool := make(rrcomps, 0, len(genomes)+1)
82 | for i := range genomes {
83 | pool = append(pool, rrcomp{genomes[i], 0})
84 | }
85 | if len(pool)%2 != 0 {
86 | pool = append(pool, rrcomp{dummy{}, -1})
87 | }
88 | pool.tourney(rounds)
89 | winners = make([]evo.Genome, µ)
90 | for i := range winners {
91 | winners[i] = pool[i].Genome
92 | }
93 | return winners
94 | }
95 |
96 | // RoundRobinPool creates a round-robin pool selector. Once λ competitors
97 | // have been put into the pool, the tournamnet is performed. The best µ
98 | // competitors must then be retrieved from the pool. Once the winners are
99 | // retrieved, the pool starts accepting competitors for another tournamnent.
100 | func RoundRobinPool(µ, λ, rounds int) Pool {
101 | var p Pool
102 | p.in = make(chan evo.Genome)
103 | p.out = make(chan evo.Genome)
104 | p.close = make(chan chan struct{})
105 |
106 | go func() {
107 | // the competitors, memory shared accross iterations
108 | pool := make(rrcomps, 0, λ+(λ%2))
109 |
110 | for {
111 | // wait to receive all competitors
112 | for len(pool) < λ {
113 | select {
114 | case ch := <-p.close:
115 | ch <- struct{}{}
116 | return
117 |
118 | case val := <-p.in:
119 | pool = append(pool, rrcomp{val, 0})
120 | }
121 | }
122 |
123 | // do the tournament
124 | if λ%2 != 0 {
125 | pool = append(pool, rrcomp{dummy{}, -1})
126 | }
127 | pool.tourney(rounds)
128 |
129 | // send out the µ genomes that won the most
130 | pool = pool[:µ]
131 | for i := range pool {
132 | select {
133 | case ch := <-p.close:
134 | ch <- struct{}{}
135 | return
136 |
137 | case p.out <- pool[i].Genome:
138 | }
139 | }
140 | pool = pool[:0]
141 | }
142 | }()
143 |
144 | return p
145 | }
146 |
--------------------------------------------------------------------------------
/sel/sel_test.go:
--------------------------------------------------------------------------------
1 | package sel_test
2 |
3 | import (
4 | "testing"
5 |
6 | "github.com/cbarrick/evo"
7 | "github.com/cbarrick/evo/sel"
8 | )
9 |
10 | type dummy float64
11 |
12 | func (d dummy) Evolve(_ ...evo.Genome) evo.Genome { return d }
13 | func (d dummy) Fitness() float64 { return float64(d) }
14 | func (d dummy) Close() {}
15 |
16 | func dummies() []evo.Genome {
17 | return []evo.Genome{
18 | dummy(1),
19 | dummy(2),
20 | dummy(3),
21 | dummy(4),
22 | dummy(5),
23 | dummy(6),
24 | dummy(7),
25 | dummy(8),
26 | dummy(9),
27 | dummy(0),
28 | }
29 | }
30 |
31 | func search(ds []evo.Genome, d float64) bool {
32 | for i := range ds {
33 | if ds[i].(dummy) == dummy(d) {
34 | return true
35 | }
36 | }
37 | return false
38 | }
39 |
40 | // elite.go
41 | // -------------------------
42 |
43 | func TestElite(t *testing.T) {
44 | pop := dummies()
45 | elite := sel.Elite(5, pop...)
46 | ok := search(elite, 9) &&
47 | search(elite, 8) &&
48 | search(elite, 7) &&
49 | search(elite, 6) &&
50 | search(elite, 5)
51 | if !ok {
52 | t.Fail()
53 | }
54 | }
55 |
56 | func TestElitePool(t *testing.T) {
57 | pop := dummies()
58 | pool := sel.ElitePool(5, 10)
59 | for i := range pop {
60 | pool.Put(pop[i])
61 | }
62 | for i := dummy(9); 4 < i; i-- {
63 | if pool.Get().(dummy) != i {
64 | t.Fail()
65 | return
66 | }
67 | }
68 | }
69 |
70 | // round_robin.go
71 | // -------------------------
72 |
73 | func TestRoundRobin(t *testing.T) {
74 | pop := dummies()
75 | elite := sel.RoundRobin(5, 10, pop...)
76 | ok := search(elite, 9) &&
77 | search(elite, 8) &&
78 | search(elite, 7) &&
79 | search(elite, 6) &&
80 | search(elite, 5)
81 | if !ok {
82 | t.Fail()
83 | }
84 | }
85 |
86 | func TestRoundRobinPool(t *testing.T) {
87 | pop := dummies()
88 | pool := sel.RoundRobinPool(5, 10, 10)
89 | for i := range pop {
90 | pool.Put(pop[i])
91 | }
92 | for i := dummy(9); 4 < i; i-- {
93 | if pool.Get().(dummy) != i {
94 | t.Fail()
95 | return
96 | }
97 | }
98 | }
99 |
100 | // tournament.go
101 | // -------------------------
102 |
103 | func TestTournament(t *testing.T) {
104 | pop := dummies()
105 | winner := sel.Tournament(pop...)
106 | if winner != dummy(9) {
107 | t.Fail()
108 | }
109 | }
110 |
111 | func TestBinaryTournament(t *testing.T) {
112 | var stats evo.Stats
113 | pop := dummies()
114 | for i := 0; i < 1e6; i++ {
115 | winner := sel.BinaryTournament(pop...).(dummy)
116 | stats = stats.Put(float64(winner))
117 | }
118 | if stats.Mean() < 5.5 || 6.5 < stats.Mean() {
119 | t.Fail()
120 | }
121 | }
122 |
--------------------------------------------------------------------------------
/sel/tournament.go:
--------------------------------------------------------------------------------
1 | package sel
2 |
3 | import (
4 | "math"
5 | "math/rand"
6 |
7 | "github.com/cbarrick/evo"
8 | )
9 |
10 | // Tournament returns the most fit suitor.
11 | func Tournament(suitors ...evo.Genome) (best evo.Genome) {
12 | var fit, bestfit float64
13 | bestfit = math.Inf(-1)
14 | for i := range suitors {
15 | fit = suitors[i].Fitness()
16 | if fit > bestfit {
17 | bestfit = fit
18 | best = suitors[i]
19 | }
20 | }
21 | return best
22 | }
23 |
24 | // BinaryTournament randomly chooses two suitors and returns the most fit.
25 | func BinaryTournament(suitors ...evo.Genome) evo.Genome {
26 | var x, y, size int
27 | size = len(suitors)
28 | if size > 2 {
29 | x = rand.Intn(size)
30 | y = x
31 | for y == x {
32 | y = rand.Intn(size)
33 | }
34 | } else {
35 | x, y = 0, 1
36 | }
37 | if suitors[x].Fitness() < suitors[y].Fitness() {
38 | return suitors[y]
39 | }
40 | return suitors[x]
41 | }
42 |
--------------------------------------------------------------------------------
/stats.go:
--------------------------------------------------------------------------------
1 | package evo
2 |
3 | import (
4 | "fmt"
5 | "math"
6 | )
7 |
8 | // A Stats object is a statistics collector. A common source of Stats objects is
9 | // the return value of Population.Stats() which gives statistics about the
10 | // fitness of genomes in the population.
11 | type Stats struct {
12 | max, min float64
13 | mean float64
14 | sumsq float64 // sum of squares of deviation from the mean
15 | count float64
16 | }
17 |
18 | // Put inserts a new value into the data.
19 | func (s Stats) Put(x float64) Stats {
20 | if s.count == 0 {
21 | s.max = math.Inf(-1)
22 | s.min = math.Inf(+1)
23 | }
24 |
25 | delta := x - s.mean
26 | newcount := s.count + 1
27 |
28 | // max & min
29 | s.max = math.Max(s.max, x)
30 | s.min = math.Min(s.min, x)
31 |
32 | // mean
33 | s.mean += delta / newcount
34 |
35 | // sum of squares
36 | s.sumsq += delta * delta * (s.count / newcount)
37 |
38 | // count
39 | s.count = newcount
40 |
41 | return s
42 | }
43 |
44 | // Merge merges the data of two Stats objects.
45 | func (s Stats) Merge(t Stats) Stats {
46 | if s.count == 0 {
47 | s.max = math.Inf(-1)
48 | s.min = math.Inf(+1)
49 | }
50 |
51 | delta := t.mean - s.mean
52 | newcount := t.count + s.count
53 |
54 | // max & min
55 | s.max = math.Max(s.max, t.max)
56 | s.min = math.Min(s.min, t.min)
57 |
58 | // mean
59 | s.mean += delta * (t.count / newcount)
60 |
61 | // sum of squares
62 | s.sumsq += t.sumsq
63 | s.sumsq += delta * delta * (t.count * s.count / newcount)
64 |
65 | // count
66 | s.count = newcount
67 |
68 | return s
69 | }
70 |
71 | // Max returns the maximum data point.
72 | func (s Stats) Max() float64 {
73 | return s.max
74 | }
75 |
76 | // Min returns the minimum data point.
77 | func (s Stats) Min() float64 {
78 | return s.min
79 | }
80 |
81 | // Range returns the difference in the maximum and minimum data points.
82 | func (s Stats) Range() float64 {
83 | return s.max - s.min
84 | }
85 |
86 | // Mean returns the average of the data.
87 | func (s Stats) Mean() float64 {
88 | return s.mean
89 | }
90 |
91 | // Var returns the population variance of the data.
92 | func (s Stats) Var() float64 {
93 | return s.sumsq / s.count
94 | }
95 |
96 | // SD returns the population standard deviation of the data.
97 | func (s Stats) SD() float64 {
98 | return math.Sqrt(s.sumsq / s.count)
99 | }
100 |
101 | // RSD returns the population relative standard deviation of the data, also
102 | // known as the coefficient of variation.
103 | func (s Stats) RSD() float64 {
104 | return s.SD() / s.Mean()
105 | }
106 |
107 | // Count returns the size of the data.
108 | func (s Stats) Count() int {
109 | return int(s.count)
110 | }
111 |
112 | // String returns a string listing a summary of the statistics.
113 | func (s Stats) String() string {
114 | return fmt.Sprintf("Max: %f | Min: %f | SD: %f",
115 | s.Max(),
116 | s.Min(),
117 | s.SD())
118 | }
119 |
--------------------------------------------------------------------------------
/stats_test.go:
--------------------------------------------------------------------------------
1 | package evo_test
2 |
3 | import (
4 | "testing"
5 |
6 | "github.com/cbarrick/evo"
7 | )
8 |
9 | func TestMerge(t *testing.T) {
10 | var a, b evo.Stats
11 | for i := float64(0); i < 5; i++ {
12 | a = a.Put(i)
13 | }
14 | for i := float64(5); i < 10; i++ {
15 | b = b.Put(i)
16 | }
17 | stats := a.Merge(b)
18 | if stats.Mean() != 4.5 {
19 | t.Fail()
20 | }
21 | if stats.Var() != 8.25 {
22 | t.Fail()
23 | }
24 | }
25 |
26 | func TestMax(t *testing.T) {
27 | stats := data()
28 | if stats.Max() != 855 {
29 | t.Fail()
30 | }
31 | }
32 |
33 | func TestMin(t *testing.T) {
34 | stats := data()
35 | if stats.Min() != 760 {
36 | t.Fail()
37 | }
38 | }
39 |
40 | func TestRange(t *testing.T) {
41 | stats := data()
42 | if stats.Range() != 95 {
43 | t.Fail()
44 | }
45 | }
46 |
47 | func TestMean(t *testing.T) {
48 | stats := data()
49 | if stats.Mean() < 810.1388888 || 810.1388890 < stats.Mean() {
50 | t.Fail()
51 | }
52 | }
53 |
54 | func TestVar(t *testing.T) {
55 | stats := data()
56 | if stats.Var() < 829.841820 || 829.841822 < stats.Var() {
57 | t.Fail()
58 | }
59 | }
60 |
61 | func TestSD(t *testing.T) {
62 | stats := data()
63 | if stats.SD() < 28.80697520 || 28.80697522 < stats.SD() {
64 | t.Fail()
65 | }
66 | }
67 |
68 | func TestRSD(t *testing.T) {
69 | stats := data()
70 | if stats.RSD() < 0.03555806986 || 0.03555806988 < stats.RSD() {
71 | t.Fail()
72 | }
73 | }
74 |
75 | func TestCount(t *testing.T) {
76 | stats := data()
77 | if stats.Count() != 36 {
78 | t.Fail()
79 | }
80 | }
81 |
82 | func data() (s evo.Stats) {
83 | s = s.Put(810)
84 | s = s.Put(820)
85 | s = s.Put(820)
86 | s = s.Put(840)
87 | s = s.Put(840)
88 | s = s.Put(845)
89 | s = s.Put(785)
90 | s = s.Put(790)
91 | s = s.Put(785)
92 | s = s.Put(835)
93 | s = s.Put(835)
94 | s = s.Put(835)
95 | s = s.Put(845)
96 | s = s.Put(855)
97 | s = s.Put(850)
98 | s = s.Put(760)
99 | s = s.Put(760)
100 | s = s.Put(770)
101 | s = s.Put(820)
102 | s = s.Put(820)
103 | s = s.Put(820)
104 | s = s.Put(820)
105 | s = s.Put(820)
106 | s = s.Put(825)
107 | s = s.Put(775)
108 | s = s.Put(775)
109 | s = s.Put(775)
110 | s = s.Put(825)
111 | s = s.Put(825)
112 | s = s.Put(825)
113 | s = s.Put(815)
114 | s = s.Put(825)
115 | s = s.Put(825)
116 | s = s.Put(770)
117 | s = s.Put(760)
118 | s = s.Put(765)
119 | return s
120 | }
121 |
--------------------------------------------------------------------------------