├── .gitignore ├── AUTHORS.rst ├── CONTRIBUTING.rst ├── COPYING.txt ├── FAQ.rst ├── MANIFEST.in ├── NEWS.rst ├── README.rst ├── TODO.org ├── TODO.org_archive ├── examples ├── eval_m_file.py ├── fir_filter.py ├── my_script.m ├── playground │ ├── sandbox.py │ ├── sandbox_cells.py │ └── sandbox_struct.py ├── print_version.py └── random_plot.py ├── matlab_wrapper ├── __init__.py ├── matlab_session.py └── typeconv.py ├── setup.py └── tests ├── leak_loops ├── putget_loop.py └── restart_loop.py └── test_matlab.py /.gitignore: -------------------------------------------------------------------------------- 1 | *.html 2 | *.pyc 3 | *.egg-info 4 | dist 5 | build 6 | docs/_build 7 | *.orig 8 | -------------------------------------------------------------------------------- /AUTHORS.rst: -------------------------------------------------------------------------------- 1 | Authors and Contributors 2 | ======================== 3 | 4 | 5 | Authors 6 | ------- 7 | 8 | * Marek Rudnicki 9 | * Joakim Möller 10 | 11 | 12 | 13 | Contributors 14 | ------------ 15 | 16 | * Michael Schutte 17 | -------------------------------------------------------------------------------- /CONTRIBUTING.rst: -------------------------------------------------------------------------------- 1 | Contributing Guidelines 2 | ======================= 3 | 4 | 5 | 6 | Reporting Issues 7 | ---------------- 8 | 9 | - Make sure that the issue is not addressed in the FAQ.rst_ file. 10 | 11 | - Provide information about your setup: 12 | 13 | - Python (version, architecture, distribution) 14 | - MATLAB (version, architecture) 15 | - OS (version, architecture) 16 | 17 | - Describe how to reproduce the issue and copy-paste the error 18 | messages in the report. 19 | 20 | - At best, provide a small code snippet, that can run by itself and 21 | illustrates the problem. 22 | 23 | - Use the `issue tracker`_. 24 | 25 | 26 | .. _FAQ.rst: FAQ.rst 27 | .. _issue tracker: https://github.com/mrkrd/matlab_wrapper/issues 28 | 29 | 30 | 31 | 32 | Contributing new Code 33 | --------------------- 34 | 35 | - Source code is located at: https://github.com/mrkrd/matlab_wrapper 36 | 37 | - Your patches or pull requests are very welcome! 38 | 39 | - Good place to start is the TODO.org_ file (best viewd in Emacs 40 | org-mode). At the moment, all new features and ideas go through 41 | this file. The status of the item can be: DONE (already 42 | implemented), TODO (some work has been started) or no status (not 43 | started). The items often contain some intended implementation 44 | details and remarks. You can also request more details through our 45 | issue tracker. 46 | 47 | - Coding style is mostly PEP8 compliant and The Zen of Python is your 48 | friend:: 49 | 50 | >>> import this 51 | 52 | - Module installation in the developer mode can be useful:: 53 | 54 | python setup.py develop --user 55 | 56 | - Each new feature should have a test case in the tests directory. 57 | Make sure that tests are passing using py.test_. 58 | 59 | - Add your name to AUTHORS.rst_ file. 60 | 61 | 62 | .. _TODO.org: TODO.org 63 | .. _py.test: http://pytest.org 64 | .. _AUTHORS.rst: AUTHORS.rst 65 | -------------------------------------------------------------------------------- /COPYING.txt: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /FAQ.rst: -------------------------------------------------------------------------------- 1 | Frequency Asked Questions 2 | ========================= 3 | 4 | 5 | Error: Unknown MATLAB location? 6 | ------------------------------- 7 | 8 | *matlab_wrapper* is unable to locate your MATLAB installation. 9 | 10 | There are several ways to fix it: 11 | 12 | 1. Include a path to the matlab executable in your PATH environment 13 | variable. You should be able to type ``matlab`` in your terminal 14 | prompt and start MATLAB. *matlab_wrapper* will try to locate the 15 | libraries based on the location of the ``matlab`` executable file. 16 | For example, put in your start-up files (.profile):: 17 | 18 | export PATH=$PATH:/opt/MATLAB_R2014a/bin 19 | 20 | 2. Set the environment variable MATLABROOT to the main MALTAB 21 | directory, which can be found in MATLAB by typing:: 22 | 23 | matlabroot 24 | 25 | Next, type in the shell or your profile file:: 26 | 27 | MATLABROOT=/opt/MATLAB/R2014b 28 | 29 | 3. You can also set MATLAB's root directory in the ``MatlabSession`` 30 | constructor. The disadvantage is that your script will not be 31 | portable, e.g.:: 32 | 33 | matlab = matlab_wrapper.MatlabSession(matlab_root="/opt/MATLAB/R2014b") 34 | 35 | See the documentation of ``MatlabSession`` for more details. 36 | 37 | 38 | 39 | Error using save, Can't write file stdio? 40 | ----------------------------------------- 41 | 42 | If you see this error message, is probably due to bug in 43 | ``engGetVariable`` in certain versions of MATLAB (2014a, 8.3) on 44 | GNU/Linux and OS X. There is not much we can do about it. The 45 | workaround is to use only double arrays. They seem to be working 46 | properly. 47 | 48 | 49 | 50 | Warning about missing ``/bin/csh``? 51 | ----------------------------------- 52 | 53 | On some systems MATLAB engine requires ``/bin/csh`` binary and you 54 | have to install it before using *matlab_wrapper*. For example, on 55 | Debian based distributions such as Ubuntu, you can do it with the 56 | following command as root:: 57 | 58 | apt-get install csh 59 | 60 | Alternatively, use your favorite package management software. 61 | Additionally, ``tcsh`` package seem to install ``/bin/csh`` too. 62 | 63 | 64 | 65 | Which platforms are supported? 66 | ------------------------------ 67 | 68 | GNU/Linux, Windows, OS X and various versions of MATLAB. 69 | 70 | If you are using *matlab_wrapper* with MATLAB version or OS, which are 71 | not listed below, please let us know and we will update the table. 72 | 73 | ========== =========== ========== ========== 74 | OS [#os]_ MATLAB Bits [#b]_ Status 75 | ========== =========== ========== ========== 76 | GNU/Linux 2014b (8.4) 64 working (py.test OK) 77 | GNU/Linux 2014a (8.3) 64 only double arrays working [#f]_ 78 | GNU/Linux 2013b (8.2) 64 working (py.test OK) 79 | GNU/Linux 2013a (8.1) 64 working (py.test OK) 80 | 81 | Windows 2014b (8.4) 32 reported working 82 | Windows 2014a (8.3) 64 working (py.test OK) 83 | 84 | OS X 2014a (8.3) 64 only double arrays working [#f]_ 85 | OS X 2013a (8.1) 64 working 86 | ========== =========== ========== ========== 87 | 88 | 89 | .. [#os] OSX version should work, but I'm unable to test it. If you 90 | have problems, let me know and we might figure it out. 91 | 92 | .. [#b] We have tested only 64-bit systems. 32-bit architectures are 93 | enabled, but not well tested. 94 | 95 | .. [#f] Due to bug in ``engGetVariable``: Error using save, Can't 96 | write file stdio. 97 | 98 | 99 | 100 | Is there alternative software? 101 | ------------------------------ 102 | 103 | Yes. Here's a little compilation: 104 | 105 | (last updated on April 18, 2015) 106 | 107 | 108 | - `MATLAB Engine for Python`_ 109 | 110 | - official package from Mathworks 111 | - supports new versions of Python (2.7, 3.3, and 3.4) 112 | - ships with MATLAB 2015a 113 | 114 | - pymatlab_ 115 | 116 | - pure Python, no compilation, using ctypes (good) 117 | - quite raw (ugly) 118 | - memory leaks (bad) 119 | 120 | - mlabwrap_ 121 | 122 | - cool interface, mlab.sin() (good) 123 | - needs compilation (bad) 124 | - not much development (bad) 125 | 126 | - mlab_ 127 | 128 | - similar interface to mlabwrap (good) 129 | - using raw pipes (hmm) 130 | - there is another very old package with `the same name 131 | `_ 132 | (ugly) 133 | 134 | - pymatbridge_ 135 | 136 | - actively developed (good) 137 | - client-server architecture with ZeroMQ and JSON, complex (ugly) 138 | - nice IPython Notebook support (good) 139 | 140 | 141 | 142 | There is a nice overview of the `available packages`_ at 143 | StackOverflow. 144 | 145 | 146 | .. _`MATLAB Engine for Python`: http://mathworks.com/help/matlab/matlab-engine-for-python.html 147 | .. _pymatlab: http://pymatlab.sourceforge.net/ 148 | .. _mlabwrap: http://mlabwrap.sourceforge.net/ 149 | .. _mlab: https://github.com/ewiger/mlab 150 | .. _pymatbridge: https://github.com/arokem/python-matlab-bridge 151 | .. _`available packages`: https://stackoverflow.com/questions/2883189/calling-matlab-functions-from-python/23762412#23762412 152 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include COPYING.txt 2 | -------------------------------------------------------------------------------- /NEWS.rst: -------------------------------------------------------------------------------- 1 | matlab_wrapper -- history of user-visible changes 2 | ================================================= 3 | 4 | Changes in version 1 5 | -------------------- 6 | 7 | + Switch to int versioning 8 | 9 | 10 | Changes in version 0.9.8 11 | ------------------------ 12 | 13 | + Fix a problem with cells (#19) 14 | 15 | 16 | Changes in version 0.9.7 17 | ------------------------ 18 | 19 | + Check if Python and MATLAB architectures match 20 | 21 | 22 | Changes in version 0.9.6 23 | ------------------------ 24 | 25 | + FIX: proper handling of empty struct arrays (thanks to Jeremy Moreau) 26 | 27 | 28 | Changes in version 0.9.5 29 | ------------------------ 30 | 31 | + enable 32-bit versions (thanks to Ralili) 32 | + disable MATLAB version checking 33 | 34 | 35 | Changes in version 0.9.4 36 | ------------------------ 37 | 38 | + Better handling of unsupported Python types 39 | + matlab.version is tuple now (was string) 40 | + FIX: platform checking 41 | + Check for /bin/csh on GNU/Linux 42 | 43 | 44 | Changes in version 0.9.3 45 | ------------------------ 46 | 47 | + FIX: memory leaks 48 | 49 | 50 | Changes in version 0.9 51 | ---------------------- 52 | 53 | + Initial OS X support (thanks to grahamj1978) 54 | 55 | 56 | Changes in version 0.8 57 | ---------------------- 58 | 59 | + Pandas' Series and DataFrame support (put) 60 | + MATLAB/OS version check and warning 61 | + BTC donations 62 | 63 | 64 | Changes in version 0.7.1 65 | ------------------------ 66 | 67 | + FIX: MatlabSession was ignoring ``matlab_root`` argument 68 | 69 | 70 | Changes in version 0.7 71 | ---------------------- 72 | 73 | + Windows support 74 | 75 | 76 | Changes in version 0.6 77 | ---------------------- 78 | 79 | + MATLAB struct array support 80 | + String array support 81 | 82 | 83 | Changes in version 0.5 84 | ---------------------- 85 | 86 | + MATLAB cell-array support 87 | 88 | 89 | Changes in version 0.4 and before 90 | --------------------------------- 91 | 92 | + Basic numerical array support 93 | + Unit tests 94 | + Easy workspace access 95 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | matlab_wrapper 2 | ============== 3 | 4 | With *matlab_wrapper* you can easily talk to MATLAB from your Python 5 | scripts and an interactive shell. MATLAB session is started in the 6 | background and appears as a regular Python object. 7 | 8 | **Info**: *matlab_wrapper* is maintained, but not actively developed. 9 | 10 | 11 | Usage 12 | ----- 13 | 14 | Initialize:: 15 | 16 | import matlab_wrapper 17 | matlab = matlab_wrapper.MatlabSession() 18 | 19 | 20 | Low level:: 21 | 22 | matlab.put('a', 12.3) 23 | matlab.eval('b = a * 2') 24 | b = matlab.get('b') 25 | 26 | 27 | Workspace:: 28 | 29 | s = matlab.workspace.sin([0.1, 0.2, 0.3]) 30 | 31 | sorted,idx = matlab.workspace.sort([3,1,2], nout=2) 32 | 33 | matlab.workspace.a = 12.3 34 | b = matlab.workspace.b 35 | 36 | 37 | More examples are in the examples_ directory! 38 | 39 | .. _examples: https://github.com/mrkrd/matlab_wrapper/tree/master/examples 40 | 41 | 42 | 43 | Features 44 | -------- 45 | 46 | - Access MATLAB variables and functions from Python 47 | - Multiplatform: GNU/Linux, Windows, OS X 48 | - On-the-fly conversion between MATLAB and Numpy data types 49 | - Support for MATLAB's numerical, logical, struct, and cell arrays 50 | - Pure Python, no need to compile anything (*matlab_wrapper* talks to 51 | `MATLAB engine library`_ using ctypes_) 52 | 53 | For a complete list of changes including new features, check the 54 | NEWS.rst_ file. 55 | 56 | .. _`MATLAB engine library`: http://www.mathworks.com/help/matlab/matlab_external/introducing-matlab-engine.html 57 | .. _ctypes: https://docs.python.org/2/library/ctypes.html 58 | .. _NEWS.rst: NEWS.rst 59 | 60 | 61 | 62 | Installation 63 | ------------ 64 | 65 | First, make sure that you have the following components installed: 66 | 67 | - Python 2.7 68 | - MATLAB (various versions) 69 | - Numpy 70 | 71 | 72 | Next, install *matlab_wrapper* using pip (the standard Python package 73 | installation tool) from your command line:: 74 | 75 | pip install matlab_wrapper 76 | 77 | 78 | 79 | Contribute 80 | ---------- 81 | 82 | Check our CONTRIBUTING_ guidelines. 83 | 84 | - Issue Tracker: https://github.com/mrkrd/matlab_wrapper/issues 85 | - Source Code: https://github.com/mrkrd/matlab_wrapper 86 | 87 | 88 | 89 | Support 90 | ------- 91 | 92 | If you are having issues, please let me know through the issue 93 | tracker: https://github.com/mrkrd/matlab_wrapper/issues. Try to avoid 94 | duplicates by searching previous issues, checking FAQ_, and 95 | CONTRIBUTING_. 96 | 97 | .. _FAQ: FAQ.rst 98 | .. _CONTRIBUTING: CONTRIBUTING.rst 99 | 100 | 101 | 102 | Acknowledgments 103 | --------------- 104 | 105 | *matlab_wrapper* was forked from pymatlab_. 106 | 107 | MATLAB is a registered trademark of `The MathWorks, Inc`_. 108 | 109 | .. _pymatlab: http://pymatlab.sourceforge.net/ 110 | .. _`The MathWorks, Inc`: http://www.mathworks.com/ 111 | 112 | 113 | 114 | 115 | License 116 | ------- 117 | 118 | The project is licensed under the GNU General Public License v3 or 119 | later (GPLv3+). 120 | -------------------------------------------------------------------------------- /TODO.org: -------------------------------------------------------------------------------- 1 | #+TITLE: TODOs for matlab_wrapper 2 | #+AUTHOR: Marek Rudnicki 3 | #+CATEGORY: matlab_wrap 4 | 5 | * TODO Auto-detect the number of output arguments (nout) 6 | 7 | - check get_nout() from oct2py: 8 | 9 | https://github.com/blink1073/oct2py/blob/master/oct2py/utils.py 10 | 11 | - check mlabwrap 12 | 13 | 14 | * TODO Proper handling of char arrays (strings) 15 | 16 | Branch: char_arrays 17 | 18 | The equivalent type of MATLAB's strings (char arrays) should be 19 | ndarray with dtype=S. 20 | 21 | At the moment MATLAB's multidimensional char array conversion to 22 | Python is not correct. 23 | 24 | 25 | * TODO Explicit warning when using Python 3 26 | 27 | * TODO [#C] Test string parameters (path) to a function (#15) 28 | 29 | ftp://ftp.scp.byu.edu/pub/software/matlab/loadsir.m 30 | ftp://ftp.scp.byu.edu/data/qscat/1999/sir/queh/SAm/201/a/queh-a-SAm99-201-204.sir.gz 31 | -------------------------------------------------------------------------------- /TODO.org_archive: -------------------------------------------------------------------------------- 1 | # -*- mode: org -*- 2 | 3 | 4 | Archived entries from file /home/marek/projects/matlab_wrapper/TODO.org 5 | 6 | 7 | * CANCELED IPython notebook support 8 | CLOSED: [2017-03-02 Thu 18:02] 9 | :PROPERTIES: 10 | :ARCHIVE_TIME: 2019-04-11 Thu 15:28 11 | :ARCHIVE_FILE: ~/projects/matlab_wrapper/TODO.org 12 | :ARCHIVE_CATEGORY: matlab_wrap 13 | :ARCHIVE_TODO: CANCELED 14 | :END: 15 | 16 | Archived entries from file /home/marek/projects/matlab_wrapper/TODO.org 17 | 18 | 19 | * CANCELED IPython notebook support 20 | CLOSED: [2017-03-02 Thu 18:02] 21 | :PROPERTIES: 22 | :ARCHIVE_TIME: 2019-04-11 Thu 15:28 23 | :ARCHIVE_FILE: ~/projects/matlab_wrapper/TODO.org 24 | :ARCHIVE_CATEGORY: matlab_wrap 25 | :ARCHIVE_TODO: CANCELED 26 | :END: 27 | 28 | Archived entries from file /home/marek/projects/matlab_wrapper/TODO.org 29 | 30 | 31 | * DONE Documentation 32 | :PROPERTIES: 33 | :ARCHIVE_TIME: 2019-04-11 Thu 15:28 34 | :ARCHIVE_FILE: ~/projects/matlab_wrapper/TODO.org 35 | :ARCHIVE_CATEGORY: matlab_wrap 36 | :ARCHIVE_TODO: DONE 37 | :END: 38 | 39 | ** DONE Apply guidelines from writethedocs.org 40 | 41 | http://docs.writethedocs.org/ 42 | 43 | ** DONE Sphinx 44 | 45 | ** DONE Python hosted 46 | 47 | ** DONE CONTRIBUTING 48 | 49 | - small code snippet illustrating an issue 50 | - python setup.py develop --user 51 | - py.test 52 | 53 | 54 | ** DONE FAQ 55 | 56 | - matlab_root (modify PATH, ln -s) 57 | - /bin/csh 58 | 59 | 60 | Archived entries from file /home/marek/projects/matlab_wrapper/TODO.org 61 | 62 | 63 | * CANCELED Spread the word 64 | :PROPERTIES: 65 | :ARCHIVE_TIME: 2019-04-11 Thu 15:28 66 | :ARCHIVE_FILE: ~/projects/matlab_wrapper/TODO.org 67 | :ARCHIVE_CATEGORY: matlab_wrap 68 | :ARCHIVE_TODO: CANCELED 69 | :END: 70 | 71 | ** Show HN 72 | 73 | ** reddit 74 | 75 | - python 76 | - matlab 77 | 78 | ** comp.soft-sys.matlab 79 | 80 | https://groups.google.com/forum/#!forum/comp.soft-sys.matlab 81 | 82 | 83 | Archived entries from file /home/marek/projects/matlab_wrapper/TODO.org 84 | 85 | 86 | * CANCELED Python 3 support 87 | CLOSED: [2017-03-02 Thu 19:36] 88 | :PROPERTIES: 89 | :ARCHIVE_TIME: 2019-04-11 Thu 15:28 90 | :ARCHIVE_FILE: ~/projects/matlab_wrapper/TODO.org 91 | :ARCHIVE_CATEGORY: matlab_wrap 92 | :ARCHIVE_TODO: CANCELED 93 | :END: 94 | 95 | Better make a new library for Python 3 with the following properties: 96 | 97 | - name: matlab_wrapper3 (?) 98 | - don't squeeze values from Matlab 99 | - assure proper indexing 100 | https://groups.google.com/forum/#!topic/matlab_wrapper/wAp6veM6xgY 101 | 102 | ** Review PR #7 from David 103 | 104 | https://github.com/mrkrd/matlab_wrapper/pull/7 105 | 106 | 107 | 108 | Archived entries from file /home/marek/projects/matlab_wrapper/TODO.org 109 | 110 | 111 | * CANCELED Auto-convert int to float in matlab.put() 112 | CLOSED: [2016-07-26 Tue 12:46] 113 | :PROPERTIES: 114 | :ARCHIVE_TIME: 2019-04-11 Thu 15:28 115 | :ARCHIVE_FILE: ~/projects/matlab_wrapper/TODO.org 116 | :ARCHIVE_CATEGORY: matlab_wrap 117 | :ARCHIVE_TODO: CANCELED 118 | :END: 119 | 120 | Canceled: “Explicit is better than implicit” 121 | 122 | The problem is that in MATLAB this conversion is implicit and writing 123 | e.g. 124 | 125 | matlab.put('a', 1) # <- here 'a' will be int 126 | 127 | may lead to unexpected behaviors. 128 | 129 | 130 | Could be activated via by a parameters: 131 | 132 | matlab = matlab_wrapper.MatlabSession(auto_int_conversion=True) 133 | 134 | 135 | Archived entries from file /home/marek/projects/matlab_wrapper/TODO.org 136 | 137 | 138 | * DONE Make sure that the MATLAB process is gone in __del__() :canceled: 139 | :PROPERTIES: 140 | :ARCHIVE_TIME: 2019-04-11 Thu 15:28 141 | :ARCHIVE_FILE: ~/projects/matlab_wrapper/TODO.org 142 | :ARCHIVE_CATEGORY: matlab_wrap 143 | :ARCHIVE_TODO: DONE 144 | :END: 145 | 146 | - add `matlab._pid' (use features('getpid') in MATLAB, might not 147 | exist in older versions) 148 | - check the standard library for the best kill/terminate functions 149 | 150 | 151 | 152 | MATLAB is unresponsive during execution of svd(). I did not find a 153 | way to reasonably kill the process (in destructor), because it hangs 154 | in the engClose(). 155 | 156 | 157 | 158 | #+BEGIN_SRC matlab 159 | m.workspace.svd(np.zeros((10000,10000))) 160 | #+END_SRC 161 | 162 | 163 | #+BEGIN_SRC python 164 | ### Get MATLAB PID 165 | try: 166 | pid = self.workspace.feature('getpid') 167 | self._pid = int(pid) 168 | except RuntimeError: 169 | self._pid = None 170 | #+END_SRC 171 | 172 | 173 | Archived entries from file /home/marek/projects/matlab_wrapper/TODO.org 174 | 175 | 176 | * DONE Check for /bin/csh on Linux 177 | :PROPERTIES: 178 | :ARCHIVE_TIME: 2019-04-11 Thu 15:28 179 | :ARCHIVE_FILE: ~/projects/matlab_wrapper/TODO.org 180 | :ARCHIVE_CATEGORY: matlab_wrap 181 | :ARCHIVE_TODO: DONE 182 | :END: 183 | 184 | /bin/csh is required by libeng and the lack of it could be detected by 185 | matlab_wrapper. 186 | 187 | <2014-09-29 Mon> 188 | 189 | 190 | Archived entries from file /home/marek/projects/matlab_wrapper/TODO.org 191 | 192 | 193 | * DONE Enable 32-bit versions 194 | :PROPERTIES: 195 | :ARCHIVE_TIME: 2019-04-11 Thu 15:28 196 | :ARCHIVE_FILE: ~/projects/matlab_wrapper/TODO.org 197 | :ARCHIVE_CATEGORY: matlab_wrap 198 | :ARCHIVE_TODO: DONE 199 | :END: 200 | 201 | ralili mentioned that it seem to be working on Windows 7, where: 202 | 203 | lib_dir = join(matlab_root, "bin", "win32") 204 | 205 | 206 | Archived entries from file /home/marek/projects/matlab_wrapper/TODO.org 207 | 208 | 209 | * DONE Error when getting empty Matlab object :urgent: 210 | :PROPERTIES: 211 | :ARCHIVE_TIME: 2019-04-11 Thu 15:28 212 | :ARCHIVE_FILE: ~/projects/matlab_wrapper/TODO.org 213 | :ARCHIVE_CATEGORY: matlab_wrap 214 | :ARCHIVE_TODO: DONE 215 | :END: 216 | 217 | Issue #6 by Jeremy Moreau 218 | 219 | 220 | Archived entries from file /home/marek/projects/matlab_wrapper/TODO.org 221 | 222 | 223 | * DONE Setup a mailing list 224 | :PROPERTIES: 225 | :ARCHIVE_TIME: 2019-04-11 Thu 15:28 226 | :ARCHIVE_FILE: ~/projects/matlab_wrapper/TODO.org 227 | :ARCHIVE_CATEGORY: matlab_wrap 228 | :ARCHIVE_TODO: DONE 229 | :END: 230 | 231 | matlab_wrapper@googlegroups.com 232 | 233 | 234 | Archived entries from file /home/marek/projects/matlab_wrapper/TODO.org 235 | 236 | 237 | * CANCELED Investigate `undefined symbol' error 238 | CLOSED: [2016-07-26 Tue 12:47] 239 | :PROPERTIES: 240 | :ARCHIVE_TIME: 2019-04-11 Thu 15:28 241 | :ARCHIVE_FILE: ~/projects/matlab_wrapper/TODO.org 242 | :ARCHIVE_CATEGORY: matlab_wrap 243 | :ARCHIVE_TODO: CANCELED 244 | :END: 245 | 246 | Canceled: not able to reproduce. 247 | 248 | Might have something to do with matplotlib. 249 | 250 | Eventually put in FAQ. 251 | 252 | 253 | 790 """ 254 | 791 def __init__(self, name, **kwargs): 255 | --> 792 self._lib = ctypes.CDLL(name, **kwargs) 256 | 793 257 | 794 if 'libeng' in name: 258 | 259 | /usr/lib/python2.7/ctypes/__init__.pyc in __init__(self, name, mode, handle, use_errno, use_last_error) 260 | 363 261 | 364 if handle is None: 262 | --> 365 self._handle = _dlopen(self._name, mode) 263 | 366 else: 264 | 367 self._handle = handle 265 | 266 | OSError: /nfs/system/opt/MATLAB/R2014b/bin/glnxa64/libicuio.so.52: undefined symbol: _ZN6icu_5213UnicodeString9doReplaceEiiPKDsii 267 | 268 | 269 | Archived entries from file /home/marek/projects/matlab_wrapper/TODO.org 270 | 271 | 272 | * DONE Investigate indexing in Numpy and MATLAB 273 | CLOSED: [2017-03-02 Thu 18:04] 274 | :PROPERTIES: 275 | :ARCHIVE_TIME: 2019-04-11 Thu 15:28 276 | :ARCHIVE_FILE: ~/projects/matlab_wrapper/TODO.org 277 | :ARCHIVE_CATEGORY: matlab_wrap 278 | :ARCHIVE_TODO: DONE 279 | :END: 280 | 281 | https://groups.google.com/forum/#!topic/matlab_wrapper/wAp6veM6xgY 282 | 283 | 284 | Numpy indexing comes form C. 285 | 286 | In carr[i][j][k], k iterates the most inner row arrays. 287 | 288 | 289 | arr.ravel('K') flattens array in the order the elements occur in the 290 | memory. 291 | 292 | 293 | matlab_wrapper has to take into account inverse indexing: 294 | 295 | [i][j][k][l] <=> [l][k][j][i] 296 | 297 | as well as row vs column of the inner most arrays: 298 | 299 | [i][j][k][l] <=> [k][l][j][i] 300 | 301 | 302 | Archived entries from file /home/marek/projects/matlab_wrapper/TODO.org 303 | 304 | 305 | * DONE Create DOI for referencing 306 | CLOSED: [2017-03-04 Sat 17:59] 307 | :PROPERTIES: 308 | :ARCHIVE_TIME: 2019-04-11 Thu 15:28 309 | :ARCHIVE_FILE: ~/projects/matlab_wrapper/TODO.org 310 | :ARCHIVE_CATEGORY: matlab_wrap 311 | :ARCHIVE_TODO: DONE 312 | :END: 313 | 314 | https://zenodo.org/badge/latestdoi/24233/mrkrd/matlab_wrapper 315 | 316 | 317 | Archived entries from file /home/marek/projects/matlab_wrapper/TODO.org 318 | 319 | 320 | * DONE Conversion of a struct (#18) 321 | CLOSED: [2017-11-10 Fri 21:06] 322 | :PROPERTIES: 323 | :ARCHIVE_TIME: 2019-04-11 Thu 15:28 324 | :ARCHIVE_FILE: ~/projects/matlab_wrapper/TODO.org 325 | :ARCHIVE_CATEGORY: matlab_wrap 326 | :ARCHIVE_TODO: DONE 327 | :END: 328 | 329 | https://github.com/mrkrd/matlab_wrapper/issues/18 330 | 331 | [[notmuch:id:mrkrd/matlab_wrapper/issues/18/274494320@github.com]] 332 | 333 | - backward compatibility is super important 334 | - possible solution is to disable squeeze'ing in a backward compatible 335 | way, e.g., MatlabSession(squeeze=False) 336 | 337 | 338 | Archived entries from file /home/marek/projects/matlab_wrapper/TODO.org 339 | 340 | 341 | * DONE Dimension of cellarrays (#19) 342 | CLOSED: [2017-01-24 Tue 14:03] 343 | :PROPERTIES: 344 | :ARCHIVE_TIME: 2019-04-11 Thu 15:28 345 | :ARCHIVE_FILE: ~/projects/matlab_wrapper/TODO.org 346 | :ARCHIVE_CATEGORY: matlab_wrap 347 | :ARCHIVE_TODO: DONE 348 | :END: 349 | 350 | https://github.com/mrkrd/matlab_wrapper/issues/19 351 | 352 | fixed by PR #20 353 | 354 | 355 | Archived entries from file /home/marek/projects/matlab_wrapper/TODO.org 356 | 357 | 358 | * DONE Python 3 tests (#23) 359 | CLOSED: [2017-11-10 Fri 21:06] 360 | :PROPERTIES: 361 | :ARCHIVE_TIME: 2019-04-11 Thu 15:28 362 | :ARCHIVE_FILE: ~/projects/matlab_wrapper/TODO.org 363 | :ARCHIVE_CATEGORY: matlab_wrap 364 | :ARCHIVE_TODO: DONE 365 | :END: 366 | 367 | https://github.com/mrkrd/matlab_wrapper/pull/23 368 | -------------------------------------------------------------------------------- /examples/eval_m_file.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | """Evaluate m-file and collect the results. A simple MATLAB script is 4 | located in my_script.m 5 | 6 | """ 7 | from __future__ import division, print_function, absolute_import 8 | from __future__ import unicode_literals 9 | 10 | import matlab_wrapper 11 | 12 | 13 | def main(): 14 | matlab = matlab_wrapper.MatlabSession() 15 | 16 | matlab.put('x', 2.) 17 | matlab.eval('my_script') 18 | y = matlab.get('y') 19 | 20 | print("And the winner is:", y) 21 | 22 | 23 | if __name__ == "__main__": 24 | main() 25 | -------------------------------------------------------------------------------- /examples/fir_filter.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | """Design a lowpas FIR filter. Based on an example from `freqz` 4 | documentation. 5 | 6 | """ 7 | 8 | from __future__ import division, print_function, absolute_import 9 | from __future__ import unicode_literals 10 | 11 | import numpy as np 12 | import matlab_wrapper 13 | 14 | 15 | def main(): 16 | 17 | matlab = matlab_wrapper.MatlabSession() 18 | 19 | kaiser = matlab.workspace.kaiser(81., 8.) 20 | 21 | b = matlab.workspace.fir1(80., 0.5, kaiser) 22 | 23 | matlab.workspace.freqz(b, 1., nout=0) 24 | 25 | raw_input("Press enter to finish...") 26 | 27 | 28 | if __name__ == "__main__": 29 | main() 30 | -------------------------------------------------------------------------------- /examples/my_script.m: -------------------------------------------------------------------------------- 1 | 2 | % Basic MATLAB script 3 | 4 | 5 | pause(3); 6 | 7 | y = x * 2; 8 | -------------------------------------------------------------------------------- /examples/playground/sandbox.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """Very simple matlab_wrapper example. 5 | 6 | """ 7 | 8 | from __future__ import division, absolute_import, print_function 9 | 10 | import numpy as np 11 | 12 | import matlab_wrapper 13 | 14 | def main(): 15 | 16 | 17 | matlab = matlab_wrapper.MatlabSession( 18 | options='-nojvm', 19 | buffer_size=1000, 20 | ) 21 | 22 | print(matlab.version) 23 | 24 | 25 | print() 26 | print('='*70) 27 | print() 28 | 29 | 30 | matlab.eval("a = pi * 2") 31 | print(matlab.output_buffer) 32 | a = matlab.get('a') 33 | print(a) 34 | 35 | 36 | print() 37 | print('='*70) 38 | print() 39 | 40 | 41 | 42 | matlab.eval("s = 'asdf'") 43 | s = matlab.get('s') 44 | print(s) 45 | 46 | 47 | 48 | print() 49 | print('='*70) 50 | print() 51 | 52 | 53 | 54 | matlab.eval("l = logical([1 1 0])") 55 | l = matlab.get('l') 56 | print(l) 57 | 58 | print(matlab.output_buffer) 59 | 60 | 61 | 62 | print() 63 | print('='*70) 64 | print() 65 | 66 | 67 | matlab.put('m', 'asdf') 68 | m = matlab.get('m') 69 | print(m) 70 | 71 | 72 | 73 | print() 74 | print('='*70) 75 | print() 76 | 77 | 78 | # matlab.put('m', np.array('asdf')) 79 | # m = matlab.get('m') 80 | # print(m) 81 | 82 | 83 | # r = np.arange(9) + np.ones(9) * 1j 84 | # while True: 85 | # matlab.put('r', r) 86 | # out = matlab.get('r') 87 | # print(out) 88 | 89 | 90 | a = matlab.workspace.sin(np.arange(10.)) 91 | print(a) 92 | 93 | 94 | print() 95 | print('='*70) 96 | print() 97 | 98 | 99 | y,i = matlab.workspace.sort([2,1,3], nout=2) 100 | print(y,i) 101 | 102 | 103 | print() 104 | print('='*70) 105 | print() 106 | 107 | 108 | print(matlab.workspace.pi()) 109 | 110 | 111 | print() 112 | print('='*70) 113 | print() 114 | 115 | matlab.workspace.a = [123, 12, 1] 116 | matlab.eval("b = a*2") 117 | print(matlab.workspace.b) 118 | 119 | #help(matlab.workspace.sin) 120 | 121 | 122 | print() 123 | print('='*70) 124 | print() 125 | 126 | 127 | matlab.eval("whos") 128 | print(matlab.output_buffer) 129 | 130 | 131 | print() 132 | print('='*70) 133 | print() 134 | 135 | 136 | print(matlab) 137 | 138 | 139 | print() 140 | print('='*70) 141 | print() 142 | 143 | 144 | matlab.workspace.a = ['asdf', 'strings'] 145 | 146 | matlab.eval('a') 147 | print(matlab.output_buffer) 148 | 149 | 150 | if __name__ == "__main__": 151 | main() 152 | -------------------------------------------------------------------------------- /examples/playground/sandbox_cells.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """Testing things with cells. 5 | 6 | """ 7 | 8 | from __future__ import division, absolute_import, print_function 9 | 10 | import numpy as np 11 | 12 | import matlab_wrapper 13 | 14 | def main(): 15 | 16 | matlab = matlab_wrapper.MatlabSession( 17 | options='-nojvm', 18 | buffer_size=1000, 19 | ) 20 | 21 | 22 | matlab.eval("c = {1, 2, 3; 'text', eye(2,3), {11; 22; 33}}") 23 | 24 | print(matlab.get('c')) 25 | 26 | 27 | matlab.put('a', np.array([[1,'asdf'], [3, np.array([1,2,3],dtype='O')]], dtype='O')) 28 | matlab.eval('a') 29 | print(matlab.output_buffer) 30 | 31 | 32 | if __name__ == "__main__": 33 | main() 34 | -------------------------------------------------------------------------------- /examples/playground/sandbox_struct.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """Testing things with cells. 5 | 6 | """ 7 | 8 | from __future__ import division, absolute_import, print_function 9 | 10 | import numpy as np 11 | 12 | import matlab_wrapper 13 | 14 | def main(): 15 | 16 | matlab = matlab_wrapper.MatlabSession( 17 | options='-nojvm', 18 | buffer_size=1000, 19 | ) 20 | 21 | 22 | matlab.eval(""" 23 | s = struct() 24 | 25 | s(1,1).x = 1 26 | s(1,1).y = 'a' 27 | 28 | s(2,2).x = 2 29 | s(2,2).y = [1,2,3] 30 | 31 | """) 32 | 33 | print(matlab.get('s')) 34 | 35 | 36 | matlab.eval(""" 37 | s = struct() 38 | 39 | s(1).x = 1 40 | s(1).y = [1 2] 41 | 42 | s(2).x = 2 43 | s(2).y = [3 5] 44 | """) 45 | 46 | s = matlab.get('s') 47 | print(s, s.dtype) 48 | 49 | print("="*70) 50 | 51 | a = np.array([(1,'a'), (2,'b')], dtype=[('x', '. 20 | 21 | 22 | from __future__ import division, print_function, absolute_import 23 | 24 | __version__ = "1" 25 | 26 | from matlab_wrapper.matlab_session import MatlabSession 27 | -------------------------------------------------------------------------------- /matlab_wrapper/matlab_session.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Copyright 2010-2013 Joakim Möller 4 | # Copyright 2014-2015 Marek Rudnicki 5 | # 6 | # This file is part of matlab_wrapper. 7 | # 8 | # matlab_wrapper is free software: you can redistribute it and/or modify 9 | # it under the terms of the GNU General Public License as published by 10 | # the Free Software Foundation, either version 3 of the License, or 11 | # (at your option) any later version. 12 | # 13 | # matlab_wrapper is distributed in the hope that it will be useful, 14 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | # GNU General Public License for more details. 17 | # 18 | # You should have received a copy of the GNU General Public License 19 | # along with matlab_wrapper. If not, see . 20 | 21 | 22 | from __future__ import print_function, division, absolute_import 23 | 24 | import numpy as np 25 | import platform 26 | from os.path import join, dirname, isfile, realpath 27 | import os 28 | import warnings 29 | import sys 30 | import weakref 31 | import collections 32 | 33 | import ctypes 34 | from ctypes import c_char_p, POINTER, c_size_t, c_bool, c_void_p, c_int 35 | 36 | from matlab_wrapper.typeconv import dtype_to_mat 37 | 38 | 39 | class mxArray(ctypes.Structure): 40 | pass 41 | 42 | 43 | class Engine(ctypes.Structure): 44 | pass 45 | 46 | 47 | mwSize = c_size_t 48 | mwIndex = c_size_t 49 | 50 | 51 | wrap_script = r""" 52 | ERRSTR__ = ''; 53 | try 54 | {0} 55 | catch err 56 | ERRSTR__ = sprintf('%s: %s\n', err.identifier, err.message); 57 | for i = 1:length(err.stack) 58 | ERRSTR__ = sprintf('%sError: in fuction %s in file %s line %i\n', ERRSTR__, err.stack(i,1).name, err.stack(i,1).file, err.stack(i,1).line); 59 | end 60 | end 61 | if exist('ERRSTR__','var') == 0 62 | ERRSTR__=''; 63 | end 64 | """ 65 | 66 | 67 | class MatlabSession(object): 68 | """Matlab session. 69 | 70 | Parameters 71 | ---------- 72 | options : str, optional 73 | Options that will be passed to MATLAB at the start, 74 | e.g. '-nosplash'. 75 | matlab_root : str or None, optional 76 | Root of the MATLAB installation. If unsure, then start MATLAB 77 | and type `matlabroot`. If `None`, then will be determined 78 | based on the `matlab` binary location. Alternatively, you can 79 | set MATLABROOT environment variable. 80 | buffer_size : int, optional 81 | MATLAB output buffer size. The output buffer can be accessed 82 | through `output_buffer` property. 83 | 84 | Attributes 85 | ---------- 86 | output_buffer : str 87 | Access to the MATLAB output buffer. 88 | workspace : Workspace object 89 | Easy access to MATLAB workspace, e.g. `workspace.sin([1.,2.,3.])`. 90 | version : tuple or None 91 | MATLAB/libeng version number. 92 | 93 | Methods 94 | ------- 95 | get() 96 | put() 97 | eval() 98 | 99 | """ 100 | def __init__(self, options='-nosplash', matlab_root=None, buffer_size=0): 101 | 102 | if (matlab_root is None) and ('MATLABROOT' in os.environ): 103 | matlab_root = os.environ['MATLABROOT'] 104 | 105 | if matlab_root is None: 106 | matlab_root = find_matlab_root() 107 | 108 | if matlab_root is None: 109 | raise RuntimeError("Unknown MATLAB location: try to initialize MatlabSession with matlab_root set properly.") 110 | 111 | self._matlab_root = matlab_root 112 | 113 | engine, libeng, libmx, version = load_engine_and_libs(matlab_root, options) 114 | 115 | self._libeng = libeng 116 | self._libmx = libmx 117 | self._ep = engine 118 | 119 | 120 | 121 | ### MATLAB/libeng version 122 | self.version = version 123 | 124 | 125 | 126 | ### Setup the output buffer 127 | if buffer_size != 0: 128 | self._output_buffer = ctypes.create_string_buffer(buffer_size) 129 | self._libeng.engOutputBuffer( 130 | self._ep, 131 | self._output_buffer, 132 | buffer_size-1 133 | ) 134 | else: 135 | self._output_buffer = None 136 | 137 | 138 | ### Workspace object 139 | self.workspace = Workspace(weakref.ref(self)) 140 | 141 | 142 | 143 | 144 | def __del__(self): 145 | try: 146 | self._libeng.engClose(self._ep) 147 | except AttributeError: 148 | pass 149 | 150 | 151 | 152 | @property 153 | def output_buffer(self): 154 | if self._output_buffer is None: 155 | raise RuntimeError("Output buffer was not initialized properly.") 156 | else: 157 | return self._output_buffer.value 158 | 159 | 160 | 161 | def eval(self, expression): 162 | """Evaluate `expression` in MATLAB engine. 163 | 164 | Parameters 165 | ---------- 166 | expression : str 167 | Expression is passed to MATLAB engine and evaluated. 168 | 169 | """ 170 | expression_wrapped = wrap_script.format(expression) 171 | 172 | 173 | ### Evaluate the expression 174 | self._libeng.engEvalString(self._ep, expression_wrapped) 175 | 176 | ### Check for exceptions in MATLAB 177 | mxresult = self._libeng.engGetVariable(self._ep, 'ERRSTR__') 178 | 179 | error_string = self._libmx.mxArrayToString(mxresult) 180 | 181 | self._libmx.mxDestroyArray(mxresult) 182 | 183 | if error_string != "": 184 | raise RuntimeError("Error from MATLAB\n{0}".format(error_string)) 185 | 186 | 187 | 188 | def get(self, name): 189 | """Get variable `name` from MATLAB workspace. 190 | 191 | Parameters 192 | ---------- 193 | name : str 194 | Name of the variable in MATLAB workspace. 195 | 196 | Returns 197 | ------- 198 | array_like 199 | Value of the variable `name`. 200 | 201 | """ 202 | pm = self._libeng.engGetVariable(self._ep, name) 203 | 204 | out = mxarray_to_ndarray(self._libmx, pm) 205 | 206 | 207 | self._libmx.mxDestroyArray(pm) 208 | 209 | return out 210 | 211 | 212 | 213 | 214 | def put(self, name, value): 215 | """Put a variable to MATLAB workspace. 216 | 217 | """ 218 | 219 | pm = ndarray_to_mxarray(self._libmx, value) 220 | 221 | self._libeng.engPutVariable(self._ep, name, pm) 222 | 223 | self._libmx.mxDestroyArray(pm) 224 | 225 | 226 | 227 | 228 | 229 | def __repr__(self): 230 | r = ''.format(root=self._matlab_root) 231 | 232 | return r 233 | 234 | 235 | def error_check(result, func, arguments): 236 | if (isinstance(result, c_int) and result != 0) or (isinstance(result, POINTER(mxArray)) and not bool(result)): 237 | raise RuntimeError( 238 | "MATLAB function {func} failed ({result}) with arguments:\n{arguments}".format( 239 | func=str(func), 240 | result=str(result), 241 | arguments=str(arguments) 242 | )) 243 | return result 244 | 245 | 246 | def find_matlab_root(): 247 | """Look for matlab binary and return root directory of MATLAB 248 | installation. 249 | 250 | """ 251 | matlab_root = None 252 | 253 | path_dirs = os.environ.get("PATH").split(os.pathsep) 254 | for path_dir in path_dirs: 255 | candidate = realpath(join(path_dir, 'matlab')) 256 | if isfile(candidate) or isfile(candidate + '.exe'): 257 | matlab_root = dirname(dirname(candidate)) 258 | break 259 | 260 | return matlab_root 261 | 262 | 263 | def load_engine_and_libs(matlab_root, options): 264 | """Load and return `libeng` and `libmx`. Start and return MATLAB 265 | engine. 266 | 267 | Returns 268 | ------- 269 | engine 270 | libeng 271 | libmx 272 | 273 | """ 274 | if sys.maxsize > 2**32: 275 | bits = '64bit' 276 | else: 277 | bits = '32bit' 278 | 279 | system = platform.system() 280 | 281 | if system == 'Linux': 282 | if bits == '64bit': 283 | lib_dir = join(matlab_root, "bin", "glnxa64") 284 | else: 285 | lib_dir = join(matlab_root, "bin", "glnx86") 286 | 287 | check_python_matlab_architecture(bits, lib_dir) 288 | 289 | libeng = Library( 290 | join(lib_dir, 'libeng.so') 291 | ) 292 | libmx = Library( 293 | join(lib_dir, 'libmx.so') 294 | ) 295 | 296 | command = "{executable} {options}".format( 297 | executable=join(matlab_root, 'bin', 'matlab'), 298 | options=options 299 | ) 300 | 301 | ### Check for /bin/csh 302 | if not os.path.exists("/bin/csh"): 303 | warnings.warn("MATLAB engine requires /bin/csh. Please install it on your system or matlab_wrapper will not work properly.") 304 | 305 | elif system == 'Windows': 306 | if bits == '64bit': 307 | lib_dir = join(matlab_root, "bin", "win64") 308 | else: 309 | lib_dir = join(matlab_root, "bin", "win32") 310 | 311 | check_python_matlab_architecture(bits, lib_dir) 312 | 313 | ## We need to modify PATH, to find MATLAB libs 314 | if lib_dir not in os.environ['PATH']: 315 | os.environ['PATH'] = lib_dir + ';' + os.environ['PATH'] 316 | 317 | libeng = Library('libeng') 318 | libmx = Library('libmx') 319 | 320 | command = None 321 | 322 | elif system == 'Darwin': 323 | if bits == '64bit': 324 | lib_dir = join(matlab_root, "bin", "maci64") 325 | else: 326 | unsupported_platform(system, bits) 327 | 328 | check_python_matlab_architecture(bits, lib_dir) 329 | 330 | libeng = Library( 331 | join(lib_dir, 'libeng.dylib') 332 | ) 333 | libmx = Library( 334 | join(lib_dir, 'libmx.dylib') 335 | ) 336 | 337 | command = "{executable} {options}".format( 338 | executable=join(matlab_root, 'bin', 'matlab'), 339 | options=options 340 | ) 341 | 342 | else: 343 | unsupported_platform(system, bits) 344 | 345 | ### Check MATLAB version 346 | try: 347 | version_str = c_char_p.in_dll(libeng, "libeng_version").value 348 | version = tuple([int(v) for v in version_str.split('.')[:2]]) 349 | 350 | except ValueError: 351 | warnings.warn("Unable to identify MATLAB (libeng) version.") 352 | version = None 353 | 354 | if (system == 'Linux') and (version == (8, 3)) and (bits == '64bit'): 355 | warnings.warn("You are using MATLAB version 8.3 (R2014a) on Linux, which appears to have a bug in engGetVariable(). You will only be able to use arrays of type double.") 356 | 357 | elif (system == 'Darwin') and (version == (8, 3)) and (bits == '64bit'): 358 | warnings.warn("You are using MATLAB version 8.3 (R2014a) on OS X, which appears to have a bug in engGetVariable(). You will only be able to use arrays of type double.") 359 | 360 | ### Start the engine 361 | engine = libeng.engOpen(command) 362 | 363 | return engine, libeng, libmx, version 364 | 365 | 366 | def check_python_matlab_architecture(bits, lib_dir): 367 | """Make sure we can find corresponding installation of Python and MATLAB.""" 368 | if not os.path.isdir(lib_dir): 369 | raise RuntimeError("It seem that you are using {bits} version of Python, but there's no matching MATLAB installation in {lib_dir}.".format(bits=bits, lib_dir=lib_dir)) 370 | 371 | 372 | def unsupported_platform(system, bits): 373 | raise RuntimeError("""Unsopported OS or architecture: {} {}. 374 | 375 | Check our website about supported platforms: 376 | https://github.com/mrkrd/matlab_wrapper""".format(system, bits)) 377 | 378 | 379 | class Workspace(object): 380 | """A convenient interface to MATLAB workspace. 381 | 382 | You can use attributes to access MALTAB functions and variables:: 383 | 384 | workspace.sin([1., 2., 3.]) 385 | pi = workspace.pi() 386 | a = workspace.a 387 | 388 | 389 | In MATLAB the output of the function depends on the number of 390 | outputs arguments. By default, we assume that there is one output 391 | argument. If you would like to change that, add `nout` keyward 392 | argument to the function, e.g.:: 393 | 394 | sorted,idx = workspace.sort([3,1,2], nout=2) 395 | 396 | """ 397 | def __init__(self, session_ref): 398 | """Workspace constructor. 399 | 400 | Parameters 401 | ---------- 402 | session_ref : weak referecne to MatlabSession 403 | We need weak reference here, because Workspace is an 404 | attribute of MatlabSession and we do not want cyclic 405 | referencing. 406 | 407 | """ 408 | self._session_ref = session_ref 409 | 410 | def __getattr__(self, attr): 411 | 412 | session = self._session_ref() 413 | 414 | session.eval("KIND__ = exist('{}')".format(attr)) 415 | kind = session.get('KIND__') 416 | session.eval("clear KIND__") 417 | 418 | if kind == 0: 419 | raise RuntimeError("No such variable/function in MATLAB workspace: {}".format(attr)) 420 | 421 | elif kind == 1: # Variable 422 | out = session.get(attr) 423 | 424 | elif kind in (2, 3, 5, 6): # Function 425 | out = MatlabFunction(name=attr, session_ref=self._session_ref) 426 | 427 | else: 428 | raise NotImplementedError("Unknown variable/function type in MATLAB workspace: {}".format(attr)) 429 | 430 | return out 431 | 432 | 433 | def __setattr__(self, name, value): 434 | 435 | if name.startswith('_'): 436 | object.__setattr__(self, name, value) 437 | else: 438 | session = self._session_ref() 439 | session.put(name, value) 440 | 441 | 442 | 443 | class MatlabFunction(object): 444 | def __init__(self, name, session_ref): 445 | self.name = name 446 | self._session_ref = session_ref 447 | 448 | 449 | def __call__(self, *args, **kwargs): 450 | session = self._session_ref() 451 | 452 | 453 | ### Left-hand side (returns) string 454 | nout = kwargs.get('nout', 1) 455 | outs = ["OUT{}__".format(i) for i in range(nout)] 456 | outs_str = ','.join(outs) 457 | 458 | 459 | ### Right hand side (arguments) string 460 | ins = [] 461 | for i,a in enumerate(args): 462 | aname = "ARG{}__".format(i) 463 | session.put(aname, a) 464 | ins.append(aname) 465 | ins_str = ','.join(ins) 466 | 467 | 468 | ### MATLAB command 469 | if outs: 470 | cmd = "[{outs}] = {name}({ins})".format( 471 | outs=outs_str, 472 | name=self.name, 473 | ins=ins_str 474 | ) 475 | else: 476 | cmd = "{name}({ins})".format( 477 | name=self.name, 478 | ins=ins_str 479 | ) 480 | 481 | 482 | ### Run the function 483 | session.eval(cmd) 484 | 485 | 486 | ### Clear input variables in MATLAB 487 | if ins: 488 | session.eval("clear {}".format(' '.join(ins))) 489 | 490 | 491 | ### Get the resulst from MATLAB 492 | rets = [] 493 | for o in outs: 494 | r = session.get(o) 495 | rets.append(r) 496 | 497 | 498 | ### Clear the resutls in MATLAB 499 | if outs: 500 | session.eval("clear {}".format(' '.join(outs))) 501 | 502 | 503 | ### Return the results 504 | if len(rets) == 1: 505 | ret = rets[0] 506 | else: 507 | ret = tuple(rets) 508 | 509 | return ret 510 | 511 | @property 512 | def __doc__(self): 513 | 514 | session = self._session_ref() 515 | 516 | session.eval( 517 | "DOC__ = help('{}')".format(self.name) 518 | ) 519 | 520 | doc = session.get('DOC__') 521 | 522 | session.eval("clear DOC__") 523 | 524 | return doc 525 | 526 | 527 | 528 | def mxarray_to_ndarray(libmx, pm): 529 | """Convert MATLAB object `pm` to numpy equivalent.""" 530 | 531 | ndims = libmx.mxGetNumberOfDimensions(pm) 532 | dims = libmx.mxGetDimensions(pm) 533 | numelems = libmx.mxGetNumberOfElements(pm) 534 | elem_size = libmx.mxGetElementSize(pm) 535 | class_name = libmx.mxGetClassName(pm) 536 | is_numeric = libmx.mxIsNumeric(pm) 537 | is_complex = libmx.mxIsComplex(pm) 538 | data = libmx.mxGetData(pm) 539 | imag_data = libmx.mxGetImagData(pm) 540 | 541 | 542 | if is_numeric: 543 | datasize = numelems*elem_size 544 | 545 | real_buffer = ctypes.create_string_buffer(datasize) 546 | ctypes.memmove(real_buffer, data, datasize) 547 | pyarray = np.ndarray( 548 | buffer=real_buffer, 549 | shape=dims[:ndims], 550 | dtype=class_name, 551 | order='F' 552 | ) 553 | 554 | if is_complex: 555 | imag_buffer = ctypes.create_string_buffer(datasize) 556 | ctypes.memmove(imag_buffer, imag_data, datasize) 557 | pyarray_imag = np.ndarray( 558 | buffer=imag_buffer, 559 | shape=dims[:ndims], 560 | dtype=class_name, 561 | order='F' 562 | ) 563 | 564 | pyarray = pyarray + pyarray_imag * 1j 565 | 566 | out = pyarray.squeeze() 567 | 568 | if out.ndim == 0: 569 | out, = np.atleast_1d(out) 570 | 571 | 572 | elif class_name == 'char': 573 | datasize = numelems + 1 574 | 575 | pystring = ctypes.create_string_buffer(datasize+1) 576 | libmx.mxGetString(pm, pystring, datasize) 577 | 578 | out = pystring.value 579 | 580 | 581 | elif class_name == 'logical': 582 | datasize = numelems*elem_size 583 | 584 | buf = ctypes.create_string_buffer(datasize) 585 | ctypes.memmove(buf, data, datasize) 586 | 587 | pyarray = np.ndarray( 588 | buffer=buf, 589 | shape=dims[:ndims], 590 | dtype='bool', 591 | order='F' 592 | ) 593 | 594 | out = pyarray.squeeze() 595 | if out.ndim == 0: 596 | out, = np.atleast_1d(out) 597 | 598 | 599 | elif class_name == 'cell': 600 | out = np.empty(numelems, dtype='O') 601 | for i in range(numelems): 602 | cell = libmx.mxGetCell(pm, i) 603 | 604 | if bool(cell): 605 | out[i] = mxarray_to_ndarray(libmx, cell) 606 | else: 607 | ### uninitialized cell 608 | out[i] = None 609 | 610 | out = out.reshape(dims[:ndims], order='F') 611 | out = out.squeeze() 612 | 613 | 614 | elif class_name == 'struct': 615 | field_num = libmx.mxGetNumberOfFields(pm) 616 | 617 | ### Get all field names 618 | field_names = [] 619 | for i in range(field_num): 620 | field_name = libmx.mxGetFieldNameByNumber(pm, i) 621 | field_names.append(field_name) 622 | 623 | ### Get all fields 624 | records = [] # [(x0, y0, z0), (x1, y1, z1), ... (xN, yN, zN)] 625 | for i in range(numelems): 626 | record = [] 627 | for field_name in field_names: 628 | field = libmx.mxGetField(pm, i, field_name) 629 | 630 | if bool(field): 631 | el = mxarray_to_ndarray(libmx, field) 632 | else: 633 | ### uninitialized cell 634 | el = None 635 | 636 | record.append(el) 637 | records.append(record) 638 | 639 | ### Set the dtypes right (if there is any ndarray, we want dtype=object) 640 | arrays = zip(*records) # [(x0, x1, ... xN), (y0, y1, ... yN), (z0, z1, ... zN)] 641 | new_arrays = [] 642 | 643 | ## This loop is necessary, because np.rec.fromarrays() cannot 644 | ## handle a list of arrays of the same size well 645 | for arr in arrays: 646 | contains_ndarray = np.any([isinstance(el, np.ndarray) for el in arr]) 647 | 648 | if contains_ndarray: 649 | newarr = np.empty(len(arr), dtype='O') 650 | for i,a in enumerate(arr): 651 | newarr[i] = a 652 | else: 653 | newarr = np.array(arr) 654 | 655 | new_arrays.append(newarr) 656 | 657 | if new_arrays: 658 | out = np.rec.fromarrays(new_arrays, names=field_names) 659 | out = out.reshape(dims[:ndims], order='F') 660 | out = out.squeeze() 661 | else: 662 | out = np.array([]) 663 | 664 | 665 | else: 666 | raise NotImplementedError('{}-arrays are not supported'.format(class_name)) 667 | 668 | 669 | return out 670 | 671 | 672 | 673 | 674 | def ndarray_to_mxarray(libmx, arr): 675 | 676 | ### Prepare `arr` object (convert to ndarray if possible), assert 677 | ### data type 678 | if isinstance(arr, str) or isinstance(arr, unicode): 679 | pass 680 | 681 | elif isinstance(arr, dict): 682 | raise NotImplementedError('dicts are not supported.') 683 | 684 | elif ('pandas' in sys.modules) and isinstance(arr, sys.modules['pandas'].DataFrame): 685 | arr = arr.to_records() 686 | 687 | elif ('pandas' in sys.modules) and isinstance(arr, sys.modules['pandas'].Series): 688 | arr = arr.to_frame().to_records() 689 | 690 | elif isinstance(arr, collections.Iterable): 691 | arr = np.array(arr, ndmin=2) 692 | 693 | elif np.issctype(type(arr)): 694 | arr = np.array(arr, ndmin=2) 695 | 696 | else: 697 | raise NotImplementedError("Data type not supported: {}".format(type(arr))) 698 | 699 | 700 | 701 | 702 | ### Convert ndarray to mxarray 703 | if isinstance(arr, str): 704 | pm = libmx.mxCreateString(arr) 705 | 706 | elif isinstance(arr, unicode): 707 | pm = libmx.mxCreateString(arr.encode('utf-8')) 708 | 709 | elif isinstance(arr, np.ndarray) and arr.dtype.kind in ['i','u','f','c']: 710 | dim = arr.ctypes.shape_as(mwSize) 711 | complex_flag = (arr.dtype.kind == 'c') 712 | 713 | pm = libmx.mxCreateNumericArray( 714 | arr.ndim, 715 | dim, 716 | dtype_to_mat(arr.dtype), 717 | complex_flag 718 | ) 719 | 720 | mat_data = libmx.mxGetData(pm) 721 | np_data = arr.real.tostring('F') 722 | ctypes.memmove(mat_data, np_data, len(np_data)) 723 | 724 | if complex_flag: 725 | mat_data = libmx.mxGetImagData(pm) 726 | np_data = arr.imag.tostring('F') 727 | ctypes.memmove(mat_data, np_data, len(np_data)) 728 | 729 | 730 | elif isinstance(arr, np.ndarray) and arr.dtype.kind == 'b': 731 | dim = arr.ctypes.shape_as(mwSize) 732 | 733 | pm = libmx.mxCreateLogicalArray(arr.ndim, dim) 734 | 735 | mat_data = libmx.mxGetData(pm) 736 | np_data = arr.real.tostring('F') 737 | ctypes.memmove(mat_data, np_data, len(np_data)) 738 | 739 | 740 | elif isinstance(arr, np.ndarray) and arr.dtype.kind in ('O', 'S', 'U'): 741 | dim = arr.ctypes.shape_as(mwSize) 742 | 743 | pm = libmx.mxCreateCellArray(arr.ndim, dim) 744 | 745 | for i,el in enumerate(arr.flatten('F')): 746 | p = ndarray_to_mxarray(libmx, el) 747 | libmx.mxSetCell(pm, i, p) 748 | 749 | 750 | elif isinstance(arr, np.ndarray) and len(arr.dtype) > 0: 751 | dim = arr.ctypes.shape_as(mwSize) 752 | 753 | name_num = len(arr.dtype.names) 754 | 755 | names_p = (c_char_p*name_num)(*[c_char_p(name) for name in arr.dtype.names]) 756 | 757 | pm = libmx.mxCreateStructArray( 758 | arr.ndim, 759 | dim, 760 | name_num, 761 | names_p, 762 | ) 763 | 764 | for i,record in enumerate(arr.flatten('F')): 765 | for name in arr.dtype.names: 766 | el = record[name] 767 | p = ndarray_to_mxarray(libmx, el) 768 | 769 | libmx.mxSetField(pm, i, name, p) 770 | 771 | elif isinstance(arr, np.ndarray): 772 | raise NotImplementedError('Unsupported dtype: {}'.format(arr.dtype)) 773 | 774 | return pm 775 | 776 | 777 | 778 | class Library(object): 779 | """Shared library proxy. 780 | 781 | The purpouse of this class is to wrap CDLL objects and append 782 | `_730` to function names on the fly. It should resolve the int vs 783 | mwSize problems for those functions. 784 | 785 | It also initializes library functions by setting `artypes`, 786 | `restype` and `errcheck` attributes. 787 | 788 | """ 789 | def __init__(self, name, **kwargs): 790 | self._lib = ctypes.CDLL(name, **kwargs) 791 | 792 | if 'libeng' in name: 793 | 794 | self.engOpen.argtypes = (c_char_p,) 795 | self.engOpen.restype = POINTER(Engine) 796 | self.engOpen.errcheck = error_check 797 | 798 | self.engPutVariable.argtypes = (POINTER(Engine), c_char_p, POINTER(mxArray)) 799 | self.engPutVariable.restype = c_int 800 | self.engPutVariable.errcheck = error_check 801 | 802 | self.engGetVariable.argtypes = (POINTER(Engine), c_char_p) 803 | self.engGetVariable.restype = POINTER(mxArray) 804 | self.engGetVariable.errcheck = error_check 805 | 806 | self.engEvalString.argtypes = (POINTER(Engine), c_char_p) 807 | self.engEvalString.restype = c_int 808 | self.engEvalString.errcheck = error_check 809 | 810 | self.engOutputBuffer.argtypes = (POINTER(Engine), c_char_p, c_int) 811 | self.engOutputBuffer.restype = c_int 812 | self.engOutputBuffer.errcheck = error_check 813 | 814 | self.engClose.argtypes = (POINTER(Engine),) 815 | self.engClose.restype = c_int 816 | self.engClose.errcheck = error_check 817 | 818 | elif 'libmx' in name: 819 | 820 | self.mxGetNumberOfDimensions.argtypes = (POINTER(mxArray),) 821 | self.mxGetNumberOfDimensions.restype = mwSize 822 | 823 | self.mxGetDimensions.argtypes = (POINTER(mxArray),) 824 | self.mxGetDimensions.restype = POINTER(mwSize) 825 | 826 | self.mxGetNumberOfElements.argtypes = (POINTER(mxArray),) 827 | self.mxGetNumberOfElements.restype = c_size_t 828 | 829 | self.mxGetElementSize.argtypes = (POINTER(mxArray),) 830 | self.mxGetElementSize.restype = c_size_t 831 | 832 | self.mxGetClassName.argtypes = (POINTER(mxArray),) 833 | self.mxGetClassName.restype = c_char_p 834 | 835 | self.mxIsNumeric.argtypes = (POINTER(mxArray),) 836 | self.mxIsNumeric.restype = c_bool 837 | 838 | self.mxIsCell.argtypes = (POINTER(mxArray),) 839 | self.mxIsCell.restype = c_bool 840 | 841 | self.mxIsComplex.argtypes = (POINTER(mxArray),) 842 | self.mxIsComplex.restype = c_bool 843 | 844 | self.mxGetData.argtypes = (POINTER(mxArray),) 845 | self.mxGetData.restype = POINTER(c_void_p) 846 | self.mxGetData.errcheck = error_check 847 | 848 | self.mxGetImagData.argtypes = (POINTER(mxArray),) 849 | self.mxGetImagData.restype = POINTER(c_void_p) 850 | self.mxGetImagData.errcheck = error_check 851 | 852 | self.mxGetCell.argtypes = (POINTER(mxArray), mwIndex) 853 | self.mxGetCell.restype = POINTER(mxArray) 854 | ### Errors has to be handled elswhere, because of NULL on uninitialized cells 855 | # self.mxGetCell.errcheck = error_check 856 | 857 | self.mxSetCell.argtypes = (POINTER(mxArray), mwIndex, POINTER(mxArray)) 858 | self.mxSetCell.restype = None 859 | 860 | self.mxGetNumberOfFields.argtypes = (POINTER(mxArray),) 861 | self.mxGetNumberOfFields.restype = c_int 862 | self.mxGetNumberOfFields.errcheck = error_check 863 | 864 | self.mxGetFieldNameByNumber.argtypes = (POINTER(mxArray), c_int) 865 | self.mxGetFieldNameByNumber.restype = c_char_p 866 | self.mxGetFieldNameByNumber.errcheck = error_check 867 | 868 | self.mxGetField.argtypes = (POINTER(mxArray), mwIndex, c_char_p) 869 | self.mxGetField.restype = POINTER(mxArray) 870 | ### Errors has to be handled elswhere, because of NULL on uninitialized fields 871 | # self.mxGetField.errcheck = error_check 872 | 873 | self.mxSetField.argtypes = (POINTER(mxArray), mwIndex, c_char_p, POINTER(mxArray)) 874 | self.mxSetField.restype = None 875 | 876 | self.mxCreateStructArray.argtypes = (mwSize, POINTER(mwSize), c_int, POINTER(c_char_p)) 877 | self.mxCreateStructArray.restype = POINTER(mxArray) 878 | self.mxCreateStructArray.errcheck = error_check 879 | 880 | self.mxArrayToString.argtypes = (POINTER(mxArray),) 881 | self.mxArrayToString.restype = c_char_p 882 | self.mxArrayToString.errcheck = error_check 883 | 884 | self.mxCreateString.argtypes = (c_char_p,) 885 | self.mxCreateString.restype = POINTER(mxArray) 886 | self.mxCreateString.errcheck = error_check 887 | 888 | self.mxGetString.argtypes = (POINTER(mxArray), c_char_p, mwSize) 889 | self.mxGetString.restype = c_int 890 | self.mxGetString.errcheck = error_check 891 | 892 | self.mxCreateNumericArray.argtypes = (mwSize, POINTER(mwSize), c_int, c_int) 893 | self.mxCreateNumericArray.restype = POINTER(mxArray) 894 | self.mxCreateNumericArray.errcheck = error_check 895 | 896 | self.mxCreateLogicalArray.argtypes = (mwSize, POINTER(mwSize)) 897 | self.mxCreateLogicalArray.restype = POINTER(mxArray) 898 | self.mxCreateLogicalArray.errcheck = error_check 899 | 900 | self.mxCreateCellArray.argtypes = (mwSize, POINTER(mwSize)) 901 | self.mxCreateCellArray.restype = POINTER(mxArray) 902 | self.mxCreateCellArray.errcheck = error_check 903 | 904 | self.mxDestroyArray.argtypes = (POINTER(mxArray),) 905 | self.mxDestroyArray.restype = None 906 | 907 | else: 908 | raise RuntimeError("Unknown library to configure: {}".format(name)) 909 | 910 | 911 | 912 | def __getattr__(self, attr): 913 | 914 | attr730 = attr + '_730' 915 | 916 | try: 917 | out = getattr(self._lib, attr730) 918 | except AttributeError: 919 | out = getattr(self._lib, attr) 920 | 921 | return out 922 | -------------------------------------------------------------------------------- /matlab_wrapper/typeconv.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # Copyright 2010-2013 Joakim Möller 4 | # Copyright 2014 Marek Rudnicki 5 | # 6 | # This file is part of matlab_wrapper. 7 | # 8 | # matlab_wrapper is free software: you can redistribute it and/or modify 9 | # it under the terms of the GNU General Public License as published by 10 | # the Free Software Foundation, either version 3 of the License, or 11 | # (at your option) any later version. 12 | # 13 | # matlab_wrapper is distributed in the hope that it will be useful, 14 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | # GNU General Public License for more details. 17 | # 18 | # You should have received a copy of the GNU General Public License 19 | # along with matlab_wrapper. If not, see . 20 | 21 | 22 | from ctypes import * 23 | from numpy import array,ndarray,dtype 24 | from os.path import join 25 | import platform 26 | import sys,numpy 27 | 28 | 29 | def dtype_to_mat(dtype): 30 | 31 | #Typedef enum 32 | #{ 33 | #0 mxUNKNOWN_CLASS = 0, 34 | #1 mxCELL_CLASS, 35 | #2 mxSTRUCT_CLASS, 36 | #3 mxLOGICAL_CLASS, 37 | if dtype.type == numpy.bool_: 38 | matlab_type = c_int(3) 39 | #4 mxCHAR_CLASS, 40 | elif dtype.type == numpy.str_: 41 | matlab_type = c_int(4) 42 | #5 mxVOID_CLASS, 43 | elif dtype.type == numpy.void: 44 | matlab_type = c_int(5) 45 | #6 mxDOUBLE_CLASS, 46 | elif dtype.type == numpy.complex128: 47 | matlab_type = c_int(6) 48 | elif dtype.type == numpy.float64: 49 | matlab_type = c_int(6) 50 | #7 mxSINGLE_CLASS, 51 | elif dtype.type ==numpy.complex64: 52 | matlab_type = c_int(7) 53 | elif dtype.type ==numpy.float32: 54 | matlab_type = c_int(7) 55 | #8 mxINT8_CLASS, 56 | elif dtype.type ==numpy.int8: 57 | matlab_type = c_int(8) 58 | #9 mxUINT8_CLASS, 59 | elif dtype.type ==numpy.uint8: 60 | matlab_type = c_int(9) 61 | #10 mxINT16_CLASS, 62 | elif dtype.type ==numpy.int16: 63 | matlab_type = c_int(10) 64 | #11 mxUINT16_CLASS, 65 | elif dtype.type ==numpy.uint16: 66 | matlab_type = c_int(11) 67 | #12 mxINT32_CLASS, 68 | elif dtype.type ==numpy.int32: 69 | matlab_type = c_int(12) 70 | #13 mxUINT32_CLASS, 71 | elif dtype.type ==numpy.uint32: 72 | matlab_type = c_int(13) 73 | #14 mxINT64_CLASS, 74 | elif dtype.type ==numpy.int64: 75 | matlab_type = c_int(14) 76 | #15 mxUINT64_CLASS, 77 | elif dtype.type ==numpy.uint64: 78 | matlab_type = c_int(15) 79 | #16 mxFUNCTION_CLASS, 80 | #17 mxOPAQUE_CLASS, 81 | #18 mxOBJECT_CLASS, /* keep the last real item in the list */ 82 | # #if defined(_LP64) || defined(_WIN64) 83 | # mxINDEX_CLASS = mxUINT64_CLASS, 84 | # #else 85 | # mxINDEX_CLASS = mxUINT32_CLASS, 86 | # #endif 87 | # /* TEMPORARY AND NASTY HACK UNTIL mxSPARSE_CLASS IS COMPLETELY ELIMINATED */ 88 | # mxSPARSE_CLASS = mxVOID_CLASS /* OBSOLETE! DO NOT USE */ 89 | # } 90 | else: 91 | matlab_type = c_int(5) #VOID_CLASS 92 | #MxClassID; 93 | return matlab_type 94 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | 3 | from setuptools import setup, find_packages 4 | 5 | with open('README.rst') as file: 6 | long_description = file.read() 7 | 8 | setup( 9 | name="matlab_wrapper", 10 | version="1", 11 | author="Marek Rudnicki", 12 | author_email="marekrud@posteo.de", 13 | 14 | description="MATLAB wrapper for Python", 15 | license="GPLv3", 16 | url="https://github.com/mrkrd/matlab_wrapper", 17 | download_url="https://github.com/mrkrd/matlab_wrapper/tarball/master", 18 | 19 | packages=find_packages(), 20 | long_description=long_description, 21 | classifiers=[ 22 | "Development Status :: 4 - Beta", 23 | "Environment :: Console", 24 | "Intended Audience :: End Users/Desktop", 25 | "Intended Audience :: Science/Research", 26 | "License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)", 27 | "Operating System :: POSIX", 28 | "Operating System :: POSIX :: Linux", 29 | "Operating System :: Microsoft :: Windows", 30 | "Operating System :: MacOS :: MacOS X", 31 | "Programming Language :: Python", 32 | "Programming Language :: Python :: 2", 33 | "Programming Language :: Python :: 2.7", 34 | ], 35 | 36 | platforms=["Linux", "Windows", "OSX"], 37 | install_requires=["numpy"], 38 | ) 39 | -------------------------------------------------------------------------------- /tests/leak_loops/putget_loop.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """Keep putting and getting a variable to MATLAB's workspace. 5 | 6 | """ 7 | 8 | from __future__ import division, absolute_import, print_function 9 | 10 | import numpy as np 11 | 12 | import matlab_wrapper 13 | import psutil 14 | 15 | 16 | def main(): 17 | matlab = matlab_wrapper.MatlabSession() 18 | 19 | p = psutil.Process() 20 | 21 | i = 0 22 | while True: 23 | print(i, p.memory_percent(), p.memory_info()) 24 | 25 | a = np.random.randn(1e7) 26 | 27 | matlab.put('a', a) 28 | matlab.get('a') 29 | 30 | i += 1 31 | 32 | 33 | if __name__ == "__main__": 34 | main() 35 | -------------------------------------------------------------------------------- /tests/leak_loops/restart_loop.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """Keep restarting MATLAB. 5 | 6 | """ 7 | 8 | from __future__ import division, absolute_import, print_function 9 | 10 | import matlab_wrapper 11 | import psutil 12 | 13 | 14 | def main(): 15 | 16 | p = psutil.Process() 17 | 18 | i = 0 19 | while True: 20 | print(i, p.memory_percent(), p.memory_info()) 21 | 22 | matlab = matlab_wrapper.MatlabSession() 23 | 24 | i += 1 25 | 26 | 27 | if __name__ == "__main__": 28 | main() 29 | -------------------------------------------------------------------------------- /tests/test_matlab.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | """Test MatlabSession 5 | 6 | """ 7 | 8 | from __future__ import division, absolute_import, print_function 9 | 10 | import numpy as np 11 | from numpy.testing import assert_equal, assert_almost_equal 12 | import pandas as pd 13 | 14 | import matlab_wrapper 15 | 16 | import pytest 17 | 18 | 19 | NUMERIC_DTYPES = ('int8', 'int16', 'int32', 'int64', 'uint8', 20 | 'uint16', 'uint32', 'uint64', 'single', 'double') 21 | 22 | 23 | np.random.seed(0) 24 | 25 | 26 | @pytest.fixture(scope='module') 27 | def matlab(): 28 | matlab = matlab_wrapper.MatlabSession( 29 | options='-nojvm', 30 | buffer_size=1024 31 | ) 32 | return matlab 33 | 34 | 35 | 36 | def test_eval_ok(matlab): 37 | command = "a = ones(10)" 38 | matlab.eval(command) 39 | 40 | 41 | 42 | def test_eval_error(matlab): 43 | command = "a = onesBLA(10)" 44 | 45 | with pytest.raises(RuntimeError): 46 | matlab.eval(command) 47 | 48 | 49 | def test_clear(matlab): 50 | command = "clear all" 51 | matlab.eval(command) 52 | 53 | 54 | def test_longscript(matlab): 55 | command = """ 56 | for i=1:10 57 | sprintf('aoeu %i',i); 58 | end 59 | """ 60 | matlab.eval(command) 61 | 62 | 63 | def test_get_numeric(matlab): 64 | for dtype in NUMERIC_DTYPES: 65 | 66 | a = np.eye(4,5, dtype=dtype) 67 | matlab.eval("b = eye(4,5, '{}')".format(dtype)) 68 | b = matlab.get('b') 69 | 70 | assert_equal(a.dtype, b.dtype) 71 | assert_equal(a, b) 72 | 73 | 74 | def test_get_logical(matlab): 75 | a = np.eye(4,5, dtype='bool') 76 | matlab.eval("b = eye(4,5) > 0") 77 | b = matlab.get('b') 78 | 79 | assert_equal(a.dtype, b.dtype) 80 | assert_equal(a, b) 81 | 82 | 83 | def test_get_comples(matlab): 84 | for dtype in ('single', 'double'): 85 | a = np.eye(4,5, dtype=dtype) + np.eye(4,5, dtype=dtype)*1j 86 | matlab.eval("b = eye(4,5, '{0}') + eye(4,5, '{0}')*j".format(dtype)) 87 | b = matlab.get('b') 88 | 89 | assert_equal(a.dtype, b.dtype) 90 | assert_equal(a, b) 91 | 92 | 93 | def test_get_string(matlab): 94 | matlab.eval("s = 'asdf'") 95 | s = matlab.get('s') 96 | 97 | assert_equal(s, 'asdf') 98 | 99 | 100 | def test_get_float(matlab): 101 | matlab.eval("a = 1.") 102 | a = matlab.get('a') 103 | 104 | assert_equal(a, 1.) 105 | 106 | 107 | 108 | def test_put_numeric(matlab): 109 | for dtype in NUMERIC_DTYPES: 110 | a = np.random.randn(2,3) * 10 111 | a = a.astype(dtype) 112 | 113 | matlab.put('a', a) 114 | matlab.eval('a') 115 | 116 | output = matlab.output_buffer 117 | 118 | numbers = output.split()[-6:] 119 | numbers = np.array(numbers, dtype=dtype) 120 | numbers.shape = (2,3) 121 | 122 | assert_almost_equal(a, numbers, decimal=4) 123 | 124 | 125 | def test_put_logical(matlab): 126 | a = np.random.randn(2,3)>0 127 | 128 | matlab.put('a', a) 129 | matlab.eval('a') 130 | 131 | output = matlab.output_buffer 132 | 133 | numbers = output.split()[-6:] 134 | numbers = np.array(numbers, dtype=int).astype('bool') 135 | numbers.shape = (2,3) 136 | 137 | assert_equal(a, numbers) 138 | 139 | 140 | 141 | 142 | def test_put_complex128(matlab): 143 | for dtype in ('complex128', 'complex64'): 144 | nums = np.linspace(0.1, 10, 6).reshape(2,3) 145 | 146 | a = nums + nums*1j 147 | a = a.astype(dtype) 148 | 149 | matlab.put('a', a) 150 | matlab.eval('a') 151 | 152 | output = matlab.output_buffer.split('\n') 153 | 154 | assert_equal(output[3], ' 0.1000 + 0.1000i 2.0800 + 2.0800i 4.0600 + 4.0600i') 155 | assert_equal(output[4], ' 6.0400 + 6.0400i 8.0200 + 8.0200i 10.0000 +10.0000i') 156 | 157 | 158 | 159 | def test_put_string(matlab): 160 | matlab.put('s', "asdf") 161 | matlab.eval('s') 162 | 163 | output = matlab.output_buffer.split() 164 | 165 | s = output[-1] 166 | 167 | assert_equal(s, "asdf") 168 | 169 | 170 | 171 | 172 | def test_put_unicode(matlab): 173 | matlab.put('s', u"Łódź") 174 | matlab.eval('s') 175 | 176 | output = matlab.output_buffer.split() 177 | 178 | s = output[-1].decode('utf-8') 179 | 180 | assert_equal(s, u"Łódź") 181 | 182 | 183 | 184 | def test_put_unicode_len(matlab): 185 | s = u"Łódź" 186 | matlab.put('s', s) 187 | matlab.eval('length(s)') 188 | 189 | output = matlab.output_buffer.split() 190 | 191 | length = int(output[-1]) 192 | 193 | assert_equal(length, len(s)) 194 | 195 | 196 | 197 | 198 | def test_put_float(matlab): 199 | matlab.put('a', 3.2) 200 | matlab.eval('a') 201 | 202 | output = matlab.output_buffer.split() 203 | 204 | a = float(output[-1]) 205 | 206 | assert_equal(a, 3.2) 207 | 208 | 209 | 210 | 211 | def test_put_get_numeric(matlab): 212 | for dtype in NUMERIC_DTYPES: 213 | a = np.random.randn(3,2,4) * 10 214 | a = a.astype(dtype) 215 | 216 | matlab.put('a', a) 217 | aa = matlab.get('a') 218 | 219 | assert_equal(a.dtype, aa.dtype) 220 | assert_equal(a, aa) 221 | 222 | 223 | 224 | def test_put_get_logical(matlab): 225 | a = np.random.randn(3,2,4)>0 226 | 227 | matlab.put('a', a) 228 | aa = matlab.get('a') 229 | 230 | assert_equal(a.dtype, aa.dtype) 231 | assert_equal(a, aa) 232 | 233 | 234 | def test_put_get_complex(matlab): 235 | for datatype in ("complex64", "complex128"): 236 | a = np.random.randn(2,4,3) + np.random.randn(2,4,3)*1j 237 | a = a.astype(datatype) 238 | 239 | matlab.put('a',a) 240 | aa = matlab.get('a') 241 | 242 | assert_equal(a.dtype, aa.dtype) 243 | assert_equal(a, aa) 244 | 245 | 246 | 247 | def test_put_get_string(matlab): 248 | s = "test string\n one more string" 249 | 250 | matlab.put('s', s) 251 | ss = matlab.get('s') 252 | 253 | assert_equal(s, ss) 254 | 255 | 256 | 257 | def test_workspace_func(matlab): 258 | 259 | x = np.arange(10, dtype=float) 260 | y = np.sin(x) 261 | 262 | ymatlab = matlab.workspace.sin(x) 263 | 264 | assert_equal(y, ymatlab) 265 | 266 | 267 | 268 | def test_workspace_nout(matlab): 269 | a = np.array([2,1,3]) 270 | 271 | y,i = matlab.workspace.sort(a, nout=2) 272 | 273 | assert_equal(y, [1,2,3]) 274 | assert_equal(i, a) 275 | 276 | 277 | def test_workspace_pi(matlab): 278 | 279 | pi = matlab.workspace.pi() 280 | 281 | assert_equal(pi, np.pi) 282 | 283 | 284 | def test_workspace_set_get(matlab): 285 | 286 | matlab.workspace.a = 12. 287 | 288 | matlab.eval("b = a*2") 289 | 290 | b = matlab.workspace.b 291 | 292 | assert_equal(b, 24) 293 | 294 | 295 | def test_get_cell(matlab): 296 | 297 | matlab.eval("c = {1, 2, 3; 'text', eye(2,3), {11; 22; 33}}") 298 | actual = matlab.workspace.c 299 | 300 | target = np.array( 301 | [ 302 | [1., 2., 3.], 303 | ['text', np.eye(2,3), np.array([11.,22.,33.], dtype='O')] 304 | ], 305 | dtype='O' 306 | ) 307 | 308 | assert_equal(actual.shape, target.shape) 309 | assert_equal(actual.dtype, target.dtype) 310 | 311 | for a,t in zip(actual.flatten(),target.flatten()): 312 | assert_equal(a,t) 313 | 314 | 315 | def test_get_uninitialized_cell(matlab): 316 | 317 | matlab.eval("c = {}; c{3} = 1") 318 | actual = matlab.workspace.c 319 | 320 | target = np.array( 321 | [None, None, np.array(1.)], 322 | dtype='O' 323 | ) 324 | 325 | assert_equal(actual.shape, target.shape) 326 | assert_equal(actual.dtype, target.dtype) 327 | 328 | for a,t in zip(actual.flatten(),target.flatten()): 329 | assert_equal(a,t) 330 | 331 | 332 | 333 | def test_put_cell(matlab): 334 | 335 | sub = np.array([3, 4.,'b'], dtype='O') 336 | c = np.array([ 337 | [1 , 'a'], 338 | [2., sub] 339 | ], dtype='O') 340 | 341 | 342 | matlab.put('c', c) 343 | 344 | ### check the main array 345 | matlab.eval('c') 346 | 347 | output = matlab.output_buffer.split('\n') 348 | 349 | assert_equal(output[3], " [1] 'a' ") 350 | assert_equal(output[4], " [2] {1x3 cell}") 351 | 352 | 353 | ### check the sub-array 354 | matlab.eval('c{2,2}') 355 | 356 | output = matlab.output_buffer.split('\n') 357 | 358 | assert_equal(output[3], " [3] [4] 'b'") 359 | 360 | 361 | 362 | 363 | 364 | def test_put_get_cell(matlab): 365 | 366 | a = np.array( 367 | [ 368 | [1., 2., 3.], 369 | ['text', np.eye(2,3), np.array([11.,22.,33.], dtype='O')] 370 | ], 371 | dtype='O' 372 | ) 373 | 374 | matlab.workspace.a = a 375 | aa = matlab.workspace.a 376 | 377 | for el,elel in zip(a.flatten(),aa.flatten()): 378 | assert_equal(el,elel) 379 | 380 | 381 | 382 | 383 | 384 | def test_get_struct(matlab): 385 | 386 | matlab.eval(""" 387 | s = struct() 388 | s(1).x = 1 389 | s(1).y = 'a' 390 | s(2).x = 2i 391 | s(2).y = 'b' 392 | """) 393 | 394 | s = matlab.get('s') 395 | 396 | desired = np.array([ 397 | (1, 'a'), 398 | (2*1j, 'b') 399 | ], dtype=[('x', 'complex'), ('y', 'S1')]) 400 | 401 | assert_equal(s, desired) 402 | 403 | 404 | 405 | def test_get_uninitialized_struct(matlab): 406 | 407 | matlab.eval(""" 408 | s = struct() 409 | s(1,1).x = 1 410 | s(2,2).x = 2 411 | s(2,2).y = 'a' 412 | """) 413 | 414 | s = matlab.get('s') 415 | 416 | 417 | desired = np.array([ 418 | [(1, None), (None, None)], 419 | [(None, None), (2, 'a')] 420 | ], dtype=[('x', 'O'), ('y', 'O')]) 421 | 422 | assert_equal(s, desired) 423 | 424 | 425 | 426 | def test_get_empty_struct(matlab): 427 | 428 | matlab.eval("s = struct([])") 429 | 430 | s = matlab.get('s') 431 | 432 | desired = np.array([]) 433 | 434 | assert_equal(s, desired) 435 | 436 | 437 | 438 | def test_put_struct(matlab): 439 | 440 | a = np.rec.fromrecords([ 441 | (1, 'a', 1.), 442 | (2, 'bb', 2.), 443 | ]) 444 | 445 | matlab.put('a', a) 446 | 447 | ### 1st element 448 | matlab.eval('a(1)') 449 | 450 | output = matlab.output_buffer.split('\n') 451 | 452 | assert_equal(output[3], " f0: 1") 453 | assert_equal(output[4], " f1: 'a'") 454 | assert_equal(output[5], " f2: 1") 455 | 456 | 457 | ### 2nd element 458 | matlab.eval('a(2)') 459 | 460 | output = matlab.output_buffer.split('\n') 461 | 462 | assert_equal(output[3], " f0: 2") 463 | assert_equal(output[4], " f1: 'bb'") 464 | assert_equal(output[5], " f2: 2") 465 | 466 | 467 | 468 | 469 | def test_put_get_struct(matlab): 470 | 471 | a = np.rec.fromrecords([ 472 | (1, 'a', 1.), 473 | (2, 'bb', 2.), 474 | ]) 475 | 476 | matlab.put('a', a) 477 | 478 | aa = matlab.get('a') 479 | 480 | assert_equal(a, aa) 481 | 482 | 483 | 484 | def test_put_strings(matlab): 485 | s = ['asdf', 'a', 'BBB'] 486 | 487 | matlab.put('s', s) 488 | matlab.eval('s') 489 | 490 | output = matlab.output_buffer.split('\n') 491 | 492 | assert_equal(output[3], " 'asdf' 'a' 'BBB'") 493 | 494 | 495 | 496 | 497 | def test_put_get_dataframe(matlab): 498 | df = pd.DataFrame([ 499 | {'a': 1, 'b': 2, 'c': 'asdf'}, 500 | {'a': 1.1, 'b': 4, 'c': 'marek'}, 501 | ]) 502 | 503 | matlab.put('df', df) 504 | a = matlab.get('df') 505 | 506 | desired = np.array([ 507 | (0, 1.0, 2, 'asdf'), 508 | (1, 1.1, 4, 'marek') 509 | ], dtype=[('index', '