From cadac019b6cdabe5d42b3658414e1842662aac37 Mon Sep 17 00:00:00 2001 From: Sam Scholten Date: Thu, 11 Sep 2025 14:49:58 +1000 Subject: init --- .gitignore | 6 + LICENSE | 674 ++++++++++++++++++++++++++++++++++++++++ Makefile | 18 ++ README.md | 114 +++++++ picostream/__init__.py | 0 picostream/consumer.py | 141 +++++++++ picostream/conversion_utils.py | 86 ++++++ picostream/dfplot.py | 608 ++++++++++++++++++++++++++++++++++++ picostream/main.py | 562 +++++++++++++++++++++++++++++++++ picostream/pico.py | 495 +++++++++++++++++++++++++++++ picostream/reader.py | 259 ++++++++++++++++ pyproject.toml | 24 ++ status_values_pico.html | 683 +++++++++++++++++++++++++++++++++++++++++ 13 files changed, 3670 insertions(+) create mode 100644 .gitignore create mode 100644 LICENSE create mode 100644 Makefile create mode 100644 README.md create mode 100644 picostream/__init__.py create mode 100644 picostream/consumer.py create mode 100644 picostream/conversion_utils.py create mode 100644 picostream/dfplot.py create mode 100644 picostream/main.py create mode 100644 picostream/pico.py create mode 100644 picostream/reader.py create mode 100644 pyproject.toml create mode 100644 status_values_pico.html diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a7c3d30 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +conda_env* +output.hdf5 +*__pycache__* +complexipy.json +build/* +*egg-info* diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..0667639 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..c9a7a95 --- /dev/null +++ b/Makefile @@ -0,0 +1,18 @@ + + + +format: + ruff format + ruff check --fix --select F,B,I . + ruff format + +lint: + prospector --with-tool mypy + +complexity: + complexipy --sort asc . + +complexity-json: + complexipy --sort desc --output-json . + + diff --git a/README.md b/README.md new file mode 100644 index 0000000..2bcca2e --- /dev/null +++ b/README.md @@ -0,0 +1,114 @@ +# PicoStream + +PicoStream is a high-performance Python application for streaming data from a PicoScope to an HDF5 file, with an optional, decoupled live visualization. It is designed for robust, high-speed data logging where data integrity is critical. + +## Features + +- **Robust Architecture**: Separates data acquisition from disk I/O using a producer-consumer pattern with a large, shared memory buffer pool to prevent data loss. +- **Zero-Risk Live Plotting**: The plotter reads from the HDF5 file, not the live data stream. This ensures that a slow or crashing GUI cannot interfere with data acquisition. +- **Efficient Visualization**: Uses `pyqtgraph` and a Numba-accelerated min-max decimation algorithm to display large datasets with minimal CPU impact. +- **Flexible Data Reading**: The included `PicoStreamReader` class allows for easy post-processing, including on-the-fly decimation ('mean' or 'min_max'). + +## Installation + +1. `pip install -e .` + +2. Install the official PicoSDK from Pico Technology. Linux can take some additional work, see the AUR wiki for details. + +## Usage + +The primary way to use the package is through the `picostream` command-line tool. + +### Acquisition + +The following command starts an acquisition at 62.5 MS/s and saves the data to `my_data.hdf5` with a live plot. + +```bash +picostream -s 62.5 -o my_data.hdf5 --plot +``` + +Run `picostream --help` for a full list of options. + +### Viewing an Existing File + +The plotter can be run as a standalone tool to view any compatible HDF5 file. + +```bash +python -m picostream.dfplot /path/to/your/data.hdf5 +``` + +## Data Analysis with `PicoStreamReader` + +The output HDF5 file contains raw ADC counts and metadata. The `PicoStreamReader` class in `picostream.reader` is the recommended way to read and process this data. + +### Example: Processing a File in Chunks + +Here is an example of how to use `PicoStreamReader` to iterate through a large file and perform analysis without loading the entire dataset into memory. + +```python +import numpy as np +from picostream.reader import PicoStreamReader + +# Use the reader as a context manager +with PicoStreamReader('my_data.hdf5') as reader: + # Metadata is available as attributes after opening + sample_rate_sps = 1e9 / reader.sample_interval_ns + print(f"File contains {reader.num_samples:,} samples.") + print(f"Sample rate: {sample_rate_sps / 1e6:.2f} MS/s") + + # Example: Iterate through the file with 10x decimation + print("\nProcessing data with 10x 'min_max' decimation...") + for times, voltages_mv in reader.get_block_iter( + chunk_size=10_000_000, decimation_factor=10, decimation_mode='min_max' + ): + # The 'times' and 'voltages_mv' arrays are now decimated. + # Process the smaller data chunk here. + print(f" - Processed a chunk of {voltages_mv.size} decimated points.") + + print("\nFinished processing.") +``` + +## API Reference: `PicoStreamReader` + +The `PicoStreamReader` provides a simple and efficient interface for accessing data. + +### Initialization + +#### `__init__(self, hdf5_path: str)` +Initializes the reader. The file is opened and metadata is read when the object is used as a context manager. + +### Metadata Attributes + +These attributes are populated from the HDF5 file's metadata when the reader is opened. + +- `num_samples: int`: Total number of raw samples in the dataset. +- `sample_interval_ns: float`: The time interval between samples in nanoseconds. +- `voltage_range_v: float`: The configured voltage range (e.g., `20.0` for ±20V). +- `max_adc_val: int`: The maximum ADC count value (e.g., 32767). +- `analog_offset_v: float`: The configured analog offset in Volts. +- `downsample_mode: str`: The hardware downsampling mode used during acquisition (`'average'` or `'aggregate'`). +- `hardware_downsample_ratio: int`: The hardware downsampling ratio used. + +### Data Access Methods + +#### `get_block_iter(self, chunk_size: int = 1_000_000, decimation_factor: int = 1, decimation_mode: str = "mean") -> Generator` +Returns a generator that yields data blocks as `(times, voltages)` tuples for the entire dataset. This is the recommended method for processing large files. +- `chunk_size`: The number of *raw* samples to read from the file for each chunk. +- `decimation_factor`: The factor by which to decimate the data. +- `decimation_mode`: The decimation method (`'mean'` or `'min_max'`). + +#### `get_next_block(self, chunk_size: int, decimation_factor: int = 1, decimation_mode: str = "mean") -> Tuple | None` +Retrieves the next sequential block of data. Returns `None` when the end of the file is reached. Use `reset()` to start over. + +#### `get_block(self, size: int, start: int = 0, decimation_factor: int = 1, decimation_mode: str = "mean") -> Tuple` +Retrieves a specific block of data from the file. +- `size`: The number of *raw* samples to retrieve. +- `start`: The starting sample index. + +#### `reset(self) -> None` +Resets the internal counter for `get_next_block()` to the beginning of the file. + + +## Acknowledgements + +This package began as a fork of [JoshHarris2108/pico_streaming](https://github.com/JoshHarris2108/pico_streaming) (which is unlicensed). I acknowledge and appreciate Josh's original idea/architecture. diff --git a/picostream/__init__.py b/picostream/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/picostream/consumer.py b/picostream/consumer.py new file mode 100644 index 0000000..b1b2a5f --- /dev/null +++ b/picostream/consumer.py @@ -0,0 +1,141 @@ +from __future__ import annotations + +import os +import queue +import threading +from typing import Any, Dict, List + +import h5py +import numpy as np +from loguru import logger + + +class Consumer: + """A data consumer that runs in a separate thread. + + This class retrieves data buffers from a queue, writes them to an HDF5 file, + and then returns the buffer index to an "empty" queue for reuse by the + producer. It handles file creation, data writing, and metadata storage. + """ + + def __init__( + self, + buffer_size: int, + data_queue: queue.Queue[int], + empty_queue: queue.Queue[int], + data_buffers: List[np.ndarray], + file_name: str, + shutdown_event: threading.Event, + metadata: Dict[str, Any], + ): + """Initializes the Consumer. + + Args: + buffer_size: The size of each individual data buffer. + data_queue: A queue for receiving indices of data-filled buffers. + empty_queue: A queue for returning indices of processed (empty) buffers. + data_buffers: A list of pre-allocated NumPy arrays for data. + file_name: The path to the output HDF5 file. + shutdown_event: A threading.Event to signal termination. + metadata: A dictionary of metadata to be saved as HDF5 attributes. + """ + self.buffer_size = buffer_size + self.data_queue = data_queue + self.empty_queue = empty_queue + self.data_buffers = data_buffers + self.file_name = file_name + self.shutdown_event = shutdown_event + self.metadata = metadata + + self.values_written: int = 0 + self.empty_con_queue_count: int = 0 + + def format_sample_count(self, count: int) -> str: + """Format a large integer count into a human-readable string. + + Uses metric prefixes (K, M, G) for thousands, millions, and billions. + + Args: + count: The integer number to format. + + Returns: + A formatted string representation of the count. + """ + if count >= 1_000_000_000: + return f"{count / 1_000_000_000:.2f}G" + if count >= 1_000_000: + return f"{count / 1_000_000:.2f}M" + if count >= 1_000: + return f"{count / 1_000:.2f}K" + else: + return str(count) + + def _processing_loop(self, dset: h5py.Dataset) -> None: + """ + Continuously processes data from the queue and writes to the HDF5 dataset. + + Args: + dset: The HDF5 dataset to write to. + """ + while not self.shutdown_event.is_set(): + try: + # Wait for a buffer index from the producer. + # A timeout allows the loop to periodically check the shutdown event. + idx = self.data_queue.get(timeout=0.1) + + # Append the new data to the HDF5 dataset. + buffer_len = len(self.data_buffers[idx]) + dset.resize((self.values_written + buffer_len,)) + dset[self.values_written :] = self.data_buffers[idx] + + # Return the buffer index to the empty queue for reuse. + self.empty_queue.put(idx) + + self.values_written += buffer_len + + except queue.Empty: + # This occurs if the producer hasn't provided data within the timeout. + self.empty_con_queue_count += 1 + # This is expected when acquisition stops, so no need to log as a warning + if not self.shutdown_event.is_set(): + logger.debug("Consumer queue was empty.") + + def consume(self) -> None: + """The main loop for the consumer thread. + + This method continuously checks for data from the producer, writes it to + the HDF5 file, and returns the buffer for reuse. It handles file setup, + the main processing loop, and graceful shutdown. + """ + try: + # Ensure a clean slate by removing any pre-existing file. + if os.path.exists(self.file_name): + os.remove(self.file_name) + logger.info(f"Removed existing file: {self.file_name}") + + with h5py.File(self.file_name, "w") as f: + # Write the collected metadata to the HDF5 file's attributes. + for key, value in self.metadata.items(): + if value is not None: + f.attrs[key] = value + + # Create a resizable dataset for the ADC data. + # Chunking is aligned with the buffer size for efficient writes. + dset = f.create_dataset( + "adc_counts", + (0,), + maxshape=(None,), + dtype="int16", + chunks=(self.buffer_size,), + ) + + self._processing_loop(dset) + except (IOError, OSError) as e: + # A critical file error means we cannot continue. + logger.critical(f"Failed to create or write to HDF5 file: {e}") + self.shutdown_event.set() # Signal other threads to shut down. + return + + logger.info( + f"Consumer couldn't obtain data from queue {self.empty_con_queue_count} times." + ) diff --git a/picostream/conversion_utils.py b/picostream/conversion_utils.py new file mode 100644 index 0000000..cce8200 --- /dev/null +++ b/picostream/conversion_utils.py @@ -0,0 +1,86 @@ +from __future__ import annotations + +import numba as nb +import numpy as np + + +@nb.jit(nopython=True, fastmath=True) +def adc_to_mV( + adc_data: np.ndarray, voltage_range_v: float, max_adc_val: int +) -> np.ndarray: + """Convert ADC counts to voltage in millivolts (mV). + + This function is JIT-compiled with Numba for high performance. It uses the + maximum ADC value provided by the PicoScope driver to correctly scale the + raw integer ADC counts to a voltage. + + Args: + adc_data: A NumPy array of raw ADC integer values. + voltage_range_v: The single-sided voltage range in Volts. For a device + configured to ±1V, this value should be 1.0. + max_adc_val: The maximum ADC count value for the configured resolution, + as obtained from the `ps5000aMaximumValue` SDK function. + + Returns: + A NumPy array of the same shape as `adc_data`, with values converted + to millivolts. + """ + voltage_range_mv = voltage_range_v * 1000.0 # Convert Volts to milliVolts + # Scale ADC counts to millivolts. Cast to float64 for precision. + return (adc_data.astype(np.float64) * voltage_range_mv) / max_adc_val + + +@nb.jit(nopython=True, fastmath=True) +def min_max_decimate_numba(data: np.ndarray, factor: int) -> np.ndarray: + """Downsample data using a min-max technique to preserve signal envelope. + + This Numba-optimized function decimates an array by a given factor. For + each block of `factor` samples, it finds the minimum and maximum values. + The output array contains these min/max pairs, effectively preserving + transients and the signal envelope while reducing the number of data points. + + Note: Any remaining data points that do not form a complete block of size + `factor` at the end of the array are discarded. + + Args: + data: The 1D NumPy array of numerical data to be decimated. + factor: The decimation factor (an integer). + + Returns: + A new NumPy array containing the decimated data, with a length of + `2 * (len(data) // factor)`. The format is [min1, max1, min2, max2, ...]. + If `factor` is 1 or less, or if the input data has fewer points than + `factor`, the original data array is returned unmodified. + """ + # If the decimation factor is 1 or less, or data is too short, do nothing. + if factor <= 1 or len(data) < factor: + return data + + # Calculate how many full blocks of size `factor` we can process. + n_complete_groups = len(data) // factor + + # Pre-allocate the output array. It will hold 2 values (min and max) + # for each group. + decimated = np.empty(n_complete_groups * 2, dtype=data.dtype) + + # Iterate over each block of data. + for i in range(n_complete_groups): + start_idx = i * factor + end_idx = start_idx + factor + + # Find the minimum and maximum value in the current block. + # Initialize with the first value in the group. + group_min = data[start_idx] + group_max = data[start_idx] + + for j in range(start_idx + 1, end_idx): + if data[j] < group_min: + group_min = data[j] + if data[j] > group_max: + group_max = data[j] + + # Store the min and max pair in the output array. + decimated[i * 2] = group_min + decimated[i * 2 + 1] = group_max + + return decimated diff --git a/picostream/dfplot.py b/picostream/dfplot.py new file mode 100644 index 0000000..cac3a38 --- /dev/null +++ b/picostream/dfplot.py @@ -0,0 +1,608 @@ +from __future__ import annotations + +import sys +import threading +import time +from typing import List, Optional +import argparse + +import h5py +import numpy as np +import pyqtgraph as pg +from loguru import logger +from PyQt5.QtCore import Qt, QTimer +from PyQt5.QtGui import QCloseEvent, QFont, QKeyEvent +from PyQt5.QtWidgets import ( + QApplication, + QHBoxLayout, + QLabel, + QMainWindow, + QVBoxLayout, + QWidget, +) + +from .conversion_utils import adc_to_mV, min_max_decimate_numba + + +class HDF5LivePlotter(QMainWindow): + """ + Real-time oscilloscope-style plotter that reads from HDF5 files. + Completely independent of acquisition system for zero-risk operation. + """ + + def __init__( + self, + hdf5_path: str = "/tmp/data.hdf5", + update_interval_ms: int = 50, + display_window_seconds: float = 0.5, + decimation_factor: int = 150, + shutdown_event: Optional[threading.Event] = None, + ) -> None: + """Initializes the HDF5LivePlotter window. + + Args: + hdf5_path: Path to the HDF5 file to monitor. + update_interval_ms: How often to check the file for updates (in ms). + display_window_seconds: The time duration of data to display. + decimation_factor: The factor by which to decimate data for plotting. + shutdown_event: An event to signal graceful shutdown to the main application. + """ + super().__init__() + + # --- Configuration --- + self.hdf5_path: str = hdf5_path + self.update_interval_ms: int = update_interval_ms + self.display_window_seconds: float = display_window_seconds + self.decimation_factor: int = decimation_factor + self.shutdown_event: Optional[threading.Event] = shutdown_event + + # --- UI State --- + self.heartbeat_chars: List[str] = ["|", "/", "-", "\\"] + self.heartbeat_index: int = 0 + self.is_saturated: bool = False + + # --- Data Buffers --- + self.display_data: np.ndarray = np.array([]) + self.time_data: np.ndarray = np.array([]) + self.data_start_sample: int = 0 + + # --- HDF5 Metadata --- + self.sample_interval_ns: float = 16.0 # Default, will be read from file + self.hardware_downsample_ratio: int = 1 + self.ch_range: Optional[int] = None + self.voltage_range_v: Optional[float] = None + self.max_adc_val: Optional[int] = None + self.downsample_mode: Optional[str] = None + self.analog_offset_v: float = 0.0 + + # --- Debug Counters --- + self.update_count: int = 0 + self.file_read_count: int = 0 + self.display_update_count: int = 0 + + # --- Performance Monitoring --- + self.display_latency_ms: float = 0.0 + self.last_data_timestamp: Optional[float] = None + + # --- Rate Checking --- + self.rate_check_start_time: Optional[float] = None + self.rate_check_start_samples: int = 0 + + # --- Data Freshness Tracking --- + self.last_displayed_size: int = 0 + self.data_change_count: int = 0 + self.stale_update_count: int = 0 + self.last_freshness_check: float = time.time() + + # --- Error Tracking --- + self.conversion_error_count: int = 0 + self.file_error_count: int = 0 + + # Setup UI + self.setup_ui() + + # Setup update timer + self.timer = QTimer() + self.timer.timeout.connect(self.update_from_file) + self.timer.start(self.update_interval_ms) + + logger.info( + f"HDF5LivePlotter initialized: path={hdf5_path}, interval={update_interval_ms}ms" + ) + + # Initial file check + self.check_file_exists() + + def setup_ui(self) -> None: + """Sets up the main window, widgets, and plot layout.""" + self.setWindowTitle("PicoScope Live Plotter - HDF5 Reader") + self.setGeometry(100, 100, 1200, 800) + + # Central widget + central_widget = QWidget() + self.setCentralWidget(central_widget) + layout = QVBoxLayout(central_widget) + + # Status bar + status_layout = QHBoxLayout() + self.heartbeat_label = QLabel("UI: -") + self.samples_label = QLabel("Samples: 0") + self.rate_label = QLabel("Rate: -") + self.plotter_latency_label = QLabel("Plotter Latency: 0 ms") + self.error_label = QLabel("Errors: 0") + self.saturation_label = QLabel("Saturation: -") + self.acq_status_label = QLabel( + 'Waiting for file...' + ) + font = QFont() + font.setFamily("Monospace") + font.setFixedPitch(True) + for label in [ + self.heartbeat_label, + self.samples_label, + self.rate_label, + self.plotter_latency_label, + self.error_label, + self.saturation_label, + self.acq_status_label, + ]: + label.setFont(font) + + # Add separators between status items + status_layout.addWidget(self.heartbeat_label) + status_layout.addWidget(QLabel(" | ")) + status_layout.addWidget(self.error_label) + status_layout.addWidget(QLabel(" | ")) + status_layout.addWidget(self.saturation_label) + status_layout.addWidget(QLabel(" | ")) + status_layout.addWidget(self.samples_label) + status_layout.addWidget(QLabel(" | ")) + status_layout.addWidget(self.plotter_latency_label) + status_layout.addWidget(QLabel(" | ")) + status_layout.addWidget(self.rate_label) + status_layout.addWidget(QLabel(" | ")) + status_layout.addWidget(self.acq_status_label) + status_layout.addStretch() + layout.addLayout(status_layout) + + # Plot widget + self.plot_widget = pg.PlotWidget() + self.plot_widget.setLabel("left", "Voltage", "mV") + self.plot_widget.setLabel("bottom", "Time", "s") + self.plot_widget.showGrid(x=True, y=True) + self.plot_widget.setXRange(0, self.display_window_seconds, padding=0) + + # Plot curve + self.curve = self.plot_widget.plot(pen="y", width=1) + + layout.addWidget(self.plot_widget) + + # Performance optimization + self.plot_widget.setDownsampling(mode="peak") + self.plot_widget.setClipToView(True) + + def check_file_exists(self) -> None: + """Checks if the HDF5 file exists and attempts to read metadata.""" + try: + with h5py.File(self.hdf5_path, "r") as f: + if "adc_counts" in f: + self.acq_status_label.setText( + 'Reading metadata...' + ) + self.read_metadata(f) + else: + self.acq_status_label.setText( + 'Waiting for data...' + ) + except (FileNotFoundError, OSError): + self.acq_status_label.setText( + 'Waiting for file...' + ) + + def read_metadata(self, hdf5_file: h5py.File) -> None: + """Reads metadata attributes from the root of an open HDF5 file. + + Args: + hdf5_file: An open h5py.File object. + """ + try: + # Metadata is stored as root-level attributes + base_sample_interval_ns = hdf5_file.attrs["sample_interval_ns"] + self.hardware_downsample_ratio = hdf5_file.attrs.get( + "hardware_downsample_ratio", 1 + ) + self.sample_interval_ns = ( + base_sample_interval_ns * self.hardware_downsample_ratio + ) + + self.voltage_range_v = hdf5_file.attrs["voltage_range_v"] + self.max_adc_val = hdf5_file.attrs["max_adc"] + self.downsample_mode = hdf5_file.attrs.get("downsample_mode", "average") + self.analog_offset_v = hdf5_file.attrs.get("analog_offset_v", 0.0) + + # Update rate label with configured sample rate + configured_rate_sps = 1e9 / self.sample_interval_ns + self.rate_label.setText( + f"Rate: ... : {self._format_rate_sps(configured_rate_sps)}" + ) + except KeyError: + logger.debug("Metadata not fully available yet. Will retry.") + + def _update_heartbeat(self) -> None: + """Update UI heartbeat to show the UI thread is alive.""" + self.heartbeat_index = (self.heartbeat_index + 1) % len(self.heartbeat_chars) + self.heartbeat_label.setText( + f"UI: {self.heartbeat_chars[self.heartbeat_index]}" + ) + + def _handle_new_data( + self, dataset: h5py.Dataset, start_index: int, current_size: int + ) -> None: + """Process a new window of data.""" + self.data_change_count += 1 + self.last_displayed_size = current_size + self.last_data_timestamp = time.time() + self.acq_status_label.setText('Active') + + # Read only the most recent data window + data_window = dataset[start_index:current_size] + self.file_read_count += 1 + + # Check for ADC saturation + # The Picoscope driver scales data to 16-bit, so saturation occurs at the 16-bit limit. + FIXED_MAX_ADC = 32767 + self.is_saturated = np.any(data_window >= FIXED_MAX_ADC) or np.any( + data_window <= -FIXED_MAX_ADC + ) + + logger.debug( + f"Update {self.update_count}: Reading window of {len(data_window):,} samples from index {start_index:,}" + ) + + # Update the display with this complete window (only when data changes) + self.update_display(data_window) + + def _handle_stale_data(self) -> None: + """Handle a file check where no new data is found.""" + self.stale_update_count += 1 + self.acq_status_label.setText( + 'Acquiring... ' + ) + # Log if we're frequently updating with no new data + if self.stale_update_count % 10 == 0: + logger.debug( + f"File check #{self.update_count} with no new data (stale checks: {self.stale_update_count})" + ) + + def _update_status_labels(self, current_size: int) -> None: + """Update the various status labels in the UI.""" + # Update samples label + samples_text = self.format_sample_count(current_size) + self.samples_label.setText(f"Samples: {samples_text}") + + # Color-code latency + latency_color = ( + "green" + if self.display_latency_ms < 100 + else "orange" + if self.display_latency_ms < 500 + else "red" + ) + self.plotter_latency_label.setText( + f'Plotter Latency: {self.display_latency_ms:.0f}ms' + ) + + # Error counter + total_errors = self.conversion_error_count + self.file_error_count + error_color = ( + "green" if total_errors == 0 else "orange" if total_errors < 10 else "red" + ) + self.error_label.setText( + f'Errors: {total_errors}' + ) + + # Saturation status + if self.voltage_range_v is None: + self.saturation_label.setText("Saturation: -") + elif self.is_saturated: + self.saturation_label.setText( + 'Saturation: CLIPPING' + ) + else: + self.saturation_label.setText( + 'Saturation: OK' + ) + + def _update_rate_label(self, current_size: int) -> None: + """Check and update acquisition rate status.""" + if not self.rate_check_start_time: + return + + elapsed_time = time.perf_counter() - self.rate_check_start_time + if elapsed_time > 1.0: # Check only after 1s for stability + points_per_timestep = 2 if self.downsample_mode == "aggregate" else 1 + samples_acquired = current_size - self.rate_check_start_samples + timesteps_acquired = samples_acquired / points_per_timestep + actual_rate_sps = timesteps_acquired / elapsed_time + + configured_rate_sps = 1e9 / self.sample_interval_ns + rate_ratio = actual_rate_sps / configured_rate_sps + + configured_rate_str = self._format_rate_sps(configured_rate_sps) + actual_rate_str = self._format_rate_sps(actual_rate_sps) + + rate_text = f"Rate: {actual_rate_str} : {configured_rate_str}" + if rate_ratio < 0.95: + self.rate_label.setText(f'{rate_text}') + else: + self.rate_label.setText(rate_text) + + def _process_data_from_file(self, f: h5py.File) -> None: + """Read and process data from an open HDF5 file.""" + if "adc_counts" not in f: + return + + dataset = f["adc_counts"] + current_size = dataset.shape[0] + + if current_size == 0: + return + + # Start the rate check timer on the first data point + if self.rate_check_start_time is None: + self.rate_check_start_time = time.perf_counter() + self.rate_check_start_samples = current_size + + # Read metadata if not already done + if self.voltage_range_v is None: + self.read_metadata(f) + + # Dynamically calculate the number of timesteps for the display window + display_window_timesteps = int( + self.display_window_seconds / (self.sample_interval_ns * 1e-9) + ) + + # In aggregate mode, each timestep has two points (min/max) + display_window_points = display_window_timesteps + if self.downsample_mode == "aggregate": + display_window_points *= 2 + + # Calculate where to start reading to get the last window of points + start_index = max(0, current_size - display_window_points) + self.data_start_sample = start_index + + # Track data freshness and changes + if current_size > self.last_displayed_size: + self._handle_new_data(dataset, start_index, current_size) + else: + self._handle_stale_data() + + self._update_status_labels(current_size) + self._update_rate_label(current_size) + + def update_from_file(self) -> None: + """Timer-driven function to read data from the HDF5 file and update the plot.""" + self.update_count += 1 + self._update_heartbeat() + + try: + with h5py.File(self.hdf5_path, "r") as f: + self._process_data_from_file(f) + except (FileNotFoundError, OSError): + self.acq_status_label.setText( + 'Waiting for file...' + ) + except Exception as e: + self.file_error_count += 1 + logger.error(f"Update {self.update_count}: Error reading file - {e}") + self.acq_status_label.setText('File error!') + + def update_display(self, data_window: np.ndarray) -> None: + """Processes and displays a new window of data. + + This involves decimation, voltage conversion, and updating the plot curve. + + Args: + data_window: A NumPy array containing the raw ADC counts for display. + """ + if len(data_window) == 0: + return + + self.display_data = data_window + self.display_update_count += 1 + + logger.debug( + f"Display update {self.display_update_count}: " + f"Displaying window of {len(self.display_data):,} samples, " + f"starting at sample {self.data_start_sample:,}" + ) + + # Apply Numba-optimized decimation for display + if self.decimation_factor > 1: + decimated_data = min_max_decimate_numba( + self.display_data, self.decimation_factor + ) + else: + decimated_data = self.display_data + + # Debug: Log ADC values and metadata + logger.debug(f"ADC range: {decimated_data.min()} to {decimated_data.max()}") + logger.debug(f"voltage_range_v: {self.voltage_range_v}") + + # Convert to voltage if we have calibration data + if self.voltage_range_v is not None and self.max_adc_val is not None: + try: + voltage_data = adc_to_mV( + decimated_data, self.voltage_range_v, self.max_adc_val + ) + if self.analog_offset_v != 0.0: + voltage_data += self.analog_offset_v * 1000 + logger.debug( + f"Voltage conversion successful, range: {voltage_data.min():.1f} to {voltage_data.max():.1f} mV" + ) + except Exception as e: + self.conversion_error_count += 1 + logger.warning(f"Voltage conversion failed: {e}, using raw ADC values") + voltage_data = decimated_data.astype(float) + else: + logger.warning( + "Missing calibration data (voltage_range_v or max_adc_val), using raw ADC values" + ) + voltage_data = decimated_data.astype(float) + + # Create time axis for the current window + time_axis = self.create_time_axis(len(voltage_data)) + + logger.debug( + f"Display update {self.display_update_count}: " + f"Decimated to {len(voltage_data):,} points, " + f"time range: {time_axis[0]:.3f}s to {time_axis[-1]:.3f}s" + ) + + # Calculate display latency + if self.last_data_timestamp: + self.display_latency_ms = (time.time() - self.last_data_timestamp) * 1000 + + # Update plot + self.curve.setData(time_axis, voltage_data) + + # Update the X-axis range to match the new time axis, creating a "snapshot" effect. + self.plot_widget.setXRange(time_axis[0], time_axis[-1], padding=0) + + # Auto-scale the Y-axis occasionally. + # TODO put to larger number and allow user to update with key press + if self.display_update_count % 5 == 1: + self.plot_widget.enableAutoRange(axis="y") + + def _format_rate_sps(self, rate_sps: float) -> str: + """Formats a sample rate in Samples/sec into a human-readable string.""" + if rate_sps >= 1e9: + return f"{rate_sps / 1e9:.2f} GS/s" + if rate_sps >= 1e6: + return f"{rate_sps / 1e6:.2f} MS/s" + if rate_sps >= 1e3: + return f"{rate_sps / 1e3:.2f} kS/s" + return f"{rate_sps:.2f} S/s" + + def format_sample_count(self, count: int) -> str: + """Formats a large integer count into a human-readable string with units. + + Args: + count: The integer number to format. + + Returns: + A formatted string (e.g., "1.23M", "2.34G"). + """ + if count >= 1_000_000_000: + return f"{count / 1_000_000_000:.2f}G" + if count >= 1_000_000: + return f"{count / 1_000_000:.2f}M" + if count >= 1_000: + return f"{count / 1_000:.2f}K" + else: + return str(count) + + def create_time_axis(self, n_samples: int) -> np.ndarray: + """Creates a time axis for the displayed data window. + + The time axis is absolute, based on the data window's start position in + the overall acquisition. It accounts for the `aggregate` downsample mode, + where the data stream consists of interleaved min/max pairs. + + For min-max decimated data, it generates pairs of time coordinates to + draw vertical lines for each min-max pair. For non-decimated data, it + generates a linearly spaced time axis. + + Args: + n_samples: The number of points for the time axis. This should be + the number of points *after* decimation. + + Returns: + A NumPy array representing the time axis in seconds. + """ + if n_samples == 0: + return np.array([]) + + time_per_timestep = self.sample_interval_ns * 1e-9 + points_per_timestep = 2 if self.downsample_mode == "aggregate" else 1 + time_per_point = time_per_timestep / points_per_timestep + + start_time = (self.data_start_sample / points_per_timestep) * time_per_timestep + + if self.decimation_factor > 1: + # For min-max, create pairs of time points for vertical lines + num_pairs = n_samples // 2 + time_step_between_groups = self.decimation_factor * time_per_point + group_times = start_time + np.arange(num_pairs) * time_step_between_groups + return np.repeat(group_times, 2) + else: + # For non-decimated data + if self.downsample_mode == "aggregate": + # Data is already min/max pairs from hardware. Create vertical lines. + num_pairs = n_samples // 2 + time_step_between_pairs = time_per_timestep + pair_times = start_time + np.arange(num_pairs) * time_step_between_pairs + return np.repeat(pair_times, 2) + else: + # For linear (non-aggregate) data, create a simple time axis + duration = ( + (n_samples - 1) * time_per_point if n_samples > 1 else 0 + ) + end_time = start_time + duration + return np.linspace(start_time, end_time, n_samples) + + def closeEvent(self, event: QCloseEvent) -> None: + """Handles the window close event. + + Stops the plot's internal timer and allows the Qt event loop to exit. + The main application will handle the graceful shutdown. + """ + logger.info("Close event received. Stopping timer.") + self.timer.stop() + event.accept() + + def keyPressEvent(self, event: QKeyEvent) -> None: + """Handles key presses for application control (e.g., 'Q' to quit).""" + if event.key() == Qt.Key_Q: + logger.info("'Q' key pressed. Closing application.") + self.close() + else: + super().keyPressEvent(event) + + +def main() -> None: + """Standalone HDF5 live plotter.""" + # Create the QApplication instance FIRST. + app = QApplication(sys.argv) + + parser = argparse.ArgumentParser(description="Standalone HDF5 live plotter.") + parser.add_argument("hdf5_path", type=str, help="Path to the HDF5 file.") + parser.add_argument( + "--window", + type=float, + default=0.5, + help="Display window in seconds. [default: 0.5]", + ) + parser.add_argument( + "--decimation", + type=int, + default=150, + help="Decimation factor for plotting. [default: 150]", + ) + args = parser.parse_args() + + logger.info("Plotter process starting") + try: + plotter = HDF5LivePlotter( + hdf5_path=args.hdf5_path, + display_window_seconds=args.window, + decimation_factor=args.decimation, + ) + plotter.show() + sys.exit(app.exec_()) + except Exception as e: + logger.error(f"Error in plotter process: {e}") + + +if __name__ == "__main__": + main() diff --git a/picostream/main.py b/picostream/main.py new file mode 100644 index 0000000..44a0c0c --- /dev/null +++ b/picostream/main.py @@ -0,0 +1,562 @@ +from __future__ import annotations + +import queue +import signal +import sys +import threading +import time +from datetime import datetime +from typing import TYPE_CHECKING, List, Optional + +if TYPE_CHECKING: + from PyQt5.QtWidgets import QApplication + +import click +import h5py +import numpy as np +from loguru import logger + +from .consumer import Consumer +from .pico import PicoDevice + + +class Streamer: + """Orchestrates the Picoscope data acquisition process. + + This class initializes the Picoscope device (producer), the HDF5 writer + (consumer), and the live plotter. It manages the threads, queues, and + graceful shutdown of the entire application. + """ + + def __init__( + self, + sample_rate_msps: float = 62.5, + resolution_bits: int = 12, + channel_range_str: str = "PS5000A_20V", + enable_live_plot: bool = False, + output_file: str = "./output.hdf5", + debug: bool = False, + plot_window_s: float = 0.5, + plot_points: int = 4000, + hardware_downsample: int = 1, + downsample_mode: str = "average", + offset_v: float = 0.0, + ) -> None: + # --- Configuration --- + self.output_file = output_file + self.debug = debug + self.enable_live_plot = enable_live_plot + self.plot_window_s = plot_window_s + + ( + sample_rate_msps, + pico_downsample_ratio, + pico_ratio_mode, + offset_v, + ) = self._validate_config( + resolution_bits, + sample_rate_msps, + channel_range_str, + hardware_downsample, + downsample_mode, + offset_v, + ) + # Dynamically size buffers to hold a specific duration of data. This makes + # memory usage proportional to the data rate, providing a consistent + # time-based buffer to handle processing latencies. + effective_rate_sps = (sample_rate_msps * 1e6) / pico_downsample_ratio + + # Consumer buffers (for writing to HDF5) are sized to hold 1 second of data. + # This is a good balance, as larger buffers lead to more efficient disk writes + # but use more RAM. + consumer_buffer_duration_s = 1.0 + self.consumer_buffer_size = int( + effective_rate_sps * consumer_buffer_duration_s + ) + if downsample_mode == "aggregate": + self.consumer_buffer_size *= 2 + self.consumer_num_buffers = 5 # A pool of 5 buffers + + # The Picoscope driver buffer is sized to hold 0.5 seconds of data. This + # buffer receives data directly from the hardware. A smaller size ensures + # that the application receives data in timely chunks, reducing latency. + driver_buffer_duration_s = 0.5 + self.pico_driver_buffer_size = int( + effective_rate_sps * driver_buffer_duration_s + ) + self.pico_driver_num_buffers = ( + 1 # A single large buffer is efficient for the driver + ) + + logger.info( + f"Consumer buffer sized to {self.consumer_buffer_size:,} samples " + f"({consumer_buffer_duration_s}s at effective rate)" + ) + logger.info( + f"Pico driver buffer sized to {self.pico_driver_buffer_size:,} samples " + f"({driver_buffer_duration_s}s at effective rate)" + ) + + # --- Plotting Decimation --- + # Calculate the decimation factor needed to achieve the target number of plot points. + points_per_timestep = 2 if downsample_mode == "aggregate" else 1 + samples_in_window = effective_rate_sps * plot_window_s * points_per_timestep + self.decimation_factor = max(1, int(samples_in_window / plot_points)) + logger.info( + f"Plotting with target of {plot_points} points. " + f"Calculated decimation factor: {self.decimation_factor}" + ) + + # Picoscope hardware settings + self.pico_resolution = f"PS5000A_DR_{resolution_bits}BIT" + self.pico_channel_range = channel_range_str + self.pico_sample_interval_ns = int(1000 / sample_rate_msps) + self.pico_sample_unit = "PS5000A_NS" + + # Streaming settings + self.pico_auto_stop = 0 # Don't auto stop + self.pico_auto_stop_stream = False + # --- End Configuration --- + + # --- System Components --- + self.shutdown_event: threading.Event = threading.Event() + data_queue: queue.Queue[int] = queue.Queue() + empty_queue: queue.Queue[int] = queue.Queue() + data_buffers: List[np.ndarray] = [] + + # Pre-allocate a pool of numpy arrays for data transfer and populate the + # empty_queue with their indices. + for idx in range(self.consumer_num_buffers): + data_buffers.append(np.empty((self.consumer_buffer_size,), dtype="int16")) + empty_queue.put(idx) + + # --- Producer --- + self.pico_device: PicoDevice = PicoDevice( + 0, # handle + self.pico_resolution, + self.pico_driver_buffer_size, + self.pico_driver_num_buffers, + self.consumer_buffer_size, + data_queue, + empty_queue, + data_buffers, + self.shutdown_event, + downsample_mode=downsample_mode, + ) + + self.pico_device.set_channel( + "PS5000A_CHANNEL_A", 1, "PS5000A_DC", self.pico_channel_range, offset_v + ) + self.pico_device.set_channel( + "PS5000A_CHANNEL_B", 0, "PS5000A_DC", self.pico_channel_range, 0.0 + ) + self.pico_device.set_data_buffer("PS5000A_CHANNEL_A", 0, pico_ratio_mode) + self.pico_device.configure_streaming_var( + self.pico_sample_interval_ns, + self.pico_sample_unit, + 0, # pre-trigger samples + pico_downsample_ratio, + pico_ratio_mode, + self.pico_auto_stop, + self.pico_auto_stop_stream, + ) + + # Run streaming once to get the actual sample interval from the driver + self.pico_device.run_streaming() + + # --- Consumer --- + # Get metadata from configured device and pass to consumer + metadata = self.pico_device.get_metadata() + self.consumer: Consumer = Consumer( + self.consumer_buffer_size, + data_queue, + empty_queue, + data_buffers, + output_file, + self.shutdown_event, + metadata=metadata, + ) + + # --- Threads --- + self.consumer_thread: threading.Thread = threading.Thread( + target=self.consumer.consume + ) + self.pico_thread: threading.Thread = threading.Thread( + target=self.pico_device.run_capture + ) + + # --- Signal Handling --- + # Only set the signal handler if not in GUI mode. + # In GUI mode, the main function will handle signals to quit the Qt app. + if not self.enable_live_plot: + signal.signal(signal.SIGINT, self.signal_handler) + + # --- Live Plotting (optional) --- + self.start_time: Optional[float] = None + + def _validate_config( + self, + resolution_bits: int, + sample_rate_msps: float, + channel_range_str: str, + hardware_downsample: int, + downsample_mode: str, + offset_v: float, + ) -> tuple[float, int, str, float]: + """Validates user-provided settings and returns derived configuration.""" + if resolution_bits == 8: + max_rate_msps = 125.0 + elif resolution_bits in [12, 14, 15, 16]: + max_rate_msps = 62.5 + else: + raise ValueError( + f"Unsupported resolution: {resolution_bits} bits. Must be one of 8, 12, 14, 15, 16." + ) + + if sample_rate_msps <= 0: + sample_rate_msps = max_rate_msps + logger.info(f"Max sample rate requested. Setting to {max_rate_msps} MS/s.") + + if sample_rate_msps > max_rate_msps: + raise ValueError( + f"Sample rate {sample_rate_msps} MS/s exceeds maximum of {max_rate_msps} MS/s for {resolution_bits}-bit resolution." + ) + + # Check if sample rate is excessive for the analog bandwidth. + # Bandwidth is dependent on both resolution and voltage range. + # (Based on PicoScope 5000A/B Series datasheet) + inv_voltage_map = {v: k for k, v in VOLTAGE_RANGE_MAP.items()} + voltage_v = inv_voltage_map.get(channel_range_str, 0) + + if resolution_bits == 16: + bandwidth_mhz = 20 # 20 MHz for all ranges + elif resolution_bits == 15: + # Bandwidth is 70MHz for < ±5V, 60MHz for >= ±5V + bandwidth_mhz = 70 if voltage_v < 5.0 else 60 + else: # 8-14 bits + # Bandwidth is 100MHz for < ±5V, 60MHz for >= ±5V + bandwidth_mhz = 100 if voltage_v < 5.0 else 60 + + # Nyquist rate is 2x bandwidth. A common rule of thumb is 3-5x. + # Warn if sampling faster than 5x the analog bandwidth. + if sample_rate_msps > 5 * bandwidth_mhz: + logger.warning( + f"Sample rate ({sample_rate_msps} MS/s) may be unnecessarily high " + f"for the selected voltage range ({channel_range_str}), which has an " + f"analog bandwidth of {bandwidth_mhz} MHz." + ) + + if downsample_mode == "aggregate" and hardware_downsample <= 1: + raise ValueError( + "Hardware downsample ratio must be > 1 for 'aggregate' mode." + ) + + if hardware_downsample > 1: + pico_downsample_ratio = hardware_downsample + pico_ratio_mode = f"PS5000A_RATIO_MODE_{downsample_mode.upper()}" + logger.info( + f"Hardware down-sampling ({downsample_mode}) enabled " + + f"with ratio {pico_downsample_ratio}." + ) + else: + pico_downsample_ratio = 1 + pico_ratio_mode = "PS5000A_RATIO_MODE_NONE" + + # Validate analog offset + if offset_v != 0.0: + if voltage_v >= 5.0: + raise ValueError( + f"Analog offset is not supported for voltage ranges >= 5V (selected: {channel_range_str})." + ) + if abs(offset_v) > voltage_v: + raise ValueError( + f"Analog offset ({offset_v}V) exceeds the selected voltage range (±{voltage_v}V)." + ) + logger.info(f"Analog offset set to {offset_v:.3f}V.") + + return sample_rate_msps, pico_downsample_ratio, pico_ratio_mode, offset_v + + def signal_handler(self, _sig: int, frame: Optional[object]) -> None: + """Handles Ctrl+C interrupts to initiate a graceful shutdown.""" + logger.warning("Ctrl+C detected. Shutting down.") + self.shutdown() + + def shutdown(self) -> None: + """Performs a graceful shutdown of all components. + + This method calculates final statistics, stops all threads, closes the + plotter, and ensures the Picoscope device is properly closed. + """ + if self.shutdown_event.is_set(): + return + + self._log_acquisition_summary() + self.shutdown_event.set() + + logger.info("Stopping data acquisition and saving...") + + self._join_threads() + self.pico_device.close_device() + + logger.success("Shutdown complete.") + + def _log_acquisition_summary(self) -> None: + """Calculates and logs final acquisition statistics.""" + if not self.start_time: + return + + end_time = time.time() + duration = end_time - self.start_time + total_samples = self.consumer.values_written + effective_rate_msps = (total_samples / duration) / 1e6 if duration > 0 else 0 + configured_rate_msps = 1e3 / self.pico_device.sample_int.value + + logger.info("--- Acquisition Summary ---") + logger.info(f"Total acquisition time: {duration:.2f} s") + logger.info( + "Total samples written: " + + f"{self.consumer.format_sample_count(total_samples)}" + ) + logger.info(f"Configured sample rate: {configured_rate_msps:.2f} MS/s") + logger.info(f"Effective average rate: {effective_rate_msps:.2f} MS/s") + + rate_ratio = ( + effective_rate_msps / configured_rate_msps + if configured_rate_msps > 0 + else 0 + ) + if rate_ratio < 0.95: + logger.warning( + f"Effective rate was only {rate_ratio:.1%} " + "of the configured rate." + ) + else: + logger.success("Effective rate matches configured rate.") + logger.info("--------------------------") + + def _join_threads(self) -> None: + """Waits for the producer and consumer threads to terminate.""" + for thread_name in ["pico_thread", "consumer_thread"]: + thread = getattr(self, thread_name, None) + if thread and thread.is_alive(): + logger.info(f"Waiting for {thread_name} to terminate...") + thread.join(timeout=2.0) + if thread.is_alive(): + logger.critical(f"{thread_name} failed to terminate.") + + def run(self, app: Optional[QApplication] = None) -> None: + """Starts the acquisition threads and optionally the Qt event loop.""" + # Start acquisition threads + self.start_time = time.time() + self.consumer_thread.start() + self.pico_thread.start() + + # Handle Qt event loop if plotting is enabled + if self.enable_live_plot and app: + from .dfplot import HDF5LivePlotter + + plotter = HDF5LivePlotter( + hdf5_path=self.output_file, + display_window_seconds=self.plot_window_s, + decimation_factor=self.decimation_factor, + shutdown_event=self.shutdown_event, + ) + plotter.show() + + # Run the Qt event loop. This will block until the plot window is closed. + app.exec_() + + # Once the window is closed, the shutdown event should have been set. + # We call shutdown() to ensure threads are joined and cleanup happens. + self.shutdown() + else: + # Original non-GUI behavior + self.consumer_thread.join() + self.pico_thread.join() + logger.success("Acquisition complete!") + + +# --- Argument Parsing --- +VOLTAGE_RANGE_MAP = { + 0.01: "PS5000A_10MV", + 0.02: "PS5000A_20MV", + 0.05: "PS5000A_50MV", + 0.1: "PS5000A_100MV", + 0.2: "PS5000A_200MV", + 0.5: "PS5000A_500MV", + 1: "PS5000A_1V", + 2: "PS5000A_2V", + 5: "PS5000A_5V", + 10: "PS5000A_10V", + 20: "PS5000A_20V", +} + + +@click.command() +@click.option( + "--sample-rate", + "-s", + type=float, + default=20, + help="Sample rate in MS/s (e.g., 62.5). Use 0 for max rate. [default: 20]", +) +@click.option( + "--resolution", + "-b", + type=click.Choice(["8", "12", "16"]), + default="12", + help="Resolution in bits. [default: 12]", +) +@click.option( + "--rangev", + "-r", + type=click.Choice([str(k) for k in sorted(VOLTAGE_RANGE_MAP.keys())]), + default="20", + help=f"Voltage range in Volts. [default: 20]", +) +@click.option( + "--plot/--no-plot", + "-p", + is_flag=True, + default=True, + help="Enable/disable live plotting. [default: --plot]", +) +@click.option( + "--output", + "-o", + type=click.Path(dir_okay=False, writable=True), + help="Output HDF5 file (default: auto-timestamped).", +) +@click.option( + "--plot-window", + "-w", + type=float, + default=0.5, + help="Live plot display window duration in seconds. [default: 0.5]", +) +@click.option( + "--verbose", "-v", is_flag=True, default=False, help="Enable debug logging." +) +@click.option( + "--plot-npts", + "-n", + type=int, + default=4000, + help="Target number of points for the plot window. [default: 4000]", +) +@click.option( + "--hardware-downsample", + "-h", + type=int, + default=1, + help="Hardware down-sampling ratio (power of 2 for 'average' mode). [default: 1]", +) +@click.option( + "--downsample-mode", + "-m", + type=click.Choice(["average", "aggregate"]), + default="average", + help="Hardware down-sampling mode. [default: average]", +) +@click.option( + "--offset", + type=float, + default=0.0, + help="Analog offset in Volts (only for ranges < 5V). [default: 0.0]", +) +def main( + sample_rate: float, + resolution: str, + rangev: str, + plot: bool, + output: Optional[str], + plot_window: float, + verbose: bool, + plot_npts: int, + hardware_downsample: int, + downsample_mode: str, + offset: float, +) -> None: + """High-speed data acquisition tool for Picoscope 5000a series.""" + # --- Argument Validation and Processing --- + channel_range_str = VOLTAGE_RANGE_MAP[float(rangev)] + resolution_bits = int(resolution) + + app: Optional[QApplication] = None + if plot: + from PyQt5.QtWidgets import QApplication + + app = QApplication(sys.argv) + + # When plotting, SIGINT should gracefully close the Qt application. + # The main loop will then handle the shutdown. + def sigint_handler(_sig: int, _frame: Optional[object]) -> None: + logger.warning("Ctrl+C detected. Closing application.") + QApplication.quit() + + signal.signal(signal.SIGINT, sigint_handler) + + # Configure logging + logger.remove() + log_level = "DEBUG" if verbose else "INFO" + logger.add(sys.stderr, level=log_level) + logger.info(f"Logging configured at level: {log_level}") + + # Auto-generate filename if not specified + if not output: + timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") + output = f"./output_{timestamp}.hdf5" + + logger.info(f"Output file: {output}") + logger.info(f"Selected voltage range: {rangev}V -> {channel_range_str}") + + try: + # Create and run the streamer + streamer = Streamer( + sample_rate_msps=sample_rate, + resolution_bits=resolution_bits, + channel_range_str=channel_range_str, + enable_live_plot=plot, + output_file=output, + debug=verbose, + plot_window_s=plot_window, + plot_points=plot_npts, + hardware_downsample=hardware_downsample, + downsample_mode=downsample_mode, + offset_v=offset, + ) + streamer.run(app) + except RuntimeError as e: + if "PICO_NOT_FOUND" in str(e): + logger.critical( + "Picoscope device not found. Please check connection and ensure no other software is using it." + ) + else: + logger.critical(f"Failed to initialize Picoscope: {e}") + sys.exit(1) + + # --- Verification Step --- + logger.info(f"Verifying output file: {output}") + try: + expected_samples = streamer.consumer.values_written + if expected_samples == 0: + logger.warning("Consumer processed no samples. Nothing to verify.") + else: + with h5py.File(output, "r") as f: + if "adc_counts" not in f: + raise ValueError("Dataset 'adc_counts' not found in HDF5 file.") + + actual_samples = len(f["adc_counts"]) + if actual_samples == expected_samples: + logger.success( + f"Verification PASSED: File contains {actual_samples} samples, as expected." + ) + else: + logger.error( + f"Verification FAILED: Expected {expected_samples} samples, but file has {actual_samples}." + ) + except Exception as e: + logger.error(f"HDF5 file verification failed: {e}") + + +if __name__ == "__main__": + main() diff --git a/picostream/pico.py b/picostream/pico.py new file mode 100644 index 0000000..4ec0f2c --- /dev/null +++ b/picostream/pico.py @@ -0,0 +1,495 @@ +from __future__ import annotations + +import ctypes +import queue +import threading +import time +from typing import Any, Dict, List, Optional + +import numpy as np +from loguru import logger + +from picosdk.functions import PICO_STATUS +from picosdk.errors import CannotFindPicoSDKError +try: + from picosdk.ps5000a import ps5000a as ps +except CannotFindPicoSDKError: + logger.critical("PICOSDK IMPORT FAILED: CANNOT FIND SDK LIB - download from pico website") + + + +def check_status(status: int, function_name: str) -> None: + """Check the status returned by a Picoscope SDK call and raise on error. + + Args: + status: The status code returned by the SDK function. + function_name: The name of the function that was called. + + Raises: + Exception: If the status is not PICO_OK. + """ + if status != PICO_STATUS["PICO_OK"]: + # Find the string name of the error code + error_name = next( + (k for k, v in PICO_STATUS.items() if v == status), "PICO_UNKNOWN_ERROR" + ) + raise RuntimeError( + f"{function_name} failed with status {status} ({error_name})" + ) + + +class PicoDevice: + """A class to manage a Picoscope 5000a series device for data streaming. + + This class handles device configuration, buffer management, and the data + capture loop. It acts as the "producer" in a producer-consumer pattern. + + Data Formats: + - average mode: Single stream of averaged ADC values + - aggregate mode: Interleaved stream [min1, max1, min2, max2, ...] + where each pair represents one downsampled timestep + + Buffer Management: + - SDK buffers: Direct hardware interface (bufferA, bufferB for aggregate) + - Application buffers: Larger buffers for efficient file writing + - Interleaved buffer: Temporary buffer for aggregate mode processing + """ + + def __init__( + self, + handle: int, + resolution: str, + pico_buffer_size: int, + pico_num_buffers: int, + comp_buffer_size: int, + data_queue: queue.Queue[int], + empty_queue: queue.Queue[int], + data_buffers: List[np.ndarray], + shutdown_event: threading.Event, + downsample_mode: str = "average", + ) -> None: + """Initializes the PicoDevice and opens a connection to the hardware. + + Args: + handle: The device handle provided by the SDK. + resolution: The desired resolution, e.g., "PS5000A_DR_16BIT". + pico_buffer_size: The size of each buffer allocated within the SDK. + pico_num_buffers: The number of buffers for the SDK to use. + comp_buffer_size: The size of the application-side buffers for writing to disk. + data_queue: Queue to send indices of full buffers to the consumer. + empty_queue: Queue to receive indices of empty buffers from the consumer. + data_buffers: A list of pre-allocated numpy arrays for data transfer. + shutdown_event: A threading.Event to signal shutdown. + """ + # --- Device and Resolution --- + self.handle: ctypes.c_int16 = ctypes.c_int16(handle) + self.resolution: str = resolution + res_enum = ps.PS5000A_DEVICE_RESOLUTION[resolution] + + # --- Picoscope SDK Buffer Configuration --- + self.pico_buffer_size: int = pico_buffer_size + self.pico_num_buffers: int = pico_num_buffers + self.total_samples: int = self.pico_buffer_size * self.pico_num_buffers + + # --- Application Buffer (for file writing) --- + self.comp_buffer_size: int = comp_buffer_size + + # --- Internal Data Buffer (receives data from SDK) --- + self.downsample_mode = downsample_mode + self.bufferA: np.ndarray = np.zeros(shape=self.pico_buffer_size, dtype=np.int16) + self.bufferB: Optional[np.ndarray] = None + self.interleaved_buffer: Optional[np.ndarray] = None + if self.downsample_mode == "aggregate": + self.bufferB = np.zeros(shape=self.pico_buffer_size, dtype=np.int16) + self.interleaved_buffer = np.zeros( + shape=self.pico_buffer_size * 2, dtype=np.int16 + ) + + # --- Ctypes and Callback --- + self.callbackFuncPtr = ps.StreamingReadyType(self.streaming_callback) + self.max_adc: ctypes.c_int16 = ctypes.c_int16() + + # --- Channel Configuration --- + self.channel_range: Optional[int] = None + self.voltage_range_v: Optional[float] = None + self.channel_a_coupling: Optional[str] = None + self.analog_offset_v: float = 0.0 + self.channel_a_range_str: Optional[str] = None + + # --- Threading and Queues --- + self.shutdown_event: threading.Event = shutdown_event + self.data_queue: queue.Queue[int] = data_queue + self.empty_queue: queue.Queue[int] = empty_queue + self.data_buffers: List[np.ndarray] = data_buffers + + # --- Buffer Management State --- + self.buf_idx: int = self.empty_queue.get() + self.buf_used: int = 0 + self.buf_free: int = self.comp_buffer_size + + # --- Streaming Configuration --- + self.streaming_configured: bool = False + self.sample_int: Optional[ctypes.c_int32] = None + self.sample_unit: Optional[int] = None + self.ratio: Optional[int] = None + self.pre_trig_samples: Optional[int] = None + self.down_sample_ratio: Optional[int] = None + self.auto_stop: Optional[int] = None + self.auto_stop_stream: Optional[int] = None + + # --- Status and Performance Metrics --- + self.captured_samples: int = 0 + self.empty_pro_queue_count: int = 0 + self.overvoltage_count: int = 0 + self.hardware_buffer_overflow_count: int = 0 + self.callback_durations: List[float] = [] + + # --- Aggregate Mode Performance Tracking --- + self.interleave_durations: List[float] = [] + + # --- Open device connection --- + status = ps.ps5000aOpenUnit(ctypes.byref(self.handle), None, res_enum) + check_status(status, "ps5000aOpenUnit") + + status = ps.ps5000aMaximumValue(self.handle, ctypes.byref(self.max_adc)) + check_status(status, "ps5000aMaximumValue") + + def set_channel( + self, chan: str, en: int, coup: str, voltage_range_str: str, offset: float + ) -> None: + """Configure a channel on the Picoscope. + + Args: + chan: The channel identifier string, e.g., "PS5000A_CHANNEL_A". + en: Whether the channel is enabled (1) or disabled (0). + coup: The coupling type string, e.g., "PS5000A_DC". + voltage_range_str: The voltage range string, e.g., "PS5000A_20V". + offset: The analog voltage offset in Volts. + """ + channel_range_enum = ps.PS5000A_RANGE[voltage_range_str] + self.channel_range = channel_range_enum + + # Store the actual voltage range for metadata and conversion + range_to_voltage = { + "PS5000A_10MV": 0.01, + "PS5000A_20MV": 0.02, + "PS5000A_50MV": 0.05, + "PS5000A_100MV": 0.1, + "PS5000A_200MV": 0.2, + "PS5000A_500MV": 0.5, + "PS5000A_1V": 1.0, + "PS5000A_2V": 2.0, + "PS5000A_5V": 5.0, + "PS5000A_10V": 10.0, + "PS5000A_20V": 20.0, + } + self.voltage_range_v = range_to_voltage.get(voltage_range_str) + + if chan == "PS5000A_CHANNEL_A" and en: + self.channel_a_coupling = coup + self.channel_a_range_str = voltage_range_str + self.analog_offset_v = offset + + channel_enum = ps.PS5000A_CHANNEL[chan] + coupling_enum = ps.PS5000A_COUPLING[coup] + status = ps.ps5000aSetChannel( + self.handle, channel_enum, en, coupling_enum, channel_range_enum, offset + ) + check_status(status, f"ps5000aSetChannel ({chan})") + logger.debug( + f"Range '{voltage_range_str}' maps to enum value: {channel_range_enum}, voltage range: {self.voltage_range_v}V" + ) + + def set_data_buffer(self, chan: str, segment: int, rat: str) -> None: + """Set up the data buffer for a specific channel for streaming. + + Args: + chan: The channel identifier string, e.g., "PS5000A_CHANNEL_A". + segment: The memory segment to use (0 for streaming). + rat: The ratio mode string, e.g., "PS5000A_RATIO_MODE_NONE". + """ + channel_enum = ps.PS5000A_CHANNEL[chan] + ratio_enum = ps.PS5000A_RATIO_MODE[rat] + + buffer_min_ptr = None + if self.bufferB is not None: + buffer_min_ptr = self.bufferB.ctypes.data_as(ctypes.POINTER(ctypes.c_int16)) + + status = ps.ps5000aSetDataBuffers( + self.handle, + channel_enum, + self.bufferA.ctypes.data_as(ctypes.POINTER(ctypes.c_int16)), + buffer_min_ptr, + self.pico_buffer_size, + segment, + ratio_enum, + ) + check_status(status, f"ps5000aSetDataBuffers ({chan})") + + def configure_streaming_var( + self, + samp_int: int, + samp_unit: str, + pre_trig_samp: int, + down_samp_rat: int, + rat: str, + auto_stop: int, + auto_stop_stream: int, + ) -> None: + """Store streaming parameters before starting the capture. + + Args: + samp_int: The desired sample interval in `samp_unit` units. + samp_unit: The time unit string, e.g., "PS5000A_NS". + pre_trig_samp: The number of pre-trigger samples. + down_samp_rat: The downsampling ratio. + rat: The ratio mode string, e.g., "PS5000A_RATIO_MODE_NONE". + auto_stop: Whether to stop the capture automatically (1) or not (0). + auto_stop_stream: Deprecated, not used. + """ + self.sample_int = ctypes.c_int32(samp_int) + self.sample_unit = ps.PS5000A_TIME_UNITS[samp_unit] + self.ratio = ps.PS5000A_RATIO_MODE[rat] + self.pre_trig_samples = pre_trig_samp + self.down_sample_ratio = down_samp_rat + self.auto_stop = auto_stop + self.auto_stop_stream = auto_stop_stream + + def get_metadata(self) -> Dict[str, Any]: + """Return comprehensive acquisition metadata.""" + metadata = { + "resolution": self.resolution, + "sample_interval_ns": self.sample_int.value if self.sample_int else None, + "voltage_range_v": self.voltage_range_v, + "channel_a_coupling": self.channel_a_coupling, + "channel_a_range": self.channel_a_range_str, + "downsample_mode": self.downsample_mode, + "analog_offset_v": self.analog_offset_v, + "hardware_downsample_ratio": self.down_sample_ratio, + "max_adc": self.max_adc.value, + "data_format_version": "2.0", + } + + if self.downsample_mode == "aggregate": + metadata.update( + { + "aggregate_format": "interleaved_min_max", + "aggregate_description": "Data format: [min1, max1, min2, max2, ...]", + } + ) + + return metadata + + def run_streaming(self) -> None: + """Starts the Picoscope streaming capture.""" + status = ps.ps5000aRunStreaming( + self.handle, + ctypes.byref(self.sample_int), + self.sample_unit, + self.pre_trig_samples, + self.total_samples, + self.auto_stop, + self.down_sample_ratio, + self.ratio, + self.pico_buffer_size, + ) + check_status(status, "ps5000aRunStreaming") + self.streaming_configured = True + logger.info( + f"Streaming configured. Actual sample interval: {self.sample_int.value} ns" + ) + + def streaming_callback( + self, + _handle: int, + noOfSamples: int, + startIndex: int, + overvoltage_flags: int, + _triggerAt: int, + _triggered: int, + _autoStop: int, + _param: int, + ) -> None: + """Callback function executed by the SDK when new streaming data is available. + + This function is the heart of the producer. It copies data from the + Picoscope's internal buffer into the application's shared buffer pool. + When an application buffer is full, its index is placed on the data_queue + for the consumer. + + Note: This function is called from a thread created by the Picoscope SDK. + It must be fast and thread-safe. + """ + if overvoltage_flags: + self.overvoltage_count += 1 + logger.warning( + "Picoscope ADC over-range detected (saturation/clipping)." + ) + + # Stop processing if a shutdown is requested. + if self.shutdown_event.is_set(): + return + + callback_start_time = time.perf_counter() + if noOfSamples > 0: + self.captured_samples += noOfSamples + + source_buffer = self.bufferA + samples_to_process = noOfSamples + + # In aggregate mode, interleave the min/max buffers into one + if ( + self.downsample_mode == "aggregate" + and self.bufferB is not None + and self.interleaved_buffer is not None + ): + interleave_start = time.perf_counter() + + # The SDK provides min/max data in separate buffers (B/A). + # We interleave them into a single [min, max, min, max, ...] + # stream for the consumer. + total_interleaved_samples = noOfSamples * 2 + + # Use numpy's more efficient interleaving + np.stack( + [ + self.bufferB[startIndex : startIndex + noOfSamples], + self.bufferA[startIndex : startIndex + noOfSamples], + ], + axis=1, + out=self.interleaved_buffer[:total_interleaved_samples].reshape( + -1, 2 + ), + ) + + source_buffer = self.interleaved_buffer + samples_to_process = total_interleaved_samples + # After interleaving, the source index is always 0 + source_index = 0 + + # Track interleaving performance + self.interleave_durations.append( + (time.perf_counter() - interleave_start) * 1000 + ) + else: + source_index = startIndex + + # This loop copies data from the source_buffer into + # our larger, shared application buffers (self.data_buffers). + while samples_to_process > 0: + # Determine how much space is left in the current application buffer. + self.buf_free = self.comp_buffer_size - self.buf_used + copy_size = min(samples_to_process, self.buf_free) + + # Copy the data slice. + self.data_buffers[self.buf_idx][ + self.buf_used : self.buf_used + copy_size + ] = source_buffer[source_index : source_index + copy_size] + + # Update pointers and remaining sample counts. + self.buf_used += copy_size + samples_to_process -= copy_size + source_index += copy_size + + # If the current application buffer is full... + if self.buf_used == self.comp_buffer_size: + # ...send its index to the consumer. + self.data_queue.put(self.buf_idx) + try: + # ...and get a new empty buffer from the consumer. + self.buf_idx = self.empty_queue.get_nowait() + self.buf_used = 0 + except queue.Empty: + # This is a critical failure. The consumer is not keeping up. + self.empty_pro_queue_count += 1 + logger.critical( + "Producer queue is empty. Consumer cannot keep up. " + "Shutting down to prevent data loss." + ) + self.shutdown_event.set() + return # Exit immediately. + + duration_ms = (time.perf_counter() - callback_start_time) * 1000 + self.callback_durations.append(duration_ms) + + def run_capture(self) -> None: + """The main capture loop for the producer thread.""" + if not self.streaming_configured: + self.run_streaming() + + # This loop polls the SDK for new data, which triggers the callback. + while not self.shutdown_event.is_set(): + status = ps.ps5000aGetStreamingLatestValues( + self.handle, self.callbackFuncPtr, None + ) + + if status == PICO_STATUS["PICO_BUFFER_STALL"]: + self.hardware_buffer_overflow_count += 1 + logger.critical( + "Picoscope hardware buffer overflow occurred. Data was lost." + ) + elif status not in [ + PICO_STATUS["PICO_OK"], + PICO_STATUS["PICO_NO_SAMPLES_AVAILABLE"], + PICO_STATUS["PICO_BUSY"], + PICO_STATUS["PICO_DATA_NOT_AVAILABLE"], + PICO_STATUS["PICO_DRIVER_FUNCTION"], + ]: + check_status(status, "ps5000aGetStreamingLatestValues") + + # Yield the GIL to other threads. + time.sleep(0.001) + + # --- Shutdown and reporting --- + logger.info( + f"Producer couldn't obtain an empty queue {self.empty_pro_queue_count} times." + ) + if self.hardware_buffer_overflow_count > 0: + logger.critical( + f"Picoscope hardware buffer overflowed {self.hardware_buffer_overflow_count} times. " + "This indicates the application could not process data fast enough from the driver." + ) + if self.overvoltage_count > 0: + logger.warning( + f"Picoscope ADC over-ranged (clipped) {self.overvoltage_count} times." + ) + if self.callback_durations: + logger.info("--- Callback Performance ---") + logger.info(f"Total callbacks: {len(self.callback_durations)}") + logger.info(f"Min duration: {min(self.callback_durations):.2f} ms") + logger.info(f"Max duration: {max(self.callback_durations):.2f} ms") + logger.info(f"Avg duration: {np.mean(self.callback_durations):.2f} ms") + logger.info("--------------------------") + + # Report aggregate mode performance if applicable + if self.downsample_mode == "aggregate" and self.interleave_durations: + logger.info("--- Aggregate Mode Performance ---") + logger.info( + f"Total interleave operations: {len(self.interleave_durations)}" + ) + logger.info( + f"Min interleave duration: {min(self.interleave_durations):.3f} ms" + ) + logger.info( + f"Max interleave duration: {max(self.interleave_durations):.3f} ms" + ) + logger.info( + f"Avg interleave duration: {np.mean(self.interleave_durations):.3f} ms" + ) + logger.info("----------------------------------") + + def close_device(self) -> None: + """Stops the Picoscope and closes the connection.""" + # Check if handle is valid before trying to close. + if self.handle.value > 0: + status_stop = ps.ps5000aStop(self.handle) + if status_stop != PICO_STATUS["PICO_OK"]: + logger.warning(f"ps5000aStop failed with status {status_stop}") + + status_close = ps.ps5000aCloseUnit(self.handle) + if status_close != PICO_STATUS["PICO_OK"]: + logger.warning(f"ps5000aCloseUnit failed with status {status_close}") + + # Invalidate handle to prevent reuse. + self.handle.value = 0 + logger.info("Picoscope connection closed.") diff --git a/picostream/reader.py b/picostream/reader.py new file mode 100644 index 0000000..aa3e425 --- /dev/null +++ b/picostream/reader.py @@ -0,0 +1,259 @@ +from __future__ import annotations + +from typing import Generator, Tuple + +import h5py +import numpy as np + +from .conversion_utils import adc_to_mV, min_max_decimate_numba + + +class PicoStreamReader: + """A helper class to read and interpret data from picostream HDF5 files. + + This class provides a simple context-manager interface to open HDF5 files, + read metadata, and retrieve blocks of data as time and voltage arrays. + + It correctly handles the `analog_offset_v` if it is present in the file's + metadata. + + Example: + >>> with PicoStreamReader("output.hdf5") as reader: + ... print(f"Sample rate: {1e9 / reader.sample_interval_ns:.2f} S/s") + ... # Iterate through the whole file + ... for times, voltages in reader.get_block_iter(chunk_size=1_000_000): + ... # process data + ... pass + ... + ... # Or iterate with 20x decimation (mean) + ... for times, voltages in reader.get_block_iter( + ... chunk_size=1_000_000, decimation_factor=20, decimation_mode='mean' + ... ): + ... # process decimated data + ... pass + ... + ... # Or get blocks sequentially + ... reader.reset() # Reset internal counter + ... while True: + ... block = reader.get_next_block(chunk_size=500_000) + ... if block is None: + ... break + ... times, voltages = block + ... # process data + """ + + def __init__(self, hdf5_path: str): + """Initializes the PicoStreamReader. + + Args: + hdf5_path: Path to the HDF5 file. + """ + self.hdf5_path = hdf5_path + self._file: h5py.File | None = None + self.dset: h5py.Dataset | None = None + self._current_pos: int = 0 + + # Metadata attributes, populated in __enter__ + self.sample_interval_ns: float = 0.0 + self.voltage_range_v: float = 0.0 + self.max_adc_val: int = 0 + self.downsample_mode: str = "average" + self.hardware_downsample_ratio: int = 1 + self.analog_offset_v: float = 0.0 + + def __enter__(self) -> PicoStreamReader: + """Opens the HDF5 file and reads metadata.""" + self._file = h5py.File(self.hdf5_path, "r") + self.dset = self._file["adc_counts"] + + # Read metadata from file attributes + attrs = self._file.attrs + base_sample_interval_ns = attrs["sample_interval_ns"] + self.hardware_downsample_ratio = attrs.get("hardware_downsample_ratio", 1) + self.sample_interval_ns = ( + base_sample_interval_ns * self.hardware_downsample_ratio + ) + self.voltage_range_v = attrs["voltage_range_v"] + if "max_adc" in attrs: + self.max_adc_val = attrs["max_adc"] + elif "resolution" in attrs: + # Fallback for older files: calculate max_adc from resolution string + res_str = attrs["resolution"] # e.g., "PS5000A_DR_16BIT" + try: + # Extract bit depth (e.g., 16) from the string + res_int = int(res_str.split("_")[-1].replace("BIT", "")) + self.max_adc_val = (2 ** (res_int - 1)) - 1 + except (ValueError, IndexError): + raise KeyError( + f"Could not parse 'resolution' attribute to determine max_adc: {res_str}" + ) + else: + raise KeyError( + "HDF5 file is missing required 'max_adc' or 'resolution' attribute." + ) + self.downsample_mode = attrs.get("downsample_mode", "average") + self.analog_offset_v = attrs.get("analog_offset_v", 0.0) + + self.reset() + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + """Closes the HDF5 file.""" + if self._file: + self._file.close() + + @property + def num_samples(self) -> int: + """Total number of samples in the dataset.""" + if self.dset: + return self.dset.shape[0] + return 0 + + def reset(self) -> None: + """Resets the internal position counter for get_next_block.""" + self._current_pos = 0 + + def get_next_block( + self, + chunk_size: int, + decimation_factor: int = 1, + decimation_mode: str = "mean", + ) -> Tuple[np.ndarray, np.ndarray] | None: + """Retrieves the next block of data. + + Args: + chunk_size: The maximum number of raw samples to retrieve. + decimation_factor: The factor by which to decimate the data. + decimation_mode: The decimation method ('mean' or 'min_max'). + + Returns: + A (times, voltages) tuple, or None if no more data is available. + """ + if self._current_pos >= self.num_samples: + return None + + size = min(chunk_size, self.num_samples - self._current_pos) + block = self.get_block( + size=size, + start=self._current_pos, + decimation_factor=decimation_factor, + decimation_mode=decimation_mode, + ) + self._current_pos += size + return block + + def get_block_iter( + self, + chunk_size: int = 1_000_000, + decimation_factor: int = 1, + decimation_mode: str = "mean", + ) -> Generator[Tuple[np.ndarray, np.ndarray], None, None]: + """Yields data blocks as (times, voltages) tuples for the entire dataset. + + Args: + chunk_size: The size of each raw data chunk to yield. + decimation_factor: The factor by which to decimate the data. + decimation_mode: The decimation method ('mean' or 'min_max'). + """ + num_samples = self.num_samples + for start_idx in range(0, num_samples, chunk_size): + size = min(chunk_size, num_samples - start_idx) + yield self.get_block( + size=size, + start=start_idx, + decimation_factor=decimation_factor, + decimation_mode=decimation_mode, + ) + + def get_block( + self, + size: int, + start: int = 0, + decimation_factor: int = 1, + decimation_mode: str = "mean", + ) -> Tuple[np.ndarray, np.ndarray]: + """Retrieves a specific block of data and converts it to time and voltage. + + Optionally, it can decimate the data using either averaging or a + min-max technique. + + Args: + size: The number of raw samples to retrieve from the file. + start: The starting sample index. + decimation_factor: The factor by which to decimate the data. + decimation_mode: The decimation method ('mean' or 'min_max'). + + Returns: + A tuple containing: + - times (np.ndarray): The time axis in seconds. + - voltages (np.ndarray): The voltage data in millivolts. + """ + if not self.dset: + raise RuntimeError("File not open. Use this class as a context manager.") + + adc_data = self.dset[start : start + size] + + if adc_data.size == 0: + return np.array([]), np.array([]) + + # --- Decimation --- + decimated_adc_data = adc_data + final_decimation_factor = 1 + + if decimation_factor > 1 and adc_data.size >= decimation_factor: + final_decimation_factor = decimation_factor + + # Truncate data to be a multiple of the decimation factor + num_windows = adc_data.size // decimation_factor + truncated_len = num_windows * decimation_factor + adc_data_to_process = adc_data[:truncated_len] + + if decimation_mode == "min_max": + decimated_adc_data = min_max_decimate_numba( + adc_data_to_process, decimation_factor + ) + elif decimation_mode == "mean": + means = adc_data_to_process.reshape( + -1, decimation_factor + ).mean(axis=1) + decimated_adc_data = np.repeat(means, 2) + else: + raise ValueError( + f"Unknown decimation_mode: '{decimation_mode}'. Use 'mean' or 'min_max'." + ) + + # --- Voltage Conversion --- + voltages_mv = adc_to_mV(decimated_adc_data, self.voltage_range_v, self.max_adc_val) + if self.analog_offset_v != 0.0: + voltages_mv += self.analog_offset_v * 1000 + + # --- Time Axis Creation --- + points_per_timestep = 2 if self.downsample_mode == "aggregate" else 1 + time_per_timestep = self.sample_interval_ns * 1e-9 + time_per_raw_point = time_per_timestep / points_per_timestep + + start_time = (start / points_per_timestep) * time_per_timestep + + num_output_samples = voltages_mv.size + + if final_decimation_factor > 1: + time_step_between_windows = time_per_raw_point * final_decimation_factor + + # Both 'mean' and 'min_max' now produce pairs of points. + # The time axis is the start time of each decimation window, repeated. + num_pairs = num_output_samples // 2 + window_start_times = ( + start_time + np.arange(num_pairs) * time_step_between_windows + ) + times = np.repeat(window_start_times, 2) + else: + # Original time axis logic for non-decimated data + if self.downsample_mode == "aggregate": + num_pairs = num_output_samples // 2 + pair_times = start_time + np.arange(num_pairs) * time_per_timestep + times = np.repeat(pair_times, 2) + else: + end_time = start_time + (num_output_samples - 1) * time_per_raw_point + times = np.linspace(start_time, end_time, num_output_samples) + + return times, voltages_mv diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..e3e8497 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,24 @@ +[build-system] +requires = ["setuptools"] +build-backend = "setuptools.build_meta" + +[project] +name = "picostream" +version = "0.2.0" +dependencies = [ + "numpy", + "loguru", + "picosdk", + "h5py", + "pyqtgraph", + "PyQt5", + "numba", + "click", +] + + +[tool.setuptools] +packages = ["picostream"] # List the package names directly + +[project.scripts] +picostream = "picostream.main:main" diff --git a/status_values_pico.html b/status_values_pico.html new file mode 100644 index 0000000..63a9aca --- /dev/null +++ b/status_values_pico.html @@ -0,0 +1,683 @@ + + + + + PICO_STATUS values + + + + + + + + + + + + + + + + + + + + + + +
+ +
+
+ Show/Hide Toolbars +
+
+
+ +
+ + +
+
+
+ + +
+
+ +
+ +
+ +
+ + + + + +
+
+

Navigation: + Driver routines +

+ +

PICO_STATUS values

+ + +
+
+ + + Scroll + + Prev + + + Top + + + Next + + + More + +
+
+
+
+
+
+ +

Every function in the PicoLog 1000 Series API returns an error code from the following list of PICO_STATUS values defined in PicoStatus.h:

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Code

+

(hex)

+

Enum

+

Description

+

00

+

PICO_OK

+

The Data Logger is functioning correctly

+

01

+

PICO_MAX_UNITS_OPENED

+

An attempt has been made to open more than 64 units

+

02

+

PICO_MEMORY_FAIL

+

Not enough memory could be allocated on the host machine

+

03

+

PICO_NOT_FOUND

+

No PicoLog 1000 device could be found

+

04

+

PICO_FW_FAIL

+

Unable to download firmware

+

05

+

PICO_OPEN_OPERATION_IN_PROGRESS

+

A request to open a device is in progress

+

06

+

PICO_OPERATION_FAILED

+

The operation was unsuccessful

+

07

+

PICO_NOT_RESPONDING

+

The device is not responding to commands from the PC

+

08

+

PICO_CONFIG_FAIL

+

The configuration information in the device has become corrupt or is missing

+

09

+

PICO_KERNEL_DRIVER_TOO_OLD

+

The kernel driver is too old to be used with the device driver

+

0A

+

PICO_EEPROM_CORRUPT

+

The EEPROM has become corrupt, so the device will use a default setting

+

0B

+

PICO_OS_NOT_SUPPORTED

+

The operating system on the PC is not supported by this driver

+

0C

+

PICO_INVALID_HANDLE

+

There is no device with the handle value passed

+

0D

+

PICO_INVALID_PARAMETER

+

A parameter value is not valid

+

0E

+

PICO_INVALID_TIMEBASE

+

The timebase is not supported or is invalid

+

0F

+

PICO_INVALID_VOLTAGE_RANGE

+

The voltage range is not supported or is invalid

+

10

+

PICO_INVALID_CHANNEL

+

The channel number is not valid on this device or no channels have been set

+

11

+

PICO_INVALID_TRIGGER_CHANNEL

+

The channel set for a trigger is not available on this device

+

12

+

PICO_INVALID_CONDITION_CHANNEL

+

The channel set for a condition is not available on this device

+

13

+

PICO_NO_SIGNAL_GENERATOR

+

The device does not have a signal generator

+

14

+

PICO_STREAMING_FAILED

+

Streaming has failed to start or has stopped without user request

+

15

+

PICO_BLOCK_MODE_FAILED

+

Block failed to start - a parameter may have been set wrongly

+

16

+

PICO_NULL_PARAMETER

+

A parameter that was required is NULL

+

18

+

PICO_DATA_NOT_AVAILABLE

+

No data is available from a run block call

+

19

+

PICO_STRING_BUFFER_TOO_SMALL

+

The buffer passed for the information was too small

+

1A

+

PICO_ETS_NOT_SUPPORTED

+

ETS is not supported on this device

+

1B

+

PICO_AUTO_TRIGGER_TIME_TOO_SHORT

+

The auto trigger time is less than the time it will take to collect the data

+

1C

+

PICO_BUFFER_STALL

+

The collection of data has stalled as unread data would be overwritten

+

1D

+

PICO_TOO_MANY_SAMPLES

+

The number of samples requested is more than available in the current memory segment

+

1E

+

PICO_TOO_MANY_SEGMENTS

+

Not possible to create number of segments requested

+

1F

+

PICO_PULSE_WIDTH_QUALIFIER

+

A null pointer has been passed in the trigger function or one of the parameters is out of range

+

20

+

PICO_DELAY

+

One or more of the hold-off parameters are out of range

+

21

+

PICO_SOURCE_DETAILS

+

One or more of the source details are incorrect

+

22

+

PICO_CONDITIONS

+

One or more of the conditions are incorrect

+

24

+

PICO_DEVICE_SAMPLING

+

An attempt is being made to get stored data while streaming. Stop streaming by calling pl1000Stop().

+

25

+

PICO_NO_SAMPLES_AVAILABLE

+

...because a run has not been completed

+

26

+

PICO_SEGMENT_OUT_OF_RANGE

+

The memory index is out of range

+

27

+

PICO_BUSY

+

Data cannot be returned yet

+

28

+

PICO_STARTINDEX_INVALID

+

The start time to get stored data is out of range

+

29

+

PICO_INVALID_INFO

+

The information number requested is not a valid number

+

2A

+

PICO_INFO_UNAVAILABLE

+

The handle is invalid so no information is available about the device. Only PICO_DRIVER_VERSION is available.

+

2B

+

PICO_INVALID_SAMPLE_INTERVAL

+

The sample interval selected for streaming is out of range

+

2C

+

PICO_TRIGGER_ERROR

+

Not used

+

2D

+

PICO_MEMORY

+

Driver cannot allocate memory

+

36

+

PICO_DELAY_NULL

+

NULL pointer passed as delay parameter

+

37

+

PICO_INVALID_BUFFER

+

The buffers for overview data have not been set while streaming

+

3A

+

PICO_CANCELLED

+

A block collection has been canceled

+

3B

+

PICO_SEGMENT_NOT_USED

+

The segment index is not currently being used

+

3F

+

PICO_NOT_USED

+

The function is not available

+

41

+

PICO_INVALID_STATE

+

Device is in an invalid state

+

43

+

PICO_DRIVE_FUNCTION

+

You called a driver function while another driver function was still being processed

+
+
+ +
+
+
+
+ +
+
+ + + + + + + + + + +
  
+
+
+
+ + + + -- cgit v1.2.3