├── .gitignore
├── LICENSE
├── MANIFEST.in
├── README.rst
├── doc
├── .gitignore
├── examples
│ ├── quickstart.hires.png
│ ├── quickstart.pdf
│ ├── quickstart.png
│ └── quickstart.py
└── source
│ ├── conf.py
│ ├── control.rst
│ ├── disturbances.rst
│ ├── emulator.rst
│ ├── index.rst
│ ├── installation.rst
│ ├── mpc.rst
│ ├── prediction.rst
│ ├── quickstart.rst
│ ├── reference.rst
│ └── stateestimation.rst
├── examples
├── .gitignore
├── __init__.py
├── quickstart.py
└── simple_space_heating_mpc.py
├── mpcpy
├── __init__.py
├── __version__.py
├── control.py
├── disturbances.py
├── emulator.py
├── mpc.py
├── prediction.py
└── stateestimation.py
├── setup.py
└── tests
├── .gitignore
├── __init__.py
├── all.py
├── boundaryconditions.py
├── data
└── example.mo
├── emulator.py
├── examples.py
├── prediction.py
└── stateestimation.py
/.gitignore:
--------------------------------------------------------------------------------
1 | *.pyc
2 | mpcpy.egg-info
3 | dist
4 | build
5 | env
6 | .idea
7 |
--------------------------------------------------------------------------------
/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 | .
--------------------------------------------------------------------------------
/MANIFEST.in:
--------------------------------------------------------------------------------
1 | include README.rst
2 | include LICENSE
3 | include examples/simple_space_heating_mpc.ipynb
4 | include examples/cplex_api.ipynb
--------------------------------------------------------------------------------
/README.rst:
--------------------------------------------------------------------------------
1 | mpcpy
2 | -----
3 |
4 | A group of classes to run Model Predictive Control (MPC) simulations using python.
5 |
6 | Installation
7 | ============
8 |
9 | Prequisites
10 | ^^^^^^^^^^^
11 |
12 | * `numpy`
13 |
14 |
15 | Setup
16 | ^^^^^
17 |
18 | Install via pip::
19 |
20 | pip install mpcpy
21 |
22 | Or:
23 |
24 | * download a `release `_
25 | * unzip and cd to the folder
26 | * run ``python setup.py install``
27 |
28 |
29 | Examples
30 | ========
31 |
32 | In the examples folder some documented examples of how to work with mpcpy are available as IPython Notebooks.
33 |
34 | This example should get you started with mpcpy
35 |
36 | * `Simple space heating mpc `_
37 |
--------------------------------------------------------------------------------
/doc/.gitignore:
--------------------------------------------------------------------------------
1 | build
--------------------------------------------------------------------------------
/doc/examples/quickstart.hires.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/BrechtBa/mpcpy/108b7a19bc07f17b1fae30ee8ecfdd1e732c1c47/doc/examples/quickstart.hires.png
--------------------------------------------------------------------------------
/doc/examples/quickstart.pdf:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/BrechtBa/mpcpy/108b7a19bc07f17b1fae30ee8ecfdd1e732c1c47/doc/examples/quickstart.pdf
--------------------------------------------------------------------------------
/doc/examples/quickstart.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/BrechtBa/mpcpy/108b7a19bc07f17b1fae30ee8ecfdd1e732c1c47/doc/examples/quickstart.png
--------------------------------------------------------------------------------
/doc/examples/quickstart.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | ################################################################################
3 | # Copyright 2015 Brecht Baeten
4 | # This file is part of mpcpy.
5 | #
6 | # mpcpy is free software: you can redistribute it and/or modify
7 | # it under the terms of the GNU General Public License as published by
8 | # the Free Software Foundation, either version 3 of the License, or
9 | # (at your option) any later version.
10 | #
11 | # mpcpy is distributed in the hope that it will be useful,
12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | # GNU General Public License for more details.
15 | #
16 | # You should have received a copy of the GNU General Public License
17 | # along with mpcpy. If not, see .
18 | ################################################################################
19 |
20 | import numpy as np
21 | import matplotlib.pyplot as plt
22 |
23 | import mpcpy
24 | import pyomo.environ as pyomo
25 |
26 |
27 | # Define an emulator class
28 | class Emulator(mpcpy.Emulator):
29 | """
30 | A custom system emulator
31 | """
32 | def simulate(self, starttime, stoptime, input):
33 | dt = 1
34 | time = np.arange(starttime, stoptime+dt, dt, dtype=np.float)
35 |
36 | # initialize
37 | x = np.ones_like(time)*self.res['x'][-1]
38 |
39 | # interpolate inputs
40 | u = np.interp(time, input['time'], input['u'])
41 | d = np.interp(time, input['time'], input['d'])
42 |
43 | # perform simulation
44 | for i, t in enumerate(time[:-1]):
45 | # dx/dt = A*x + d + u
46 | x[i+1] = x[i] + (self.parameters['A']*x[i] + d[i] + u[i])*dt
47 |
48 | # create and return a results dict
49 | res = {
50 | 'time': time,
51 | 'x': x,
52 | 'd': d,
53 | 'u': u,
54 | }
55 |
56 | return res
57 |
58 |
59 | # Define a control class
60 | class SetpointControl(mpcpy.Control):
61 | """
62 | A control to keep the state as close to a set point as possible
63 | """
64 | def formulation(self):
65 | # create a pyomo model
66 | model = pyomo.AbstractModel()
67 |
68 | model.i = pyomo.Set()
69 | model.ip = pyomo.Set()
70 |
71 | model.time = pyomo.Param(model.ip)
72 | model.d = pyomo.Param(model.ip, initialize=0.)
73 | model.x = pyomo.Var(model.ip, domain=pyomo.Reals, initialize=0.)
74 | model.u = pyomo.Var(model.ip, domain=pyomo.NonNegativeReals, bounds=(0., 1.), initialize=0.)
75 |
76 | model.x0 = pyomo.Param(initialize=0.)
77 |
78 | model.initialcondition = pyomo.Constraint(
79 | rule=lambda model: model.x[0] == model.x0
80 | )
81 |
82 | model.constraint = pyomo.Constraint(
83 | model.i,
84 | rule=lambda model, i: (model.x[i+1]-model.x[i])/(model.time[i+1]-model.time[i]) ==
85 | self.parameters['A']*model.x[i] + model.d[i] + model.u[i]
86 | )
87 |
88 | model.objective = pyomo.Objective(
89 | rule=lambda model: sum((model.x[i]-self.parameters['set'])**2 for i in model.i)
90 | )
91 |
92 | # store the model inside the object
93 | self.model = model
94 |
95 | def solution(self, sta, pre):
96 | # create data and instantiate the pyomo model
97 | ip = np.arange(len(pre['time']))
98 | data = {
99 | None: {
100 | 'i': {None: ip[:-1]},
101 | 'ip': {None: ip},
102 | 'time': {(i,): v for i, v in enumerate(pre['time'])},
103 | 'x0': {None: sta['x']},
104 | 'd': {(i,): pre['d'][i] for i in ip},
105 | }
106 | }
107 |
108 | instance = self.model.create_instance(data)
109 |
110 | # solve and return the control inputs
111 | optimizer = pyomo.SolverFactory('ipopt')
112 | results = optimizer.solve(instance)
113 |
114 | sol = {
115 | 'time': np.array([pyomo.value(instance.time[i]) for i in instance.ip]),
116 | 'x': np.array([pyomo.value(instance.x[i]) for i in instance.ip]),
117 | 'u': np.array([pyomo.value(instance.u[i]) for i in instance.ip]),
118 | 'd': np.array([pyomo.value(instance.d[i]) for i in instance.ip]),
119 | }
120 |
121 | return sol
122 |
123 |
124 | # Define a state estimation class
125 | class StateestimationPerfect(mpcpy.Stateestimation):
126 | """
127 | Perfect state estimation
128 | """
129 | def stateestimation(self, time):
130 | return {'x': np.interp(time, self.emulator.res['time'], self.emulator.res['x'])}
131 |
132 |
133 | # instantiate the emulator
134 | emulator = Emulator(['u', 'd'], parameters={'A': -0.2}, initial_conditions={'x': 0})
135 |
136 | # test the emulator with some random data
137 | time = np.arange(0., 1001., 10.)
138 | np.random.seed(0)
139 | d = np.random.random(len(time)) - 0.5
140 | u = 1.0*np.ones(len(time))
141 |
142 | emulator.initialize()
143 | res = emulator(time, {'time': time, 'd': d, 'u': u})
144 | print(res)
145 |
146 |
147 | # create a disturbances object
148 | time = np.arange(0., 1001., 10.)
149 | d = 0.5*np.sin(2*np.pi*time/1000)
150 | disturbances = mpcpy.Disturbances({'time': time, 'd': d})
151 |
152 | bcs = disturbances(np.array([0, 20, 40, 60, 100]))
153 | print(bcs)
154 |
155 |
156 | # create a stateestimation object
157 | stateestimation = StateestimationPerfect(emulator)
158 | sta = stateestimation(0)
159 | print(sta)
160 |
161 |
162 | # create a prediction object
163 | prediction = mpcpy.Prediction(disturbances)
164 | pre = prediction(np.array([0, 20, 40, 60, 100]))
165 | print(pre)
166 |
167 |
168 | # create a control object and mpc object
169 | control = SetpointControl(stateestimation, prediction, parameters={'A': -0.2, 'set': 3.0},
170 | horizon=100., timestep=10., receding=10.)
171 | mpc = mpcpy.MPC(emulator, control, disturbances, emulationtime=1000, resulttimestep=10)
172 |
173 | # run the mpc
174 | res = mpc(verbose=1)
175 | print(res)
176 |
177 |
178 | # plot results
179 | fig, ax = plt.subplots(2, 1)
180 | ax[0].plot(res['time'], res['u'])
181 | ax[0].set_ylabel('u')
182 |
183 | ax[1].plot(res['time'], res['x'])
184 | ax[1].set_xlabel('time')
185 | ax[1].set_ylabel('x')
186 |
187 |
188 | if __name__ == '__main__':
189 | plt.show()
--------------------------------------------------------------------------------
/doc/source/conf.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | #
3 | # Someproject documentation build configuration file, created by
4 | # sphinx-quickstart on Mon Sep 05 08:56:23 2016.
5 | #
6 | # This file is execfile()d with the current directory set to its
7 | # containing dir.
8 | #
9 | # Note that not all possible configuration values are present in this
10 | # autogenerated file.
11 | #
12 | # All configuration values have a default; values that are commented out
13 | # serve to show the default.
14 |
15 | # If extensions (or modules to document with autodoc) are in another directory,
16 | # add these directories to sys.path here. If the directory is relative to the
17 | # documentation root, use os.path.abspath to make it absolute, like shown here.
18 | #
19 | # import os
20 | # import sys
21 | # sys.path.insert(0, os.path.abspath('.'))
22 |
23 | # -- General configuration ------------------------------------------------
24 |
25 | # If your documentation needs a minimal Sphinx version, state it here.
26 | #
27 | # needs_sphinx = '1.0'
28 |
29 | # Add any Sphinx extension module names here, as strings. They can be
30 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
31 | # ones.
32 |
33 | import sys
34 | import os
35 | import sphinx_rtd_theme
36 |
37 | sys.path.insert(0, os.path.abspath('../..'))
38 |
39 | # import the version string
40 | from mpcpy.__version__ import version as __version__
41 |
42 | extensions = [
43 | 'sphinx.ext.autodoc',
44 | 'sphinx.ext.autosummary',
45 | 'sphinx.ext.mathjax',
46 | 'sphinx.ext.viewcode',
47 | 'numpydoc',
48 | 'matplotlib.sphinxext.plot_directive',
49 | ]
50 |
51 | # Add any paths that contain templates here, relative to this directory.
52 | templates_path = ['_templates']
53 |
54 | # The suffix(es) of source filenames.
55 | # You can specify multiple suffix as a list of string:
56 | #
57 | # source_suffix = ['.rst', '.md']
58 | source_suffix = '.rst'
59 |
60 | # The encoding of source files.
61 | #
62 | # source_encoding = 'utf-8-sig'
63 |
64 | # The master toctree document.
65 | master_doc = 'index'
66 |
67 | # General information about the project.
68 | project = u'mpcpy'
69 | copyright = u'2017, Brecht Baeten'
70 | author = u'Brecht Baeten'
71 |
72 | # The version info for the project you're documenting, acts as replacement for
73 | # |version| and |release|, also used in various other places throughout the
74 | # built documents.
75 | #
76 | # The short X.Y version.
77 | version = str(__version__)
78 | # The full version, including alpha/beta/rc tags.
79 | release = str(__version__)
80 |
81 | # The language for content autogenerated by Sphinx. Refer to documentation
82 | # for a list of supported languages.
83 | #
84 | # This is also used if you do content translation via gettext catalogs.
85 | # Usually you set "language" from the command line for these cases.
86 | language = None
87 |
88 | # There are two options for replacing |today|: either, you set today to some
89 | # non-false value, then it is used:
90 | #
91 | # today = ''
92 | #
93 | # Else, today_fmt is used as the format for a strftime call.
94 | #
95 | # today_fmt = '%B %d, %Y'
96 |
97 | # List of patterns, relative to source directory, that match files and
98 | # directories to ignore when looking for source files.
99 | # This patterns also effect to html_static_path and html_extra_path
100 | exclude_patterns = []
101 |
102 | # The reST default role (used for this markup: `text`) to use for all
103 | # documents.
104 | #
105 | # default_role = None
106 |
107 | # If true, '()' will be appended to :func: etc. cross-reference text.
108 | #
109 | # add_function_parentheses = True
110 |
111 | # If true, the current module name will be prepended to all description
112 | # unit titles (such as .. function::).
113 | #
114 | # add_module_names = True
115 |
116 | # If true, sectionauthor and moduleauthor directives will be shown in the
117 | # output. They are ignored by default.
118 | #
119 | # show_authors = False
120 |
121 | # The name of the Pygments (syntax highlighting) style to use.
122 | pygments_style = 'sphinx'
123 |
124 | # A list of ignored prefixes for module index sorting.
125 | # modindex_common_prefix = []
126 |
127 | # If true, keep warnings as "system message" paragraphs in the built documents.
128 | # keep_warnings = False
129 |
130 | # If true, `todo` and `todoList` produce output, else they produce nothing.
131 | todo_include_todos = False
132 |
133 |
134 | # -- Options for HTML output ----------------------------------------------
135 |
136 | # The theme to use for HTML and HTML Help pages. See the documentation for
137 | # a list of builtin themes.
138 | #
139 | html_theme = 'sphinx_rtd_theme'
140 |
141 | # Theme options are theme-specific and customize the look and feel of a theme
142 | # further. For a list of options available for each theme, see the
143 | # documentation.
144 | #
145 | # html_theme_options = {}
146 |
147 | # Add any paths that contain custom themes here, relative to this directory.
148 | html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
149 |
150 | # The name for this set of Sphinx documents.
151 | # " v documentation" by default.
152 | #
153 | # html_title = u'Someproject v3.1.2'
154 |
155 | # A shorter title for the navigation bar. Default is the same as html_title.
156 | #
157 | # html_short_title = None
158 |
159 | # The name of an image file (relative to this directory) to place at the top
160 | # of the sidebar.
161 | #
162 | # html_logo = None
163 |
164 | # The name of an image file (relative to this directory) to use as a favicon of
165 | # the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
166 | # pixels large.
167 | #
168 | # html_favicon = None
169 |
170 | # Add any paths that contain custom static files (such as style sheets) here,
171 | # relative to this directory. They are copied after the builtin static files,
172 | # so a file named "default.css" will overwrite the builtin "default.css".
173 | html_static_path = ['_static']
174 |
175 | # Add any extra paths that contain custom files (such as robots.txt or
176 | # .htaccess) here, relative to this directory. These files are copied
177 | # directly to the root of the documentation.
178 | #
179 | # html_extra_path = []
180 |
181 | # If not None, a 'Last updated on:' timestamp is inserted at every page
182 | # bottom, using the given strftime format.
183 | # The empty string is equivalent to '%b %d, %Y'.
184 | #
185 | # html_last_updated_fmt = None
186 |
187 | # If true, SmartyPants will be used to convert quotes and dashes to
188 | # typographically correct entities.
189 | #
190 | # html_use_smartypants = True
191 |
192 | # Custom sidebar templates, maps document names to template names.
193 | #
194 | html_sidebars = {
195 | '**': [
196 | 'about.html',
197 | 'navigation.html',
198 | 'relations.html',
199 | 'searchbox.html',
200 | 'donate.html'
201 | ]
202 | }
203 |
204 | # Additional templates that should be rendered to pages, maps page names to
205 | # template names.
206 | #
207 | # html_additional_pages = {}
208 |
209 | # If false, no module index is generated.
210 | #
211 | # html_domain_indices = True
212 |
213 | # If false, no index is generated.
214 | #
215 | # html_use_index = True
216 |
217 | # If true, the index is split into individual pages for each letter.
218 | #
219 | # html_split_index = False
220 |
221 | # If true, links to the reST sources are added to the pages.
222 | #
223 | # html_show_sourcelink = True
224 |
225 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
226 | #
227 | # html_show_sphinx = True
228 |
229 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
230 | #
231 | # html_show_copyright = True
232 |
233 | # If true, an OpenSearch description file will be output, and all pages will
234 | # contain a tag referring to it. The value of this option must be the
235 | # base URL from which the finished HTML is served.
236 | #
237 | # html_use_opensearch = ''
238 |
239 | # This is the file name suffix for HTML files (e.g. ".xhtml").
240 | # html_file_suffix = None
241 |
242 | # Language to be used for generating the HTML full-text search index.
243 | # Sphinx supports the following languages:
244 | # 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja'
245 | # 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr', 'zh'
246 | #
247 | # html_search_language = 'en'
248 |
249 | # A dictionary with options for the search language support, empty by default.
250 | # 'ja' uses this config value.
251 | # 'zh' user can custom change `jieba` dictionary path.
252 | #
253 | # html_search_options = {'type': 'default'}
254 |
255 | # The name of a javascript file (relative to the configuration directory) that
256 | # implements a search results scorer. If empty, the default will be used.
257 | #
258 | # html_search_scorer = 'scorer.js'
259 |
260 | # Output file base name for HTML help builder.
261 | htmlhelp_basename = 'Someprojectdoc'
262 |
263 | # -- Options for LaTeX output ---------------------------------------------
264 |
265 | latex_elements = {
266 | # The paper size ('letterpaper' or 'a4paper').
267 | #
268 | # 'papersize': 'letterpaper',
269 |
270 | # The font size ('10pt', '11pt' or '12pt').
271 | #
272 | # 'pointsize': '10pt',
273 |
274 | # Additional stuff for the LaTeX preamble.
275 | #
276 | # 'preamble': '',
277 |
278 | # Latex figure (float) alignment
279 | #
280 | # 'figure_align': 'htbp',
281 | }
282 |
283 | # Grouping the document tree into LaTeX files. List of tuples
284 | # (source start file, target name, title,
285 | # author, documentclass [howto, manual, or own class]).
286 | latex_documents = [
287 | (master_doc, 'mpcpy.tex', u'mpcpy Documentation',
288 | u'me', 'manual'),
289 | ]
290 |
291 | # The name of an image file (relative to this directory) to place at the top of
292 | # the title page.
293 | #
294 | # latex_logo = None
295 |
296 | # For "manual" documents, if this is true, then toplevel headings are parts,
297 | # not chapters.
298 | #
299 | # latex_use_parts = False
300 |
301 | # If true, show page references after internal links.
302 | #
303 | # latex_show_pagerefs = False
304 |
305 | # If true, show URL addresses after external links.
306 | #
307 | # latex_show_urls = False
308 |
309 | # Documents to append as an appendix to all manuals.
310 | #
311 | # latex_appendices = []
312 |
313 | # It false, will not define \strong, \code, itleref, \crossref ... but only
314 | # \sphinxstrong, ..., \sphinxtitleref, ... To help avoid clash with user added
315 | # packages.
316 | #
317 | # latex_keep_old_macro_names = True
318 |
319 | # If false, no module index is generated.
320 | #
321 | # latex_domain_indices = True
322 |
323 |
324 | # -- Options for manual page output ---------------------------------------
325 |
326 | # One entry per manual page. List of tuples
327 | # (source start file, name, description, authors, manual section).
328 | man_pages = [
329 | (master_doc, 'mpcpy', u'mpcpy Documentation',
330 | [author], 1)
331 | ]
332 |
333 | # If true, show URL addresses after external links.
334 | #
335 | # man_show_urls = False
336 |
337 |
338 | # -- Options for Texinfo output -------------------------------------------
339 |
340 | # Grouping the document tree into Texinfo files. List of tuples
341 | # (source start file, target name, title, author,
342 | # dir menu entry, description, category)
343 | texinfo_documents = [
344 | (master_doc, 'mpcpy', u'mpcpy Documentation',
345 | author, 'mpcpy', '',
346 | 'Miscellaneous'),
347 | ]
348 |
349 | # Documents to append as an appendix to all manuals.
350 | #
351 | # texinfo_appendices = []
352 |
353 | # If false, no module index is generated.
354 | #
355 | # texinfo_domain_indices = True
356 |
357 | # How to display URL addresses: 'footnote', 'no', or 'inline'.
358 | #
359 | # texinfo_show_urls = 'footnote'
360 |
361 | # If true, do not generate a @detailmenu in the "Top" node's menu.
362 | #
363 | # texinfo_no_detailmenu = False
364 |
365 |
366 |
367 | # -- Options for numpydoc ----------------------------------------------------
368 |
369 | numpydoc_show_class_members = False
370 | numpydoc_show_inherited_class_members = False
371 |
372 |
373 | # -- Options for autodoc ----------------------------------------------------
374 |
375 | autoclass_content = 'both'
--------------------------------------------------------------------------------
/doc/source/control.rst:
--------------------------------------------------------------------------------
1 | Control
2 | =======
3 |
4 | .. autoclass:: mpcpy.Control
5 | :members:
6 | :special-members: __call__
--------------------------------------------------------------------------------
/doc/source/disturbances.rst:
--------------------------------------------------------------------------------
1 | Disturbances
2 | ============
3 |
4 | .. autoclass:: mpcpy.Disturbances
5 | :members:
6 | :special-members: __call__
--------------------------------------------------------------------------------
/doc/source/emulator.rst:
--------------------------------------------------------------------------------
1 | Emulator
2 | ========
3 |
4 | .. autoclass:: mpcpy.Emulator
5 | :members:
6 | :special-members: __call__
7 |
--------------------------------------------------------------------------------
/doc/source/index.rst:
--------------------------------------------------------------------------------
1 | .. mpcpy documentation master file, created by python-git-package.
2 | You can adapt this file completely to your liking, but it should at least
3 | contain the root `toctree` directive.
4 |
5 | mpcpy
6 | =====
7 |
8 | :Release: |version|
9 | :Date: |today|
10 |
11 |
12 | A group of classes to run Model Predictive Control (MPC) simulations using python.
13 |
14 |
15 | Contents:
16 |
17 | .. toctree::
18 | :maxdepth: 2
19 |
20 | installation
21 | quickstart
22 | reference
23 |
24 |
25 |
--------------------------------------------------------------------------------
/doc/source/installation.rst:
--------------------------------------------------------------------------------
1 | Installation
2 | ============
3 | .. toctree::
4 | :maxdepth: 3
5 |
6 |
7 | Prequisites
8 | -----------
9 |
10 | * :code:`numpy`
11 |
12 |
13 | Setup
14 | -----
15 |
16 | Install via pip:
17 |
18 | .. code-block:: bash
19 |
20 | pip install mpcpy
21 |
22 | Or:
23 |
24 | * download a `release `_
25 | * unzip and cd to the folder
26 | * run :code:`python setup.py install`
27 |
28 |
--------------------------------------------------------------------------------
/doc/source/mpc.rst:
--------------------------------------------------------------------------------
1 | MPC
2 | ===
3 |
4 | .. autoclass:: mpcpy.MPC
5 | :members:
6 | :special-members: __call__
--------------------------------------------------------------------------------
/doc/source/prediction.rst:
--------------------------------------------------------------------------------
1 | Prediction
2 | ==========
3 |
4 | .. autoclass:: mpcpy.Prediction
5 | :members:
6 | :special-members: __call__
--------------------------------------------------------------------------------
/doc/source/quickstart.rst:
--------------------------------------------------------------------------------
1 | Quickstart
2 | ==========
3 | .. toctree::
4 | :maxdepth: 3
5 |
6 |
7 | MPC programming structure
8 | -------------------------
9 |
10 | In Model Predictive Control (MPC) a dynamic system is controlled with some
11 | control inputs. These inputs are computed with the aid of a model of the dynamic
12 | system which predicts the system behavior over a certain time horizon.
13 |
14 | An MPC simulation is here defined as a dynamic simulation of such a system. In
15 | such a simulation the actual system is replaced by a system emulator, a dynamic
16 | simulation which should model the system behavior a close as possible.
17 |
18 | The control algorithm contains a more simplified model of the dynamic system and
19 | often uses an optimization technique to compute the control signals which
20 | minimize some objective function over a time horizon. This is referred to as an
21 | Optimal Control Problem (OCP).
22 |
23 | The system under consideration is most likely subjected to some uncontrolled
24 | disturbances. The OCP thus requires a prediction of these disturbances over the
25 | prediction horizon to be able to compute the system behavior. Furthermore, an
26 | estimation of the current system state is needed, probably requiring some
27 | (virtual) measurements.
28 |
29 | An MPC simulation can thus be broken down into the following steps:
30 |
31 | * Estimate the state of the system.
32 | * Generate a prediction for the disturbances over the control horizon.
33 | * Compute control signals by solving an OCP.
34 | * Supply the control signals to a system emulator and simulate the system behavior.
35 | * Repeat.
36 |
37 |
38 | In mpcpy the :code:`mpcpy.mcp` object contains the main functions for
39 | orchestrating the MPC. It depends on an :code:`mpcpy.emulator` object, an
40 | :code:`mpcpy.disturbances` object and an :code:`mpcpy.control` object.
41 |
42 | The emulation time is split up in parts defined by the control receding time.
43 | For each part, the above steps are executed and the emulator simulates the
44 | system over the receding time.
45 |
46 | The :code:`mpcpy.control` object handles the generation of control signals.
47 | Therfore it requires an :code:`mpcpy.stateestimation` object and an
48 | :code:`mpcpy.prediction` object.
49 |
50 | Example
51 | ^^^^^^^
52 |
53 | When the :code:`mpcpy.emulator`, :code:`mpcpy.control` and
54 | :code:`mpcpy.disturbances` objects are defined, an :code:`mpcpy.mpc` object can
55 | be instantiated:
56 |
57 | .. literalinclude:: ../../examples/quickstart.py
58 | :lines: 171
59 |
60 |
61 |
62 | Emulator
63 | --------
64 |
65 | The :code:`mpcpy.emulator` class serves as a base class for defining emulator
66 | objects. By default, the emulator object returns the control solution as its
67 | result. So when no detailed emulator model is available, the
68 | :code:`mpcpy.emulator` class can be used to split an OCP in different parts and
69 | solve it sequentially. Care must be taken that the OCPs overlap sufficiently, so
70 | the receding time must be significantly shorter than the horizon.
71 |
72 | The :code:`mpcpy.emulator` class requires a list of keys as input arguments,
73 | this list specifies which disturbances and control signals should be
74 | passed to the simulation, all control signals are passed to the simulation.
75 |
76 | When subclassing the :code:`mpcpy.emulator` class the main method to be
77 | redefined is the :code:`simulate` method. This method receives a starttime,
78 | stoptime and input dictionary as arguments and should return a results
79 | dictionary with a time array and values for the results between the start- and
80 | stoptime.
81 |
82 | Internally a :code:`res` dictionary holds the results of the simulation up to
83 | the current point in time. This :code:`res` dictionary can also be used to
84 | determine the state required for the OCP.
85 |
86 | The system can then be simulated by calling an :code:`mpcpy.emulator` object
87 | with an array of input times (the time steps at which results are required) and
88 | a dictionary of inputs. During an MPC simulation this is handled by the
89 | :code:`mpcpy.mpc` object.
90 |
91 | Example
92 | ^^^^^^^
93 |
94 | .. literalinclude:: ../../examples/quickstart.py
95 | :lines: 27-56,134-144
96 |
97 |
98 | Disturbances
99 | ------------
100 |
101 | The :code:`mpcpy.disturbances` class is a helper class for manging the
102 | disturbances.
103 | Signals are defined based on a dictionary which must include a :code:`time` key
104 | and specifies the values of all signals at these time steps.
105 | An :code:`mpcpy.disturbances` object can then interpolate the values to
106 | the required time points in the :code:`mpcpy.emulator` and
107 | :code:`mpcpy.prediction` objects.
108 |
109 | Example
110 | ^^^^^^^
111 |
112 | .. literalinclude:: ../../examples/quickstart.py
113 | :lines: 148-153
114 |
115 |
116 | Control
117 | -------
118 | The emulator requires control inputs which are generated by an object derived
119 | from the :code:`mpcpy.Control` base class.
120 | The methods that should be redefined in a child class are the
121 | :code:`formulation` and :code:`solution` methods.
122 |
123 | The :code:`formulation` method is called once by the :code:`mpcpy.mpc` object
124 | before the start of the simulation. This method can thus be used to formulate an
125 | abstract optimal control problem and assign values that will not change through
126 | the course of the simulation.
127 |
128 | The :code`solution` method should generate the control signals to be used by the
129 | emulator. When the control signals should be generated, it is called with two
130 | parameters representing the current state of the system and the predictions of
131 | the disturbances over the control horizon. These are generated by the
132 | :code:`mpcpy.stateestimation` and :code:`mpcpy.prediction` objects supplied to
133 | the control object during initialization respectively.
134 | The :code`solution` method must return a dictionary with a time vector and the
135 | control signal values over the entire control horizon.
136 |
137 | Example
138 | ^^^^^^^
139 |
140 | .. literalinclude:: ../../examples/quickstart.py
141 | :lines: 60-121
142 |
143 | When the stateestimation and prediction objects are defined, a control object
144 | can be instantiated:
145 |
146 | .. literalinclude:: ../../examples/quickstart.py
147 | :lines: 169-170
148 |
149 |
150 | State estimation
151 | ----------------
152 |
153 | The :code:`mpcpy.stateestimation` class is a base class for defining object that
154 | estimate the current state required for the control based on measurements done
155 | on the emulator. When the states required for the control problem are not
156 | directly measurable they are often computed with a Kalman filter.
157 | The main method to redefine in a child class is the :code`stateestimation`
158 | method. This method takes the time at which the states should be estimated as an
159 | input parameter and must return a dictionary of key-value pairs representing the
160 | state at that time.
161 |
162 | Example
163 | ^^^^^^^
164 |
165 | .. literalinclude:: ../../examples/quickstart.py
166 | :lines: 125-130,157-159
167 |
168 |
169 | Prediction
170 | ----------
171 |
172 | The :code:`mpcpy.prediction` class is a base class for returning prediction data
173 | required for the OCP.
174 |
175 | It requires a :code:`mpcpy.disturbances` object which represent the actual
176 | conditions. From these values predictions may be derived.
177 |
178 | Example
179 | ^^^^^^^
180 |
181 | .. literalinclude:: ../../examples/quickstart.py
182 | :lines: 163-165
183 |
184 |
185 | MPC
186 | ---
187 |
188 | The entire MPC simulation can now be run from the above defined objects. Just
189 | call the :code:`mpcpy.MPC` object to start the simulation. Results will be
190 | returned in a dictionary.
191 |
192 |
193 | Example
194 | ^^^^^^^
195 |
196 | .. literalinclude:: ../../examples/quickstart.py
197 | :lines: 169-175
198 |
199 |
200 | The optimal control inputs and resulting state of the quickstart example is presented below.
201 |
202 | .. plot:: ../../examples/quickstart.py
203 |
--------------------------------------------------------------------------------
/doc/source/reference.rst:
--------------------------------------------------------------------------------
1 | Reference
2 | =========
3 | .. toctree::
4 | :maxdepth: 3
5 |
6 | disturbances
7 | emulator
8 | stateestimation
9 | prediction
10 | control
11 | mpc
--------------------------------------------------------------------------------
/doc/source/stateestimation.rst:
--------------------------------------------------------------------------------
1 | Stateestimation
2 | ===============
3 |
4 | .. autoclass:: mpcpy.Stateestimation
5 | :members:
6 | :special-members: __call__
--------------------------------------------------------------------------------
/examples/.gitignore:
--------------------------------------------------------------------------------
1 | .ipynb_checkpoints
2 | dsin.txt
--------------------------------------------------------------------------------
/examples/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/BrechtBa/mpcpy/108b7a19bc07f17b1fae30ee8ecfdd1e732c1c47/examples/__init__.py
--------------------------------------------------------------------------------
/examples/quickstart.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | ################################################################################
3 | # Copyright 2015 Brecht Baeten
4 | # This file is part of mpcpy.
5 | #
6 | # mpcpy is free software: you can redistribute it and/or modify
7 | # it under the terms of the GNU General Public License as published by
8 | # the Free Software Foundation, either version 3 of the License, or
9 | # (at your option) any later version.
10 | #
11 | # mpcpy is distributed in the hope that it will be useful,
12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | # GNU General Public License for more details.
15 | #
16 | # You should have received a copy of the GNU General Public License
17 | # along with mpcpy. If not, see .
18 | ################################################################################
19 |
20 | import numpy as np
21 | import matplotlib.pyplot as plt
22 |
23 | import mpcpy
24 | import pyomo.environ as pyomo
25 |
26 |
27 | # Define an emulator class
28 | class Emulator(mpcpy.Emulator):
29 | """
30 | A custom system emulator
31 | """
32 | def simulate(self, starttime, stoptime, input):
33 | dt = 1
34 | time = np.arange(starttime, stoptime+dt, dt, dtype=np.float)
35 |
36 | # initialize
37 | x = np.ones_like(time)*self.res['x'][-1]
38 |
39 | # interpolate inputs
40 | u = np.interp(time, input['time'], input['u'])
41 | d = np.interp(time, input['time'], input['d'])
42 |
43 | # perform simulation
44 | for i, t in enumerate(time[:-1]):
45 | # dx/dt = A*x + d + u
46 | x[i+1] = x[i] + (self.parameters['A']*x[i] + d[i] + u[i])*dt
47 |
48 | # create and return a results dict
49 | res = {
50 | 'time': time,
51 | 'x': x,
52 | 'd': d,
53 | 'u': u,
54 | }
55 |
56 | return res
57 |
58 |
59 | # Define a control class
60 | class SetpointControl(mpcpy.Control):
61 | """
62 | A control to keep the state as close to a set point as possible
63 | """
64 | def formulation(self):
65 | # create a pyomo model
66 | model = pyomo.AbstractModel()
67 |
68 | model.i = pyomo.Set()
69 | model.ip = pyomo.Set()
70 |
71 | model.time = pyomo.Param(model.ip)
72 | model.d = pyomo.Param(model.ip, initialize=0.)
73 | model.x = pyomo.Var(model.ip, domain=pyomo.Reals, initialize=0.)
74 | model.u = pyomo.Var(model.ip, domain=pyomo.NonNegativeReals, bounds=(0., 1.), initialize=0.)
75 |
76 | model.x0 = pyomo.Param(initialize=0.)
77 |
78 | model.initialcondition = pyomo.Constraint(
79 | rule=lambda model: model.x[0] == model.x0
80 | )
81 |
82 | model.constraint = pyomo.Constraint(
83 | model.i,
84 | rule=lambda model, i: (model.x[i+1]-model.x[i])/(model.time[i+1]-model.time[i]) ==
85 | self.parameters['A']*model.x[i] + model.d[i] + model.u[i]
86 | )
87 |
88 | model.objective = pyomo.Objective(
89 | rule=lambda model: sum((model.x[i]-self.parameters['set'])**2 for i in model.i)
90 | )
91 |
92 | # store the model inside the object
93 | self.model = model
94 |
95 | def solution(self, sta, pre):
96 | # create data and instantiate the pyomo model
97 | ip = np.arange(len(pre['time']))
98 | data = {
99 | None: {
100 | 'i': {None: ip[:-1]},
101 | 'ip': {None: ip},
102 | 'time': {(i,): v for i, v in enumerate(pre['time'])},
103 | 'x0': {None: sta['x']},
104 | 'd': {(i,): pre['d'][i] for i in ip},
105 | }
106 | }
107 |
108 | instance = self.model.create_instance(data)
109 |
110 | # solve and return the control inputs
111 | optimizer = pyomo.SolverFactory('ipopt')
112 | results = optimizer.solve(instance)
113 |
114 | sol = {
115 | 'time': np.array([pyomo.value(instance.time[i]) for i in instance.ip]),
116 | 'x': np.array([pyomo.value(instance.x[i]) for i in instance.ip]),
117 | 'u': np.array([pyomo.value(instance.u[i]) for i in instance.ip]),
118 | 'd': np.array([pyomo.value(instance.d[i]) for i in instance.ip]),
119 | }
120 |
121 | return sol
122 |
123 |
124 | # Define a state estimation class
125 | class StateestimationPerfect(mpcpy.Stateestimation):
126 | """
127 | Perfect state estimation
128 | """
129 | def stateestimation(self, time):
130 | return {'x': np.interp(time, self.emulator.res['time'], self.emulator.res['x'])}
131 |
132 |
133 | # instantiate the emulator
134 | emulator = Emulator(['u', 'd'], parameters={'A': -0.2}, initial_conditions={'x': 0})
135 |
136 | # test the emulator with some random data
137 | time = np.arange(0., 1001., 10.)
138 | np.random.seed(0)
139 | d = np.random.random(len(time)) - 0.5
140 | u = 1.0*np.ones(len(time))
141 |
142 | emulator.initialize()
143 | res = emulator(time, {'time': time, 'd': d, 'u': u})
144 | print(res)
145 |
146 |
147 | # create a disturbances object
148 | time = np.arange(0., 1001., 10.)
149 | d = 0.5*np.sin(2*np.pi*time/1000)
150 | disturbances = mpcpy.Disturbances({'time': time, 'd': d})
151 |
152 | bcs = disturbances(np.array([0, 20, 40, 60, 100]))
153 | print(bcs)
154 |
155 |
156 | # create a stateestimation object
157 | stateestimation = StateestimationPerfect(emulator)
158 | sta = stateestimation(0)
159 | print(sta)
160 |
161 |
162 | # create a prediction object
163 | prediction = mpcpy.Prediction(disturbances)
164 | pre = prediction(np.array([0, 20, 40, 60, 100]))
165 | print(pre)
166 |
167 |
168 | # create a control object and mpc object
169 | control = SetpointControl(stateestimation, prediction, parameters={'A': -0.2, 'set': 3.0},
170 | horizon=100., timestep=10., receding=10.)
171 | mpc = mpcpy.MPC(emulator, control, disturbances, emulationtime=1000, resulttimestep=10)
172 |
173 | # run the mpc
174 | res = mpc(verbose=1)
175 | print(res)
176 |
177 |
178 | # plot results
179 | fig, ax = plt.subplots(2, 1)
180 | ax[0].plot(res['time'], res['u'])
181 | ax[0].set_ylabel('u')
182 |
183 | ax[1].plot(res['time'], res['x'])
184 | ax[1].set_xlabel('time')
185 | ax[1].set_ylabel('x')
186 |
187 |
188 | if __name__ == '__main__':
189 | plt.show()
--------------------------------------------------------------------------------
/examples/simple_space_heating_mpc.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | ################################################################################
3 | # Copyright 2015 Brecht Baeten
4 | # This file is part of mpcpy.
5 | #
6 | # mpcpy is free software: you can redistribute it and/or modify
7 | # it under the terms of the GNU General Public License as published by
8 | # the Free Software Foundation, either version 3 of the License, or
9 | # (at your option) any later version.
10 | #
11 | # mpcpy is distributed in the hope that it will be useful,
12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | # GNU General Public License for more details.
15 | #
16 | # You should have received a copy of the GNU General Public License
17 | # along with mpcpy. If not, see .
18 | ################################################################################
19 |
20 | import numpy as np
21 | import matplotlib.pyplot as plt
22 | import pyomo.environ as pyomo
23 |
24 | import mpcpy
25 |
26 | # Disturbances
27 | time = np.arange(0.,24.01*3600.,3600.)
28 | dst = {
29 | 'time': time,
30 | 'T_am': 5 + 2*np.sin(2*np.pi*time/24./3600.)+273.15,
31 | 'Q_flow_so': 500 + 500*np.sin(2*np.pi*time/24./3600.),
32 | 'p_el': 0.2 + 0.05*np.sin(2*np.pi*time/24./3600.),
33 | 'Q_flow_hp_max': 5000*np.ones_like(time),
34 | 'T_in_min': 20*np.ones_like(time)+273.15,
35 | 'T_em_max': 30*np.ones_like(time)+273.15
36 | }
37 |
38 | disturbances = mpcpy.Disturbances(dst, periodic=False)
39 | # test
40 | print(disturbances(1800))
41 | print(disturbances(24.5 * 3600)) # extrapolation
42 |
43 |
44 | # Emulator
45 | class Emulator(mpcpy.Emulator):
46 | """
47 | A custom system emulator
48 | """
49 | def simulate(self, starttime, stoptime, input):
50 | dt = 60
51 | time = np.arange(starttime, stoptime+dt, dt, dtype=np.float)
52 |
53 | # initialize
54 | T_em = np.ones_like(time)*self.res['T_em'][-1]
55 | T_in = np.ones_like(time)*self.res['T_in'][-1]
56 |
57 | # interpolate inputs
58 | Q_flow_hp = np.interp(time, input['time'], input['Q_flow_hp'])
59 | Q_flow_so = np.interp(time, input['time'], input['Q_flow_so'])
60 | T_am = np.interp(time, input['time'], input['T_am'])
61 |
62 | for i,t in enumerate(time[:-1]):
63 | # C_em dT_em/dt = Q_flow_hp - UA_em_in*(T_em-T_in)
64 | T_em[i+1] = T_em[i] + (Q_flow_hp[i] - self.parameters['UA_em_in']*(T_em[i]-T_in[i]))*dt/self.parameters['C_em']
65 |
66 | # C_in dT_in/dt = Q_flow_so - UA_em_in*(T_in-T_em) - UA_in_am*(T_in-T_am)
67 | T_in[i+1] = T_in[i] + (Q_flow_so[i] - self.parameters['UA_em_in']*(T_in[i]-T_em[i]) - self.parameters['UA_in_am']*(T_in[i]-T_am[i]))*dt/self.parameters['C_em']
68 |
69 | # create and return a results dict
70 | res = {
71 | 'time': time,
72 | 'Q_flow_hp':Q_flow_hp,
73 | 'Q_flow_so':Q_flow_so,
74 | 'T_em':T_em,
75 | 'T_in':T_in,
76 | 'T_am':T_am,
77 | }
78 |
79 | return res
80 |
81 |
82 | # Emulator parameters and initial conditions:
83 | emulator_parameters = {
84 | 'C_em': 10e6,
85 | 'C_in': 5e6,
86 | 'UA_in_am': 200,
87 | 'UA_em_in': 1600
88 | }
89 | emulator_initial_conditions = {
90 | 'T_em': 22+273.15,
91 | 'T_in': 21+273.15
92 | }
93 |
94 | emulator = Emulator(['T_am','Q_flow_so','Q_flow_hp'],parameters=emulator_parameters,initial_conditions=emulator_initial_conditions)
95 | emulator.initialize()
96 | # test
97 | inp = {
98 | 'time': [0., 3600., 7200.],
99 | 'T_am': [273.15, 274.15, 275.15],
100 | 'Q_flow_so': [500., 400., 300.],
101 | 'Q_flow_hp': [4000., 4000., 4000.]
102 | }
103 | emulator(np.arange(0., 7201., 1200.), inp)
104 |
105 | print(emulator.res['time'])
106 | print(emulator.res['T_em'])
107 |
108 |
109 | # State estimation
110 | class StateestimationPerfect(mpcpy.Stateestimation):
111 | """
112 | Custom state estimation method
113 | """
114 | def stateestimation(self, time):
115 | state = {}
116 | state['T_in'] = np.interp(time, self.emulator.res['time'], self.emulator.res['T_in'])
117 | state['T_em'] = np.interp(time, self.emulator.res['time'], self.emulator.res['T_em'])
118 |
119 | return state
120 |
121 | stateestimation = StateestimationPerfect(emulator)
122 | # test
123 | print(stateestimation(0))
124 |
125 |
126 | # Prediction
127 | prediction = mpcpy.Prediction(disturbances)
128 | # test
129 | print(prediction([0., 1800., 3600.]))
130 |
131 |
132 | # Control
133 | class LinearProgram(mpcpy.Control):
134 | def formulation(self):
135 | """
136 | formulates the abstract optimal control problem
137 | """
138 | model = pyomo.AbstractModel()
139 |
140 | # sets
141 | model.i = pyomo.Set() # initialize=range(len(time)-1)
142 | model.ip = pyomo.Set() # initialize=range(len(time))
143 |
144 | # parameters
145 | model.time = pyomo.Param(model.ip)
146 |
147 | model.UA_em_in = pyomo.Param(initialize=800.)
148 | model.UA_in_am = pyomo.Param(initialize=200.)
149 |
150 | model.C_in = pyomo.Param(initialize=5.0e6)
151 | model.C_em = pyomo.Param(initialize=20.0e6)
152 |
153 | model.T_in_ini = pyomo.Param(initialize=21.+273.15)
154 | model.T_em_ini = pyomo.Param(initialize=22.+273.15)
155 |
156 | model.T_in_min = pyomo.Param(initialize=20.+273.15)
157 | model.T_in_max = pyomo.Param(initialize=24.+273.15)
158 |
159 | model.T_am = pyomo.Param(model.i, initialize=0.+273.15)
160 | model.Q_flow_so = pyomo.Param(model.i, initialize=0.)
161 |
162 | # variables
163 | model.T_in = pyomo.Var(model.ip,domain=pyomo.Reals, initialize=20.+273.15)
164 | model.T_em = pyomo.Var(model.ip,domain=pyomo.Reals,initialize=20.+273.15)
165 |
166 | model.T_in_min_slack = pyomo.Var(model.ip,domain=pyomo.NonNegativeReals, initialize=0)
167 | model.T_in_max_slack = pyomo.Var(model.ip,domain=pyomo.NonNegativeReals, initialize=0)
168 |
169 | model.Q_flow_hp = pyomo.Var(model.i,domain=pyomo.NonNegativeReals,bounds=(0.,10000.),initialize=0.)
170 |
171 | # constraints
172 | model.state_T_em = pyomo.Constraint(
173 | model.i,
174 | rule=lambda model,i: model.C_em*(model.T_em[i+1]-model.T_em[i])/(model.time[i+1]-model.time[i]) == \
175 | model.Q_flow_hp[i] \
176 | - model.UA_em_in*(model.T_em[i]-model.T_in[i])
177 | )
178 | model.ini_T_em = pyomo.Constraint(rule=lambda model: model.T_em[0] == model.T_em_ini)
179 |
180 | model.state_T_in = pyomo.Constraint(
181 | model.i,
182 | rule=lambda model,i: model.C_in*(model.T_in[i+1]-model.T_in[i])/(model.time[i+1]-model.time[i]) == \
183 | model.Q_flow_so[i] \
184 | - model.UA_em_in*(model.T_in[i]-model.T_em[i]) \
185 | - model.UA_in_am*(model.T_in[i]-model.T_am[i])
186 | )
187 | model.ini_T_in = pyomo.Constraint(rule=lambda model: model.T_in[0] == model.T_in_ini)
188 |
189 | # soft constraints
190 | model.constraint_T_in_min_slack = pyomo.Constraint(
191 | model.ip,
192 | rule=lambda model,i: model.T_in_min_slack[i] >= model.T_in_min-model.T_in[i]
193 | )
194 |
195 | model.constraint_T_in_max_slack = pyomo.Constraint(
196 | model.ip,
197 | rule=lambda model,i: model.T_in_max_slack[i] >= model.T_in[i]-model.T_in_max
198 | )
199 |
200 | # a large number
201 | L = 1e6
202 |
203 | # objective
204 | model.objective = pyomo.Objective(
205 | rule=lambda model: sum(model.Q_flow_hp[i]*(model.time[i+1]-model.time[i])/3600/1000 for i in model.i) \
206 | +sum(model.T_in_min_slack[i]*(model.time[i+1]-model.time[i])/3600 for i in model.i)*L\
207 | +sum(model.T_in_max_slack[i]*(model.time[i+1]-model.time[i])/3600 for i in model.i)*L\
208 | )
209 |
210 | self.model = model
211 |
212 | def solution(self, sta, pre):
213 | """
214 | instanciate the optimal control problem, solve it and return a solution dictionary
215 | """
216 |
217 | ip = np.arange(len(pre['time']))
218 |
219 | data = {
220 | None: {
221 | 'i': {None: ip[:-1]},
222 | 'ip': {None: ip},
223 | 'time': {(i,): v for i, v in enumerate(pre['time'])},
224 | 'T_am': {(i,): pre['T_am'][i] for i in ip[:-1]},
225 | 'Q_flow_so': {(i,): pre['Q_flow_so'][i] for i in ip[:-1]},
226 | 'T_em_ini': {None: sta['T_em']},
227 | 'T_in_ini': {None: sta['T_in']},
228 | 'C_em': {None: self.parameters['C_em']},
229 | 'C_in': {None: self.parameters['C_in']},
230 | 'UA_em_in': {None: self.parameters['UA_em_in']},
231 | 'UA_in_am': {None: self.parameters['UA_in_am']},
232 | }
233 | }
234 |
235 | instance = self.model.create_instance(data)
236 | optimizer = pyomo.SolverFactory('ipopt')
237 | results = optimizer.solve(instance)
238 |
239 | # return the contol inputs
240 | sol = {
241 | 'time': np.array([pyomo.value(instance.time[i]) for i in instance.ip]),
242 | 'T_em': np.array([pyomo.value(instance.T_em[i]) for i in instance.ip]),
243 | 'T_in': np.array([pyomo.value(instance.T_in[i]) for i in instance.ip]),
244 | 'Q_flow_hp': np.array([pyomo.value(instance.Q_flow_hp[i]) for i in instance.i]),
245 | }
246 |
247 | return sol
248 |
249 |
250 | # Control parameters
251 | control_parameters = {
252 | 'C_in': emulator_parameters['C_in'],
253 | 'C_em': emulator_parameters['C_em'],
254 | 'UA_in_am': emulator_parameters['UA_in_am'],
255 | 'UA_em_in': emulator_parameters['UA_em_in'],
256 | }
257 | # create an instance
258 | control = LinearProgram(stateestimation, prediction, parameters=control_parameters, horizon=24*3600., timestep=3600.)
259 | # test
260 | print(control(0))
261 |
262 |
263 | # MPC
264 | mpc = mpcpy.MPC(emulator, control, disturbances, emulationtime=1*24*3600., resulttimestep=60)
265 | res = mpc(verbose=1)
266 |
267 |
268 | # Plot results
269 | fix, ax = plt.subplots(2, 1)
270 | ax[0].plot(res['time']/3600, res['Q_flow_hp'], 'k', label='hp')
271 | ax[0].plot(res['time']/3600, res['Q_flow_so'], 'g', label='sol')
272 | ax[0].set_ylabel('Heat flow rate (W)')
273 | ax[0].legend(loc='lower right')
274 |
275 | ax[1].plot(res['time']/3600, res['T_in']-273.17, 'k', label='in')
276 | ax[1].plot(res['time']/3600, res['T_em']-273.17, 'b', label='em')
277 | ax[1].plot(res['time']/3600, res['T_am']-273.17, 'g', label='amb')
278 | ax[1].set_ylabel('Temperature ($^\circ$C)')
279 | ax[1].set_xlabel('Time (h)')
280 | ax[1].legend(loc='lower right')
281 |
282 |
283 | # Using the default emulator
284 | # The default emulator simply reuses the control solution. The results are a bit different due to model mismatch.
285 | def_emulator = mpcpy.Emulator(['T_am', 'Q_flow_so', 'Q_flow_hp'],initial_conditions=emulator_initial_conditions)
286 | emulator.initialize()
287 |
288 | def_stateestimation = StateestimationPerfect(def_emulator)
289 | def_control = LinearProgram(def_stateestimation, prediction,
290 | parameters=control_parameters, horizon=24*3600., timestep=3600.)
291 | def_mpc = mpcpy.MPC(def_emulator, def_control, disturbances, emulationtime=1*24*3600., resulttimestep=60)
292 | def_res = def_mpc(verbose=1)
293 |
294 | fix, ax = plt.subplots(2, 1)
295 | ax[0].plot(def_res['time']/3600, def_res['Q_flow_hp'], 'k', label='hp')
296 | ax[0].plot(res['time']/3600, res['Q_flow_hp'], 'k--')
297 | ax[0].plot(def_res['time']/3600, def_res['Q_flow_so'], 'g', label='sol')
298 | ax[0].set_ylabel('Heat flow rate (W)')
299 | ax[0].legend(loc='lower right')
300 |
301 | ax[1].plot(def_res['time']/3600, def_res['T_in']-273.17, 'k', label='in')
302 | ax[1].plot(def_res['time']/3600, def_res['T_em']-273.17, 'b', label='em')
303 | ax[1].plot(def_res['time']/3600, def_res['T_am']-273.17, 'g', label='amb')
304 | ax[1].plot(res['time']/3600, res['T_in']-273.17, 'k--')
305 | ax[1].plot(res['time']/3600, res['T_em']-273.17, 'b--')
306 | ax[1].set_ylabel('Temperature ($^\circ$C)')
307 | ax[1].set_xlabel('Time (h)')
308 | ax[1].legend(loc='lower right')
309 |
310 |
311 | if __name__ == '__main__':
312 | plt.show()
313 |
--------------------------------------------------------------------------------
/mpcpy/__init__.py:
--------------------------------------------------------------------------------
1 | from .__version__ import version as __version__
2 |
3 | __all__ = ['disturbances.py', 'control', 'emulator', 'mpc', 'prediction', 'stateestimation']
4 |
5 | from .disturbances import Disturbances
6 | from .control import *
7 | from .emulator import *
8 | from .mpc import MPC
9 | from .prediction import Prediction
10 | from .stateestimation import Stateestimation
11 |
--------------------------------------------------------------------------------
/mpcpy/__version__.py:
--------------------------------------------------------------------------------
1 | version = '0.3.0'
--------------------------------------------------------------------------------
/mpcpy/control.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | ################################################################################
3 | # Copyright 2015 Brecht Baeten
4 | # This file is part of mpcpy.
5 | #
6 | # mpcpy is free software: you can redistribute it and/or modify
7 | # it under the terms of the GNU General Public License as published by
8 | # the Free Software Foundation, either version 3 of the License, or
9 | # (at your option) any later version.
10 | #
11 | # mpcpy is distributed in the hope that it will be useful,
12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | # GNU General Public License for more details.
15 | #
16 | # You should have received a copy of the GNU General Public License
17 | # along with mpcpy. If not, see .
18 | ################################################################################
19 |
20 | import sys
21 | import numpy as np
22 |
23 | class Control(object):
24 | """
25 | Base class for defining the control for an mpc simulation
26 |
27 | the :code:`formulation` and :code:`solution` methods must be redefined in a
28 | child class to generate control signals over the control horizon
29 |
30 | """
31 |
32 | def __init__(self, stateestimation, prediction,
33 | parameters=None, horizon=None, timestep=None, receding=None, savesolutions=0):
34 | """
35 | Initializes the control object
36 |
37 | Parameters
38 | ----------
39 | stateestimation : mpcpy.Stateestimation
40 | The object used to determine the state at the beginning of the
41 | control horizon.
42 |
43 | prediction : mpcpy.Prediction object
44 | The object used to determine the predictions over the control
45 | horizon.
46 |
47 | parameters : dict
48 | Dictionary specifying control parameters.
49 |
50 | horizon : number
51 | The length of the control horizon.
52 |
53 | timestep : number
54 | The length of the control timestep.
55 |
56 | receding : number
57 | The receding time, i.e. the time between subsequent calls to
58 | this control object.
59 |
60 | savesolutions : int
61 | Number of control solutions to be saved in the control object. Set
62 | to -1 to save all solutions.
63 |
64 | """
65 |
66 | self.stateestimation = stateestimation
67 | self.prediction = prediction
68 |
69 | if horizon is None:
70 | raise Exception('horizon parameter must be supplied')
71 | else:
72 | self.horizon = horizon
73 |
74 | if timestep is None:
75 | raise Exception('timestep parameter must be supplied')
76 | else:
77 | self.timestep = timestep
78 |
79 | self.receding = receding
80 | if self.receding is None:
81 | self.receding = self.timestep
82 |
83 | self.parameters = {}
84 | if not parameters is None:
85 | self.parameters = parameters
86 |
87 | self.savesolutions = savesolutions
88 | self.solutions = []
89 |
90 | self._formulated = False
91 |
92 | def time(self,starttime):
93 | """
94 | Returns a time vector over the control horizon with the defined timestep
95 |
96 | Parameters
97 | ----------
98 | starttime : real
99 | Time at the beginning of the control horizon.
100 |
101 | """
102 | return np.arange(starttime, starttime+self.horizon+0.01*self.timestep, self.timestep, dtype=np.float)
103 |
104 | def formulation(self):
105 | """
106 | Performs actions the first time the control is run.
107 |
108 | Can be used to set up an optimal control problem. The set-up and
109 | solution are separated as sometimes the set-up takes a significant
110 | amount of time and performs actions which must not be repeated.
111 |
112 | Should be redefined in a child class to set up the actual control
113 | algorithm.
114 |
115 | """
116 | pass
117 |
118 |
119 | def solution(self,state,prediction):
120 | """
121 | Returns the control profiles ("the plan").
122 |
123 | Should be redefined in a child class to set up the actual control
124 | algorithm.
125 |
126 | Parameters
127 | ----------
128 | state : dict
129 | Dictionary with the states at the start of the control horizon as
130 | returned by the stateestimation object.
131 |
132 | prediction : dict
133 | Dictionary with the values of predictions over the control horizon
134 | as returned by the prediction object.
135 |
136 | Returns
137 | -------
138 | dict
139 | Dictionary with the solution, "time" must be a key.
140 | """
141 | sol = {}
142 | return sol
143 |
144 |
145 | def __call__(self,starttime):
146 | """
147 | Calculate the value of the control signal over the control horizon.
148 | Calls the :code:`solution` method.
149 |
150 | Parameters
151 | ----------
152 | starttime : real
153 | Time at the beginning of the control horizon.
154 |
155 | Returns
156 | -------
157 | dict
158 | A dictionary with representing the control signals with time.
159 |
160 | """
161 |
162 | # get the state and the predictions
163 | state = self.stateestimation(starttime)
164 | prediction = self.prediction(self.time(starttime))
165 |
166 | # formulate the ocp during the first call
167 | if not self._formulated:
168 | tempsolution = self.formulation()
169 | if tempsolution != None:
170 | print('Warning: returning a solution function from the "formulation" method is depreciated. Overwrite the "solution" method instead.')
171 | self.solution = tempsolution
172 |
173 | self._formulated = True
174 |
175 | # solve the ocp
176 | solution = self.solution(state,prediction)
177 |
178 |
179 | if self.savesolutions == -1:
180 | # save all solutions
181 | self.solutions.append(solution)
182 |
183 | elif self.savesolutions > 0:
184 | # save only the last x solutions
185 | self.solutions.append(solution)
186 | if len(self.solutions) > self.savesolutions:
187 | self.solutions.pop(0)
188 |
189 | return solution
190 |
191 |
192 | def cplex_infeasibilityanalysis(ocp):
193 | """
194 | Give information about infeasible constraints in cplex.
195 |
196 | Parameters
197 | ----------
198 | ocp : CPlex object
199 | A CPlex optimization problem which is infeasible
200 |
201 | """
202 |
203 | ocp.conflict.refine(ocp.conflict.all_constraints())
204 |
205 | try:
206 | for conflict,v in enumerate(ocp.conflict.get()):
207 | if v > 0:
208 | for c in ocp.conflict.get_groups(conflict)[1]:
209 | if c[0]==1:
210 | print( 'Lower bound constraint on variable {}: {}'.format(c[1],ocp.variables.get_names(c[1])) )
211 | if c[0]==2:
212 | print( 'Upper bound constraint on variable {}: {}'.format(c[1],ocp.variables.get_names(c[1])) )
213 | if c[0]==3:
214 | print( 'Linear constraint {}: {}'.format(c[1],ocp.linear_constraints.get_names(c[1])) )
215 | else:
216 | print(ocp.conflict.get_groups(conflict))
217 | except Exception as e:
218 | pass
--------------------------------------------------------------------------------
/mpcpy/disturbances.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | ################################################################################
3 | # Copyright 2015 Brecht Baeten
4 | # This file is part of mpcpy.
5 | #
6 | # mpcpy is free software: you can redistribute it and/or modify
7 | # it under the terms of the GNU General Public License as published by
8 | # the Free Software Foundation, either version 3 of the License, or
9 | # (at your option) any later version.
10 | #
11 | # mpcpy is distributed in the hope that it will be useful,
12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | # GNU General Public License for more details.
15 | #
16 | # You should have received a copy of the GNU General Public License
17 | # along with mpcpy. If not, see .
18 | ################################################################################
19 |
20 | import numpy as np
21 |
22 |
23 | class Disturbances(object):
24 | """
25 | A class to define disturbances in the format required by mpcpy.
26 |
27 | """
28 |
29 | def __init__(self, data, periodic=True, extra_time=7*24*3600., zoh_keys=None):
30 | """
31 | Create a disturbances object.
32 |
33 | Parameters
34 | ----------
35 | data : dict
36 | Actual boundary conditions and a time vector.
37 |
38 | periodic : boolean, optional
39 | Determines how to determine values when time is larger than the
40 | boundary conditions time.
41 |
42 | extra_time : float, optional
43 | Maximum allowed time outside the boundary conditions time, should be
44 | at least as large as the control horizon.
45 |
46 | zoh_keys : list of strings, optional
47 | Keys which will be interpolated with zero-order hold. All other
48 | values are interpolated linearly.
49 |
50 | Examples
51 | --------
52 | >>> dst = Disturbances({'time': np.arange(0.,24*3600.+1,3600.), 'T_amb':np.random.random(25)})
53 | >>> dst(12.1*3600)
54 |
55 | """
56 |
57 | self.data = {}
58 |
59 | # create a new time vector including the extra time
60 | # this method is about 2 times faster than figuring out the correct time during interpolation
61 | ind = np.where(data['time']-data['time'][0] < extra_time)[0]
62 | self.data['time'] = np.concatenate((data['time'][:-1], data['time'][ind]+data['time'][-1]-data['time'][0]))
63 |
64 | if periodic:
65 | # the values at time lower than extra_time are repeated at the end of the dataset
66 | # extra_time should thus be larger than the control horizon
67 | for key in data:
68 | if key != 'time':
69 | self.data[key] = np.concatenate((data[key][:-1], data[key][ind]))
70 | else:
71 | # last value is repeated after the actual data
72 | for key in data:
73 | if key != 'time':
74 | self.data[key] = np.concatenate((data[key][:-1], data[key][-1]*np.ones(len(ind))))
75 |
76 | if zoh_keys is None:
77 | self.zoh_keys = []
78 | else:
79 | self.zoh_keys = zoh_keys
80 |
81 | def interp(self, key, time):
82 | """
83 | Interpolate a value to an array of timesteps
84 |
85 | Parameters
86 | ----------
87 | key : str
88 | The key to interpolate.
89 |
90 | time : np.array
91 | An array of times to interpolate to.
92 |
93 | """
94 |
95 | if len(np.array(self.data[key]).shape) == 1:
96 | if key in self.zoh_keys:
97 | value = interp_zoh(time, self.data['time'], self.data[key])
98 | else:
99 | value = np.interp(time, self.data['time'], self.data[key])
100 |
101 | elif len(np.array(self.data[key]).shape) == 2:
102 | # 2d boundary conditions support
103 | value = np.zeros((len(time), self.data[key].shape[1]))
104 | if key in self.zoh_keys:
105 | for j in range(self.data[key].shape[1]):
106 | value[:, j] = interp_zoh(time, self.data['time'], self.data[key][:, j])
107 | else:
108 | for j in range(self.data[key].shape[1]):
109 | value[:, j] = np.interp(time, self.data['time'], self.data[key][:, j])
110 | else:
111 | raise Exception('Only 1D or 2D data allowed as boundary conditions')
112 |
113 | return value
114 |
115 | def __call__(self, time):
116 | """
117 | Return the interpolated boundary conditions
118 |
119 | Parameters
120 | ----------
121 | time : number or np.array
122 | true value for time
123 |
124 | Returns
125 | -------
126 | dict
127 | Dictionary with interpolated boundary conditions.
128 |
129 | """
130 |
131 | dst_int = {}
132 | for key in self.data:
133 | dst_int[key] = self.interp(key, time)
134 |
135 | return dst_int
136 |
137 | def __getitem__(self, key):
138 | return self.data[key]
139 |
140 | def has_key(self, key):
141 | return self.data.has_key(key)
142 |
143 | def __contains__(self, item):
144 | return item in self.data
145 |
146 | def __iter__(self):
147 | return self.data.__iter__()
148 |
149 |
150 | def interp_zoh(x, xp, fp):
151 | """
152 | Interpolate with zero order hold
153 |
154 | Parameters
155 | ----------
156 | x : np.array
157 | An array of independent variables where the values are required.
158 |
159 | xp : np.array
160 | An array of independent variables where the values are known, must be
161 | monotonic and increasing.
162 |
163 | fp : np.array
164 | The known values at points xp.
165 |
166 | Returns
167 | -------
168 | np.array
169 | The interpolated values
170 |
171 | """
172 |
173 | return np.array([fp[int((len(xp)-1)*(xi-xp[0])/(xp[-1]-xp[0]))] for xi in x])
174 |
--------------------------------------------------------------------------------
/mpcpy/emulator.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | ################################################################################
3 | # Copyright 2015 Brecht Baeten
4 | # This file is part of mpcpy.
5 | #
6 | # mpcpy is free software: you can redistribute it and/or modify
7 | # it under the terms of the GNU General Public License as published by
8 | # the Free Software Foundation, either version 3 of the License, or
9 | # (at your option) any later version.
10 | #
11 | # mpcpy is distributed in the hope that it will be useful,
12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | # GNU General Public License for more details.
15 | #
16 | # You should have received a copy of the GNU General Public License
17 | # along with mpcpy. If not, see .
18 | ################################################################################
19 |
20 | import numpy as np
21 |
22 |
23 | class Emulator(object):
24 | """
25 | Base class for defining an emulator object
26 |
27 | """
28 |
29 | def __init__(self, input_keys, parameters=None, initial_conditions=None):
30 | """
31 | Initializes the emulator object
32 | :code:`self.inputs` and :code:`self.res` attributes must be defined
33 |
34 | Parameters
35 | ----------
36 | input_keys : list of strings
37 | list of strings of inputs. This is done so that not all data
38 | from the boundary conditions and control signals have to be
39 | transferred to the simulation. Only the boundary conditions and
40 | control signals in the :code:`inputs` attribute are interpolated and
41 | passed to the :code:`__call__` method.
42 |
43 | parameters : dict
44 | A dictionary of parameters used by the emulator.
45 |
46 | initial_conditions : dict
47 | A dictionary of initial conditions of the system under
48 | consideration.
49 | """
50 |
51 | self.inputs = input_keys
52 | self.initial_conditions = {}
53 | if not initial_conditions is None:
54 | # set only the last value for each key
55 | for key in initial_conditions:
56 | try:
57 | self.initial_conditions[key] = initial_conditions[key][-1]
58 | except:
59 | self.initial_conditions[key] = initial_conditions[key]
60 | self.parameters = {}
61 | if not parameters is None:
62 | self.parameters = parameters
63 | self.res = {}
64 |
65 | def initialize(self):
66 | """
67 | Redefine in a child class
68 |
69 | This method is called once before the start of the MPC and by default
70 | clears the results dictionary and then add the initial conditions to it
71 | at time 0.
72 |
73 | """
74 |
75 | self.res = {
76 | 'time': np.array([0.])
77 | }
78 | for key in self.initial_conditions:
79 | self.res[key] = np.array([self.initial_conditions[key]])
80 |
81 | def simulate(self, starttime, stoptime, input):
82 | """
83 | Redefine in a child class
84 |
85 | This method runs the simulation and should return a dictionary with
86 | results for times between the :code:`starttime` and :code:`stoptime`
87 | given the inputs.
88 |
89 | Parameters
90 | ----------
91 | starttime : number
92 | time to start the simulation
93 |
94 | stoptime : number
95 | time to stop the simulation
96 |
97 | input : dict
98 | dictionary with values for the inputs for the simulation, 'time'
99 | and all values in self.inputs must be keys
100 |
101 | Returns
102 | -------
103 | dict
104 | dictionary with the simulation results
105 |
106 | """
107 |
108 | return {}
109 |
110 | def __call__(self, time, input):
111 | """
112 | Simulates the system and updated the results dictionary, calls the
113 | :code:`simulate`method.
114 |
115 | Parameters
116 | ----------
117 | time : numpy array
118 | Times at which the results are requested.
119 |
120 | input : dict
121 | Dictionary with values for the inputs of the model, time must be a
122 | part of it.
123 |
124 | Returns
125 | -------
126 | dict
127 | Dictionary with the complete simulation results.
128 |
129 | Examples
130 | --------
131 | >>> em = Emulator(['u1'])
132 | >>> t = np.arange(0., 3600.1, 600.)
133 | >>> u1 = 5.*np.ones_like(t)
134 | >>> em(t, ['time': t, 'u1': u1])
135 |
136 | """
137 |
138 | res = self.simulate(time[0], time[-1], input)
139 |
140 | # adding the inputs to the result
141 | for key in input.keys():
142 | # make sure not to do double adding
143 | if not key in res.keys():
144 | if key in self.res:
145 | # append the result
146 | if len(input[key]) == 1:
147 | self.res[key] = input[key]
148 | else:
149 | self.res[key] = np.append(self.res[key][:-1], np.interp(time, input['time'], input[key]))
150 | else:
151 | self.res[key] = np.interp(time, input['time'], input[key])
152 | # interpolate results to the input points in time
153 | for key in res.keys():
154 | if key in self.res:
155 | # append the result
156 | if len(res[key]) == 1:
157 | self.res[key] = res[key]
158 | else:
159 | if key == 'time':
160 | self.res[key] = np.append(self.res[key][:-1], time)
161 | else:
162 | self.res[key] = np.append(self.res[key][:-1], np.interp(time, res['time'], res[key]))
163 |
164 | else:
165 | if len(res[key]) == 1:
166 | self.res[key] = res[key]
167 | else:
168 | self.res[key] = np.interp(time, res['time'], res[key])
169 | return self.res
170 |
171 | def set_initial_conditions(self, ini):
172 | print('Warning: Depreciated,'
173 | 'set the initial conditions during the object creation with the "initial_conditions" keyword parameter.')
174 | # set only the last value for each key
175 | for key in ini:
176 | try:
177 | self.initial_conditions[key] = ini[key][-1]
178 | except:
179 | self.initial_conditions[key] = ini[key]
180 |
181 | def set_parameters(self, par):
182 | print('Warning: Depreciated,'
183 | 'set the initial conditions during the object creation with the "parameters" keyword parameter.')
184 | self.parameters = par
185 |
186 |
187 | class DympyEmulator(Emulator):
188 | """
189 | A class defining an emulator object using dympy for the simulation
190 |
191 | """
192 |
193 | def __init__(self, dymola, inputs, initializationtime=1, **kwargs):
194 | """
195 | Initialize a dympy object for use as an MPC emulation
196 |
197 | Parameters
198 | ----------
199 | dymola : dympy.Dymola
200 | a dympy object with an opened and compiled dymola model
201 |
202 | inputs : list of strings
203 | a list of strings of the variable names of the inputs
204 |
205 | initializationtime : number
206 | time to run the initialization simulation
207 |
208 | **kwargs :
209 | arguments which can be passed on to dympy
210 |
211 | """
212 |
213 | self.inputs = inputs
214 | self.initializationtime = initializationtime
215 |
216 | self.dymola = dymola
217 | self.initial_conditions = {}
218 | self.parameters = {}
219 | self.res = {}
220 |
221 | # check for additional dymola arguments
222 | self.simulation_args = {}
223 | for key in kwargs:
224 | if key in ['OutputInterval', 'NumberOfIntervals', 'Tolerance', 'FixedStepSize', 'Algorithm']:
225 | self.simulation_args[key] = kwargs[key]
226 |
227 | def initialize(self):
228 | """
229 | initializes the dympy model, by simulating it for
230 | :code:`self.initializationtime`. Afterwards the :code:`res` attribute is
231 | populated
232 |
233 | Also, the keys in parameters and initialconditions are checked. If they
234 | do not appear in the dympy results, they are removed and the model is
235 | reinitialized.
236 |
237 | """
238 |
239 | self.dymola.set_parameters(self.initial_conditions)
240 | self.dymola.set_parameters(self.parameters)
241 |
242 | # clear the result dict
243 | self.res = {}
244 |
245 | # simulate the model for a very short time to get the initial states in the res dict
246 | self.dymola.simulate(StartTime=0, StopTime=self.initializationtime)
247 | res = self.dymola.get_result()
248 |
249 | # remove the initial conditions and parameters which are not in the results file
250 | redosim = False
251 | keystoremove = []
252 | for key in self.initial_conditions:
253 | if not key in res:
254 | keystoremove.append(key)
255 | redosim = True
256 |
257 | for key in keystoremove:
258 | del self.initial_conditions[key]
259 |
260 | keystoremove = []
261 | for key in self.parameters:
262 | if not key in res:
263 | keystoremove.append(key)
264 | redosim = True
265 |
266 | for key in keystoremove:
267 | del self.parameters[key]
268 |
269 | # redo the simulation if required
270 | if redosim:
271 | self.dymola.set_parameters(self.initial_conditions)
272 |
273 | self.dymola.set_parameters(self.parameters)
274 | self.dymola.simulate(StartTime=0, StopTime=self.initializationtime)
275 | res = self.dymola.get_result()
276 | for key in res:
277 | self.res[key] = np.array([res[key][0]])
278 |
279 | def simulate(self, starttime, stoptime, input):
280 | """
281 | """
282 |
283 | self.dymola.write_dsu(input)
284 | try:
285 | self.dymola.dsfinal2dsin()
286 | except:
287 | pass
288 |
289 | try:
290 | self.dymola.simulate(StartTime=starttime, StopTime=stoptime, **self.simulation_args)
291 | except:
292 | print('Ignoring error during simulation at time {}'.format(starttime));
293 |
294 | try:
295 | res = self.dymola.get_result()
296 | except:
297 | print('Ignoring error while loading dymola res file at time {}'.format(input['time'][0]))
298 |
299 | return res
300 |
301 |
302 | def interp_averaged(t, tp, yp):
303 | y = np.zeros_like(t)
304 | for i in range(len(t)-1):
305 | y[i] = np.mean(yp[np.where((tp >= t[i]) & (tp < t[i+1]))])
306 |
307 | y[-1] = np.interp(t[-1], tp, yp)
308 |
309 | return y
310 |
--------------------------------------------------------------------------------
/mpcpy/mpc.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | ################################################################################
3 | # Copyright 2015 Brecht Baeten
4 | # This file is part of mpcpy.
5 | #
6 | # mpcpy is free software: you can redistribute it and/or modify
7 | # it under the terms of the GNU General Public License as published by
8 | # the Free Software Foundation, either version 3 of the License, or
9 | # (at your option) any later version.
10 | #
11 | # mpcpy is distributed in the hope that it will be useful,
12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | # GNU General Public License for more details.
15 | #
16 | # You should have received a copy of the GNU General Public License
17 | # along with mpcpy. If not, see .
18 | ################################################################################
19 |
20 | import sys
21 | import numpy as np
22 |
23 |
24 | class MPC(object):
25 |
26 | def __init__(self, emulator, control, disturbances,
27 | emulationtime=7 * 24 * 3600, resulttimestep=600, nextstepcalculator=None, plotfunction=None):
28 | """
29 | initialize an MPC object
30 |
31 | Parameters
32 | ----------
33 | emulator : mpcpy.Emulator
34 | The emulator object to be used.
35 |
36 | control : mpcpy.Control
37 | The control object to be used.
38 |
39 | disturbances : mpcpy.Disturbances
40 | The disturbances object to be used.
41 |
42 | emulationtime : number
43 | The total time of the simulation.
44 |
45 | resulttimestep : number
46 | The timestep for which the results are returned.
47 |
48 | nextstepcalculator : function
49 | Function returning an integer representing the number of receding
50 | timesteps to skip. When not specified, no steps are skipped and the
51 | next step is 1.
52 |
53 | plotfunction : function
54 | A function which creates or updates a plot for live viewing of
55 | results, probably broken, untested.
56 |
57 | """
58 |
59 | self.emulator = emulator
60 | self.control = control
61 | self.disturbances = disturbances
62 |
63 | self.emulationtime = emulationtime
64 | self.resulttimestep = resulttimestep
65 |
66 | if nextstepcalculator == None:
67 | def nextstepcalculator(controlsolution):
68 | return 1
69 |
70 | self.nextstepcalculator = nextstepcalculator
71 |
72 | self.plotfunction = plotfunction
73 |
74 | self.res = {}
75 | self.appendres = {}
76 |
77 | def __call__(self, verbose=0):
78 | """
79 | Runs the mpc simulation
80 |
81 | Parameters
82 | ----------
83 | verbose: optional, int
84 | Controls the amount of print output
85 |
86 | Returns
87 | -------
88 | dict
89 | A dictionary with results, also stored in the res attribute.
90 |
91 | """
92 |
93 | # initialize the emulator
94 | self.emulator.initialize()
95 | starttime = 0
96 |
97 | if self.plotfunction:
98 | (fig,ax,pl) = self.plotfunction()
99 |
100 | # prepare a progress bar
101 | barwidth = 80-2
102 | barvalue = 0
103 | if verbose > 0:
104 | print('Running MPC')
105 | print('[' + (' '*barwidth) + ']', end='')
106 |
107 | while starttime < self.emulationtime:
108 |
109 | # calculate control signals for the control horizon
110 | control = self.control(starttime)
111 |
112 | # create a simulation time vector
113 | nextStep = self.nextstepcalculator(control)
114 | time = np.arange(
115 | starttime,
116 | min(self.emulationtime+self.resulttimestep, starttime+nextStep*self.control.receding+0.01*self.resulttimestep),
117 | self.resulttimestep, dtype=np.float
118 | )
119 | time[-1] = min(time[-1], self.emulationtime)
120 |
121 | # create input of all controls and the required boundary conditions
122 | # add times at the control time steps minus 1e-6 times the result time step to achieve zero order hold
123 | ind = np.where(
124 | (control['time']-1e-6*self.resulttimestep > time[0])
125 | & (control['time']-1e-6*self.resulttimestep <= time[-1])
126 | )
127 | inputtime = np.sort(np.concatenate((time, control['time'][ind]-1e-6*self.resulttimestep)))
128 | input = {'time': inputtime}
129 |
130 | # add controls first
131 | for key in control:
132 | if not key in input:
133 | input[key] = interp_zoh(input['time'], control['time'], control[key])
134 |
135 | # add the rest of the inputs from the boundary conditions
136 | for key in self.emulator.inputs:
137 | if not key in input and key in self.disturbances:
138 | input[key] = self.disturbances.interp(key, input['time'])
139 | elif not key in input:
140 | print('Warning {} not found in disturbances object'.format(key))
141 |
142 | # prepare and run the simulation
143 | self.emulator(time, input)
144 |
145 | # plot results
146 | if self.plotfunction:
147 | self.plotfunction(pl=pl, res=self.emulator.res)
148 |
149 | # update starting time
150 | starttime = self.emulator.res['time'][-1]
151 |
152 | # update the progress bar
153 | if verbose > 0:
154 | if starttime/self.emulationtime*barwidth >= barvalue:
155 | barvalue += int(round(starttime/self.emulationtime*barwidth-barvalue))
156 | print('\r[' + ('='*barvalue) + (' '*(barwidth-barvalue)) + ']', end='')
157 |
158 | # copy the results to a local res dictionary
159 | self.res.update(self.emulator.res)
160 |
161 | # interpolate the boundary conditions and add them to self.res
162 | self.res.update(self.disturbances(self.res['time']))
163 | if verbose > 0:
164 | print(' done')
165 |
166 | return self.res
167 |
168 |
169 | def interp_zoh(x, xp, fp):
170 | return np.array([fp[int((len(xp)-1)*(xi-xp[0])/(xp[-1]-xp[0]))] for xi in x])
171 |
--------------------------------------------------------------------------------
/mpcpy/prediction.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | ################################################################################
3 | # Copyright 2015 Brecht Baeten
4 | # This file is part of mpcpy.
5 | #
6 | # mpcpy is free software: you can redistribute it and/or modify
7 | # it under the terms of the GNU General Public License as published by
8 | # the Free Software Foundation, either version 3 of the License, or
9 | # (at your option) any later version.
10 | #
11 | # mpcpy is distributed in the hope that it will be useful,
12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | # GNU General Public License for more details.
15 | #
16 | # You should have received a copy of the GNU General Public License
17 | # along with mpcpy. If not, see .
18 | ################################################################################
19 |
20 | import sys
21 | import numpy as np
22 |
23 | class Prediction(object):
24 | """
25 | Base class for defining the predictions for an mpc the "prediction" method
26 | can be redefined in a child class. If not it returns a perfect prediction of
27 | all future disturbances.
28 | """
29 |
30 | def __init__(self,boundaryconditions,parameters=None):
31 | """
32 |
33 | Parameters
34 | ----------
35 | boundaryconditions: mpcpy.Disturbances
36 | An :code:`mpcpy.Boundaryconditions` object to derive the predictions from.
37 |
38 | parameters : dict
39 | A dictionary of parameters used by the prediction algorithm.
40 | """
41 |
42 | self.boundaryconditions = boundaryconditions
43 |
44 | self.parameters = {}
45 | if not parameters is None:
46 | self.parameters = parameters
47 |
48 | def prediction(self,time):
49 | """
50 | Defines perfect predictions, returns the exact boundary conditions dict
51 | Can be redefined in a child class to contain an actual prediction
52 | algorithm.
53 |
54 | Parameters
55 | ----------
56 | time : np.array
57 | The times at which the predictions are required
58 |
59 | Returns
60 | -------
61 | dict
62 | A dictionary with the predictions at the specified times
63 |
64 | """
65 | return self.boundaryconditions(time)
66 |
67 |
68 | def __call__(self,time):
69 | return self.prediction(time)
--------------------------------------------------------------------------------
/mpcpy/stateestimation.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | ################################################################################
3 | # Copyright 2015 Brecht Baeten
4 | # This file is part of mpcpy.
5 | #
6 | # mpcpy is free software: you can redistribute it and/or modify
7 | # it under the terms of the GNU General Public License as published by
8 | # the Free Software Foundation, either version 3 of the License, or
9 | # (at your option) any later version.
10 | #
11 | # mpcpy is distributed in the hope that it will be useful,
12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | # GNU General Public License for more details.
15 | #
16 | # You should have received a copy of the GNU General Public License
17 | # along with mpcpy. If not, see .
18 | ################################################################################
19 |
20 | import sys
21 | import numpy as np
22 |
23 | class Stateestimation(object):
24 | """
25 | Base class for defining the state estimation for an mpc
26 | the "stateestimation" method must be redefined in a child class.
27 |
28 | """
29 |
30 | def __init__(self,emulator,parameters=None):
31 | """
32 | Parameters
33 | ----------
34 | emulator : mpcpy.Emulator
35 | An :code:`mpcpy.Emulator` object from which the state should be estimated.
36 |
37 | parameters : dict, optional
38 | Optional parameter dictionary.
39 |
40 | """
41 |
42 | self.emulator = emulator
43 | self.parameters = parameters
44 |
45 |
46 | def stateestimation(self,time):
47 | """
48 | Must be redefined in a child class to return a dictionary with the
49 | estimated state at the specified time as required by the control object.
50 |
51 | Parameters
52 | ----------
53 | time : number
54 | The time at which the state should be estimated.
55 |
56 | Returns
57 | -------
58 | dict
59 | A dictionary with key-value pairs representing the state.
60 |
61 | """
62 |
63 | return None
64 |
65 |
66 | def __call__(self,time):
67 | """
68 | Returns the state at a given time as computed by the
69 | :code:`stateestimation` method.
70 |
71 | Parameters
72 | ----------
73 | time : number
74 | The time at which the state should be estimated.
75 |
76 | Returns
77 | -------
78 | dict
79 | A dictionary with key-value pairs representing the state.
80 |
81 | """
82 | return self.stateestimation(time)
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | from setuptools import setup, find_packages
3 | import os
4 |
5 | setuppath = os.path.dirname(os.path.abspath(__file__))
6 |
7 | # retrieve the version
8 | try:
9 | versionfile = os.path.join(setuppath, 'mpcpy', '__version__.py')
10 | f = open(versionfile, 'r')
11 | content = f.readline()
12 | splitcontent = content.split('\'')
13 | version = splitcontent[1]
14 | f.close()
15 | except:
16 | raise Exception('Could not determine the version from mpcpy/__version__.py')
17 |
18 |
19 | # run the setup command
20 | setup(
21 | name='mpcpy',
22 | version=version,
23 | license='GPLv3',
24 | description='A package to run MPC, moving horizon simulations in Python.',
25 | long_description=open(os.path.join(setuppath, 'README.rst')).read(),
26 | url='https://github.com/BrechtBa/mpcpy',
27 | author='Brecht Baeten',
28 | author_email='brecht.baeten@gmail.com',
29 | packages=find_packages(),
30 | install_requires=['numpy'],
31 | extras_require={
32 | 'dev': [
33 | 'pyomo',
34 | 'matplotlib'
35 | ]
36 | },
37 | classifiers=['Programming Language :: Python :: 2.7'],
38 | )
--------------------------------------------------------------------------------
/tests/.gitignore:
--------------------------------------------------------------------------------
1 | dsin.txt
--------------------------------------------------------------------------------
/tests/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/BrechtBa/mpcpy/108b7a19bc07f17b1fae30ee8ecfdd1e732c1c47/tests/__init__.py
--------------------------------------------------------------------------------
/tests/all.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | ################################################################################
3 | # Copyright 2015 Brecht Baeten
4 | # This file is part of mpcpy.
5 | #
6 | # mpcpy is free software: you can redistribute it and/or modify
7 | # it under the terms of the GNU General Public License as published by
8 | # the Free Software Foundation, either version 3 of the License, or
9 | # (at your option) any later version.
10 | #
11 | # mpcpy is distributed in the hope that it will be useful,
12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | # GNU General Public License for more details.
15 | #
16 | # You should have received a copy of the GNU General Public License
17 | # along with mpcpy. If not, see .
18 | ################################################################################
19 |
20 | import unittest
21 |
22 | from .boundaryconditions import *
23 | from .prediction import *
24 | from .stateestimation import *
25 | from .emulator import *
26 | from .examples import *
27 |
28 | if __name__ == '__main__':
29 | unittest.main()
30 |
--------------------------------------------------------------------------------
/tests/boundaryconditions.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | ################################################################################
3 | # Copyright 2015 Brecht Baeten
4 | # This file is part of mpcpy.
5 | #
6 | # mpcpy is free software: you can redistribute it and/or modify
7 | # it under the terms of the GNU General Public License as published by
8 | # the Free Software Foundation, either version 3 of the License, or
9 | # (at your option) any later version.
10 | #
11 | # mpcpy is distributed in the hope that it will be useful,
12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | # GNU General Public License for more details.
15 | #
16 | # You should have received a copy of the GNU General Public License
17 | # along with mpcpy. If not, see .
18 | ################################################################################
19 |
20 | import unittest
21 | import mpcpy
22 | import numpy as np
23 |
24 |
25 | # define variables
26 | time = np.arange(0.0,7*24*3600.+1.,900.)
27 | y0 = np.sin(time/(24*3600.))
28 | y1 = np.random.random(len(time))
29 | bcs = {'time':time, 'y0':y0, 'y1':y1}
30 |
31 | class TestBoundaryconditions(unittest.TestCase):
32 |
33 | def test_create(self):
34 | boundaryconditions = mpcpy.Disturbances(bcs)
35 |
36 | def test_create_periodic(self):
37 | boundaryconditions = mpcpy.Disturbances(bcs, periodic=True)
38 | boundaryconditions = mpcpy.Disturbances(bcs, periodic=False)
39 |
40 | def test_create_extratime(self):
41 | boundaryconditions = mpcpy.Disturbances(bcs, extra_time=1 * 24 * 3600)
42 | boundaryconditions = mpcpy.Disturbances(bcs, periodic=False, extra_time=1 * 24 * 3600)
43 |
44 | def test_getitem(self):
45 | boundaryconditions = mpcpy.Disturbances(bcs)
46 | temp = boundaryconditions['y0']
47 |
48 | def test_value(self):
49 | boundaryconditions = mpcpy.Disturbances(bcs)
50 |
51 | t0 = 1*24*3600.
52 | val = boundaryconditions(t0)
53 |
54 | self.assertEqual(val,{'time':t0,'y0':np.interp(t0,time,y0),'y1':np.interp(t0,time,y1)})
55 |
56 | def test_value_periodic(self):
57 | boundaryconditions = mpcpy.Disturbances(bcs)
58 |
59 | t0 = 1*24*3600.
60 | t1 = t0 + time[-1]
61 |
62 | val0 = boundaryconditions(t0)
63 | val1 = boundaryconditions(t1)
64 |
65 | self.assertEqual(val0['y0'],val1['y0'])
66 | self.assertEqual(val0['y1'],val1['y1'])
67 |
68 | def test_value_periodic_timeoffset(self):
69 | bcs_timeoffset = dict(bcs)
70 | bcs_timeoffset['time'] = bcs_timeoffset['time'] + 2*24*3600.
71 | boundaryconditions = mpcpy.Disturbances(bcs_timeoffset)
72 |
73 | t0 = 3*24*3600.
74 | t1 = t0 + (time[-1]-time[0])
75 |
76 | val0 = boundaryconditions(t0)
77 | val1 = boundaryconditions(t1)
78 |
79 | self.assertEqual(val0['y0'],val1['y0'])
80 | self.assertEqual(val0['y1'],val1['y1'])
81 |
82 | def test_value_notperiodic(self):
83 | boundaryconditions = mpcpy.Disturbances(bcs, periodic=False)
84 |
85 | t0 = 1*24*3600.
86 | t1 = t0 + time[-1]
87 |
88 | val0 = boundaryconditions(time[-1])
89 | val1 = boundaryconditions(t1)
90 |
91 | self.assertEqual(val0['y0'],val1['y0'])
92 | self.assertEqual(val0['y1'],val1['y1'])
93 |
94 |
95 |
96 | if __name__ == '__main__':
97 | unittest.main()
--------------------------------------------------------------------------------
/tests/data/example.mo:
--------------------------------------------------------------------------------
1 | within ;
2 | model example
3 | Modelica.Thermal.HeatTransfer.Components.HeatCapacitor C_em(C=1) annotation (
4 | Placement(transformation(
5 | extent={{-10,-10},{10,10}},
6 | rotation=180,
7 | origin={-30,-26})));
8 | Modelica.Thermal.HeatTransfer.Components.HeatCapacitor C_in(C=1) annotation (
9 | Placement(transformation(
10 | extent={{-10,-10},{10,10}},
11 | rotation=180,
12 | origin={10,-26})));
13 | Modelica.Thermal.HeatTransfer.Components.ThermalConductor UA_em_in(G=1)
14 | annotation (Placement(transformation(extent={{-20,-10},{0,10}})));
15 | Modelica.Thermal.HeatTransfer.Components.ThermalConductor UA_in_amb(G=1)
16 | annotation (Placement(transformation(extent={{20,-10},{40,10}})));
17 | Modelica.Thermal.HeatTransfer.Sources.PrescribedTemperature
18 | prescribedTemperature_amb annotation (Placement(transformation(
19 | extent={{-10,-10},{10,10}},
20 | rotation=180,
21 | origin={70,0})));
22 | Modelica.Thermal.HeatTransfer.Sources.PrescribedHeatFlow
23 | prescribedHeatFlow_hp annotation (Placement(transformation(
24 | extent={{-10,-10},{10,10}},
25 | rotation=270,
26 | origin={-58,30})));
27 | Modelica.Blocks.Interfaces.RealInput Q_flow_hp
28 | annotation (Placement(transformation(extent={{-120,30},{-80,70}})));
29 | Modelica.Blocks.Interfaces.RealInput T_amb annotation (Placement(
30 | transformation(
31 | extent={{-20,-20},{20,20}},
32 | rotation=270,
33 | origin={50,100})));
34 | Modelica.Blocks.Interfaces.RealInput Q_flow_sol annotation (Placement(
35 | transformation(
36 | extent={{-20,-20},{20,20}},
37 | rotation=270,
38 | origin={10,100})));
39 | Modelica.Thermal.HeatTransfer.Sources.PrescribedHeatFlow
40 | prescribedHeatFlow_sol annotation (Placement(transformation(
41 | extent={{-10,-10},{10,10}},
42 | rotation=270,
43 | origin={10,30})));
44 | equation
45 | connect(UA_in_amb.port_b, prescribedTemperature_amb.port)
46 | annotation (Line(points={{40,0},{60,0}}, color={191,0,0}));
47 | connect(UA_in_amb.port_a, C_in.port)
48 | annotation (Line(points={{20,0},{10,0},{10,-16}}, color={191,0,0}));
49 | connect(UA_em_in.port_b, C_in.port)
50 | annotation (Line(points={{0,0},{10,0},{10,-16}}, color={191,0,0}));
51 | connect(UA_em_in.port_a, C_em.port)
52 | annotation (Line(points={{-20,0},{-30,0},{-30,-16}}, color={191,0,0}));
53 | connect(prescribedHeatFlow_hp.port, C_em.port) annotation (Line(points={{-58,
54 | 20},{-58,0},{-30,0},{-30,-16}}, color={191,0,0}));
55 | connect(prescribedHeatFlow_sol.port, C_in.port)
56 | annotation (Line(points={{10,20},{10,-16}}, color={191,0,0}));
57 | connect(Q_flow_hp, prescribedHeatFlow_hp.Q_flow)
58 | annotation (Line(points={{-100,50},{-58,50},{-58,40}}, color={0,0,127}));
59 | connect(Q_flow_sol, prescribedHeatFlow_sol.Q_flow) annotation (Line(points={{
60 | 10,100},{10,100},{10,40},{10,40}}, color={0,0,127}));
61 | connect(T_amb, prescribedTemperature_amb.T) annotation (Line(points={{50,100},
62 | {50,100},{50,46},{88,46},{88,0},{82,0}}, color={0,0,127}));
63 | annotation (uses(Modelica(version="3.2.1")), Diagram(coordinateSystem(
64 | preserveAspectRatio=false, extent={{-100,-100},{100,100}})));
65 | end example;
66 |
--------------------------------------------------------------------------------
/tests/emulator.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | ################################################################################
3 | # Copyright 2015 Brecht Baeten
4 | # This file is part of mpcpy.
5 | #
6 | # mpcpy is free software: you can redistribute it and/or modify
7 | # it under the terms of the GNU General Public License as published by
8 | # the Free Software Foundation, either version 3 of the License, or
9 | # (at your option) any later version.
10 | #
11 | # mpcpy is distributed in the hope that it will be useful,
12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | # GNU General Public License for more details.
15 | #
16 | # You should have received a copy of the GNU General Public License
17 | # along with mpcpy. If not, see .
18 | ################################################################################
19 |
20 | import unittest
21 | import mpcpy
22 | import numpy as np
23 | import sys
24 | import os
25 |
26 |
27 | # current path
28 | modulepath = os.path.abspath(os.path.dirname(sys.modules[__name__].__file__))
29 |
30 |
31 | class TestEmulator(unittest.TestCase):
32 | def setUp(self):
33 |
34 | self.ini = {'C_em.T': 22+273.15, 'C_in.T': 21+273.15}
35 | self.par = {'C_em.C': 10e6,
36 | 'C_in.C': 5e6,
37 | 'UA_in_amb.G': 200,
38 | 'UA_em_in.G': 1600}
39 | self.inp = {
40 | 'time': np.array([0. , 3600. , 7200.]),
41 | 'T_amb': np.array([273.15, 274.15, 275.15]),
42 | 'Q_flow_sol': np.array([500. , 400. , 300.]),
43 | 'Q_flow_hp': np.array([4000. , 4000. , 4000.])
44 | }
45 |
46 | def test_create(self):
47 | emulator = mpcpy.Emulator([])
48 |
49 |
50 | def test_call(self):
51 | emulator = mpcpy.Emulator([])
52 | emulator(self.inp['time'],self.inp)
53 |
54 | self.assertEqual(emulator.res['time'][1],self.inp['time'][1])
55 | self.assertEqual(emulator.res['Q_flow_sol'][2],self.inp['Q_flow_sol'][2])
56 |
57 | if __name__ == '__main__':
58 | unittest.main()
--------------------------------------------------------------------------------
/tests/examples.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | ################################################################################
3 | # Copyright 2015 Brecht Baeten
4 | # This file is part of mpcpy.
5 | #
6 | # mpcpy is free software: you can redistribute it and/or modify
7 | # it under the terms of the GNU General Public License as published by
8 | # the Free Software Foundation, either version 3 of the License, or
9 | # (at your option) any later version.
10 | #
11 | # mpcpy is distributed in the hope that it will be useful,
12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | # GNU General Public License for more details.
15 | #
16 | # You should have received a copy of the GNU General Public License
17 | # along with mpcpy. If not, see .
18 | ################################################################################
19 |
20 |
21 | import unittest
22 |
23 |
24 | class TestExamples(unittest.TestCase):
25 |
26 | def test_simple_space_heating_mpc(self):
27 | from examples import simple_space_heating_mpc
28 |
29 | def test_quickstart(self):
30 | from examples import quickstart
31 |
32 |
33 | if __name__ == '__main__':
34 | unittest.main()
--------------------------------------------------------------------------------
/tests/prediction.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | ################################################################################
3 | # Copyright 2015 Brecht Baeten
4 | # This file is part of mpcpy.
5 | #
6 | # mpcpy is free software: you can redistribute it and/or modify
7 | # it under the terms of the GNU General Public License as published by
8 | # the Free Software Foundation, either version 3 of the License, or
9 | # (at your option) any later version.
10 | #
11 | # mpcpy is distributed in the hope that it will be useful,
12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | # GNU General Public License for more details.
15 | #
16 | # You should have received a copy of the GNU General Public License
17 | # along with mpcpy. If not, see .
18 | ################################################################################
19 |
20 | import unittest
21 | import mpcpy
22 | import numpy as np
23 |
24 |
25 | # define variables
26 | time = np.arange(0.0,7*24*3600.+1.,900.)
27 | y0 = np.sin(time/(24*3600.))
28 | y1 = np.random.random(len(time))
29 | bcs = {'time':time, 'y0':y0, 'y1':y1}
30 |
31 | boundaryconditions = mpcpy.Disturbances(bcs)
32 |
33 |
34 | class TestPrediction(unittest.TestCase):
35 |
36 | def test_create(self):
37 | prediction = mpcpy.Prediction(boundaryconditions)
38 |
39 | def test_value(self):
40 | prediction = mpcpy.Prediction(boundaryconditions)
41 |
42 | t0 = 1*24*3600.
43 |
44 | self.assertEqual(prediction(t0),boundaryconditions(t0))
45 |
46 |
47 |
48 | if __name__ == '__main__':
49 | unittest.main()
--------------------------------------------------------------------------------
/tests/stateestimation.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | ################################################################################
3 | # Copyright 2015 Brecht Baeten
4 | # This file is part of mpcpy.
5 | #
6 | # mpcpy is free software: you can redistribute it and/or modify
7 | # it under the terms of the GNU General Public License as published by
8 | # the Free Software Foundation, either version 3 of the License, or
9 | # (at your option) any later version.
10 | #
11 | # mpcpy is distributed in the hope that it will be useful,
12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | # GNU General Public License for more details.
15 | #
16 | # You should have received a copy of the GNU General Public License
17 | # along with mpcpy. If not, see .
18 | ################################################################################
19 |
20 | import unittest
21 | import mpcpy
22 | import numpy as np
23 |
24 | # define variables
25 | val = 123
26 |
27 | class TestStateestimation(unittest.TestCase):
28 |
29 | def test_create(self):
30 | class Stateestimation(mpcpy.Stateestimation):
31 | def stateestimation(self,time):
32 | return val
33 |
34 | stateestimation = Stateestimation(None)
35 |
36 | def test_value(self):
37 | class Stateestimation(mpcpy.Stateestimation):
38 | def stateestimation(self,time):
39 | return val
40 |
41 | stateestimation = Stateestimation(None)
42 |
43 | self.assertEqual(stateestimation(0),val)
44 |
45 |
46 |
47 | if __name__ == '__main__':
48 | unittest.main()
--------------------------------------------------------------------------------