diff --git a/.copier-answers.yml b/.copier-answers.yml index ed848e7..a17a8aa 100644 --- a/.copier-answers.yml +++ b/.copier-answers.yml @@ -1,21 +1,21 @@ # Changes here will be overwritten by Copier -_commit: a093063 +_commit: 8d1a17d _src_path: https://codeberg.org/Fresh2dev/copier-f2dv-project.git author_email: hello@Fresh2.dev author_name: Donald Mellenbruch ci_domain_name: lokalhost.net -docs_url: https://www.Fresh2.dev/code/r/ezpq/i +docs_url: https://www.Fresh2.dev/code/r/ppqueue/i funding_url: https://www.Fresh2.dev/funding home_page: https://www.Fresh2.dev is_minimal: false is_python: true -license_type: GPLv3 -package_name: ezpq -project_description: None -project_name: ezpq -python_version: '3.7' -repo_mirror: https://www.Fresh2.dev/code/r/ezpq -repo_name: fresh2dev/ezpq +license_type: MIT +package_name: ppqueue +project_description: Parallel Process Queue (ppqueue) for Python +project_name: ppqueue +python_version: '3.8' +repo_mirror: https://www.Fresh2.dev/code/r/ppqueue +repo_name: fresh2dev/ppqueue repo_owner: fresh2dev -repo_url: https://www.github.com/fresh2dev/ezpq +repo_url: https://www.github.com/fresh2dev/ppqueue diff --git a/.drone.yml b/.drone.yml index 2273c67..83e15d8 100644 --- a/.drone.yml +++ b/.drone.yml @@ -2,10 +2,13 @@ kind: template load: hostbutter.jsonnet data: domains: >- - ["lokalhost.net"] + ["lokalhost.net", "fresh2.dev"] domainTriggers: >- { - "lokalhost.net": {} + "lokalhost.net": {}, + "fresh2.dev": { + "ref": ["refs/heads/main", "refs/tags/*"] + } } domainClusterMap: >- {} diff --git a/.env b/.env index b637a6c..baca766 100644 --- a/.env +++ b/.env @@ -1,5 +1,5 @@ ### STACK NAME -COMPOSE_PROJECT_NAME=ezpq +COMPOSE_PROJECT_NAME=ppqueue ### GLOBAL VARIABLES HB_DOMAIN= @@ -11,7 +11,7 @@ HB_IMAGE_REGISTRY= ## APP APP_SVC_ID=app -APP_SUBDOMAIN=ezpq. +APP_SUBDOMAIN=ppqueue. APP_ROUTE_PREFIX= # APP_STRIP_PREFIX= APP_HTTP_PORT=80 diff --git a/.gitignore b/.gitignore index 0b947a3..b8092cc 100644 --- a/.gitignore +++ b/.gitignore @@ -9,6 +9,7 @@ /dist /build +**/.ipynb_checkpoints **/.coverage **/.hypothesis **/.tox diff --git a/.python-base-version b/.python-base-version index 36f601f..eee6392 100644 --- a/.python-base-version +++ b/.python-base-version @@ -1 +1 @@ -3.7.16 +3.8.16 diff --git a/CHANGELOG.md b/CHANGELOG.md index 72fade9..704639e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,8 +1,19 @@ # Changelog -## v0.3.0 - -- refactor full of breaking changes, for the sake of simplicity and completeness. +## Unreleased + +- rename from `ezpq` to `ppqueue` +- replaced `queue.get` with `queue.dequeue` / `queue.pop` +- `queue.put` is an alias for `queue.enqueue` +- renamed `queue.empty` to `queue.is_empty` +- renamed `queue.full` to `queue.is_full` +- renamed `queue.count_queues` to `queue.sizes` +- replaced `ezpq.FinishedJob` with `ezpq.Job` +- `job.output` is now `job.result` +- `job.callback` is now `job.callback_result` +- wrapped `Plot(...).build(...)` into just `plot_jobs(...)` +- use of enums to constrain plot parameter choices +- bump dependencies ## v0.2.1 diff --git a/Dockerfile b/Dockerfile index 0c22f98..690b578 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,8 +1,8 @@ ARG HB_IMAGE_REGISTRY=docker.io FROM ${HB_IMAGE_REGISTRY}/python:3.10.10-slim-bullseye as build -LABEL org.opencontainers.image.source=https://www.github.com/fresh2dev/ezpq -LABEL org.opencontainers.image.description="None" -LABEL org.opencontainers.image.licenses=GPLv3 +LABEL org.opencontainers.image.source=https://www.github.com/fresh2dev/ppqueue +LABEL org.opencontainers.image.description="Parallel Process Queue (ppqueue) for Python" +LABEL org.opencontainers.image.licenses=MIT RUN apt-get update && apt-get install --upgrade -y build-essential git WORKDIR /app ENV PYTHONUNBUFFERED=1 @@ -14,11 +14,11 @@ RUN find /dist -name "*.whl" -exec \ pip install --no-cache-dir \ --extra-index-url "https://codeberg.org/api/packages/Fresh2dev/pypi/simple" \ "{}" \; \ - && pip show "ezpq" + && pip show "ppqueue" FROM ${HB_IMAGE_REGISTRY}/python:3.10.10-slim-bullseye COPY --from=build /app/venv /app/venv COPY --from=build /usr/local/bin /usr/local/bin ENV PATH="/app/venv/bin:$PATH" -ENTRYPOINT ["ezpq"] +ENTRYPOINT ["ppqueue"] WORKDIR /workspace diff --git a/Dockerfile-docs b/Dockerfile-docs index cf55f68..4f22f85 100644 --- a/Dockerfile-docs +++ b/Dockerfile-docs @@ -1,7 +1,7 @@ ARG HB_IMAGE_REGISTRY=docker.io FROM ${HB_IMAGE_REGISTRY}/nginx:1 -LABEL org.opencontainers.image.source=https://www.github.com/fresh2dev/ezpq -LABEL org.opencontainers.image.description="None" -LABEL org.opencontainers.image.licenses=GPLv3 +LABEL org.opencontainers.image.source=https://www.github.com/fresh2dev/ppqueue +LABEL org.opencontainers.image.description="Parallel Process Queue (ppqueue) for Python" +LABEL org.opencontainers.image.licenses=MIT ARG CONTENT_PATH=public COPY $CONTENT_PATH /usr/share/nginx/html diff --git a/LICENSE b/LICENSE index aa08301..58cb9a5 100644 --- a/LICENSE +++ b/LICENSE @@ -1,674 +1,7 @@ -GNU GENERAL PUBLIC LICENSE -Version 3, 29 June 2007 +Copyright 2023 Donald Mellenbruch -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. +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: -Preamble +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. -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 -. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/README.ipynb b/README.ipynb deleted file mode 100644 index 1229fea..0000000 --- a/README.ipynb +++ /dev/null @@ -1,304 +0,0 @@ -{ - "cells": [ - { - "cell_type": "raw", - "metadata": {}, - "source": [ - "---\n", - "title: My app title 🚀\n", - "description: Data app with many calculations\n", - "params:\n", - " variable:\n", - " input: text \n", - " label: Please provide text\n", - "---" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "> TODO: standardize pending job > finished job attributes.\n", - " - inactive\n", - " - active\n", - " - finished\n", - "- [ ] change all `assert` to `raise Exception...`\n", - "- [ ] type-hint everywhere.\n", - "- [ ] redo all docstrings.\n", - "- [ ] cleanup logging output.\n", - "\n", - "# ezpq\n", - "\n", - "> easy parallel queue\n", - "\n", - "## Overview\n", - "\n", - "`ezpq` is a Python module that serves as an abstraction layer to both `multiprocessing.Process` and `threading.Thread` that offers:\n", - "- a unified API for parallel processing using multiprocessing or threading.\n", - "- FIFO priority queueing.\n", - "- methods for generating plots.\n", - "- `tqdm` integration for progress-bars.\n", - "- error-handling, logging.\n", - "- cross-platform compatibility.\n", - "\n", - "This project is:\n", - "- free, open-source\n", - "- **fun**ctional\n", - "- interesting\n", - "- all I need it to be\n", - "\n", - "This project is **not**:\n", - "- extensively tested\n", - "- super-clean\n", - "- thoroughly documented\n", - "\n", - "Bug reports and MRs are welcome, though I don't imagine any major enhancements; just enough to keep tests passing.\n", - "\n", - "## Install\n", - "\n", - "From PyPi: `pip install ezpq[plot]`\n", - "\n", - "From source: `git clone ... && pip install .`\n", - "\n", - "Run tests from source: `make test`\n", - "\n", - "Build this README with Jupyter: `make builddocs`\n", - "\n", - "## Examples" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "> imports." - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "metadata": {}, - "outputs": [], - "source": [ - "import ezpq\n", - "import threading\n", - "import multiprocessing as mp\n", - "import time" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "> minimal example.\n", - "\n", - "3 workers, 18 jobs, each job takes 1 second:" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "metadata": {}, - "outputs": [ - { - "name": "stderr", - "output_type": "stream", - "text": [ - "100%|██████████| 18/18 [00:06<00:00, 2.79op/s]\n" - ] - }, - { - "data": { - "image/png": "iVBORw0KGgoAAAANSUhEUgAAAsMAAAGuCAYAAAB1DgtbAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjUuMCwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy8/fFQqAAAACXBIWXMAAA9hAAAPYQGoP6dpAAA5/klEQVR4nO3deXhU5fnG8XtWEggYMoEQ1iCRABVRAqK4gFqwLZVFwYUiFaRgFX5Si0VaEKOA0iKCgkJBQ90KVYoLLrigragtFje0AaQEEAmyDhKSOMs5vz8oKUkmkAmzZHK+n+viupJzzrzncXxg7vPOO2dspmmaAgAAACzIHu8CAAAAgHghDAMAAMCyCMMAAACwLMIwAAAALIswDAAAAMsiDAMAAMCyCMMAAACwLGe8C4iGkpISbdq0SZ06dVLDhg3jXQ4AA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oKFDh+qss87SVVddpebNm2vv3r16+eWXtWPHDj3//PMRK660tFSNGjWqsK1Ro0bau3dvlWOLiopUVFQkSSooKIhYDZV5vV45nU4CXyWmaSoYDMrhcPDcnMA0TXomhFj2y/TZJVEdP3p2R/0My5dkR/0cQCQVFRWpU6dOFbbdddddeuCBB9SqVSt9/fXXcarsmGbNmsnpdFbJKd9++21EH4PICnuqatCgQfroo4/Uo0cPvfjii7r33nv14osvqkePHvroo480aNCgiBWXnJyso0ePVth29OhRJSdXnc1YvHixcnNzlZubqxEjRkSsBgAAUDdUvoAOBoP66quvJEk2m03BYHzfCXI4HOrevbtWrVpVYfvJJgpr8xhEVq2+dOPcc8/V8uXLI11LFW3bttXKlStlGEb5W8yFhYW69NJLqxw7btw4DRw4UNKxmeFoBeLU1FR5PB7e8q7k+NvezIBWZBiGAoEAPVNJLPslb3IiLpM4oLQ0T9SXSQCJplWrVlq7dq369+8vSdqwYYMCgYA2bdokqW4sLfjd736nQYMGadSoUbr++uu1YcMGPfXUUxF/DCLntL6BLlKCwaCCwaAMw5BhGOXrK7t27Sq3262//vWvGjRokP75z39qx44duuiii6qMkZmZqczMzKjX6nK55Ha7CTaVmKYpu91OGK7EMAx6JoRY9ktOgq0EMAxDe/Y41KJFEj0DVDJs2DA98MADevfdd+VwONSjRw+de+65mjp1qhwOh+644454l6iBAwdq0aJFmjlzppYvX65evXppxYoV6tWrV0Qfg8gJOwwbhqGlS5fq+eef165du6p8ctNms+k///lPWGOuWLGiwkzz+++/r8svv1wTJ07U1KlTtWDBAi1fvlzNmzfXlClTuK0aAAAW1LNnT82ZM0cbN25UZmamevbsqYEDB2rz5s1q3ry50tLS4l2ipGPvVo8bN678d6/XW2H/9u3bT/kY6djEAaIv7DA8efJkPfjgg+rTp48uu+wyud3u0y5i+PDhGj58eMh9WVlZmjNnzmmfAwAAJL727dtXuMWrzWar8qE6IBxhh+FnnnlGeXl5mjZtWjTqAQAAqNaHH36oNWvWaN++fWrWrJl+9KMf6YILLoh3WUhgYYfhsrIy9e7dOxq1AAAAVOutt97S008/rcGDByszM1NFRUVatGiRSkpKdPnll8e7vGqlpqay5KEOCzsM/+xnP9PLL7+sK664Ihr1AAAAhLRq1SpNmTJFOTk55ds6d+6sBQsWxD0Mb9iwISrj5ubmRmVc/E/YYfiCCy7Q1KlT9e2336pfv34hP8x29dVXR6I2AACAcvv3768QhCUpJycn5JdxATUVdhi+8cYbJUk7duzQihUrquyvCze9BgAA9U9aWpoOHDggj8dTvu3AgQNq2rRpHKuqqGPHjhEba8uWLREbC9ULOwwXFhZGow4AAICTGjt2rEpLSytsKy0trXJLMiAcYYfhdu3aRaMOAACAkzrvvPOqbGvdurVat24dh2pQX9QoDB88eFCpqamy2+06ePDgKY+vKze9BgAA9UdxcbHy8/O1ZcsWtWvXTr/85S/1zTff6I033lDz5s01ZMgQuVyueJeJarz00kuaMGGCDhw4oNWrV6tv377xLkmSVKPv+mzWrJn+9a9/SZLS09PVrFmzk/4BAACItCVLlui7777TDTfcoLKyMj322GNaunSpGjdurHXr1mnJkiXxLjFmxo4dq1atWqlJkybKysrSrFmzavS4BQsWqEOHDmrcuLG6du2ql19+uXzfLbfcopSUlPI/SUnHvhZ+//79kqQ9e/Zo6NCh8ng8atGihWbOnFlh7GnTpqlr165yOp266667qpz717/+tebMmaPi4uIKQXj//v1KT0+P2/2iazQz/MQTT6hDhw7lP9tstqgWBQAAUNknn3yiRx99VCkpKeratatGjBihxx9/XOnp6Ro0aJBuv/123XrrrfEuMyYmTpyo+fPnKzk5WV9//bWuvPJKZWdn69prr632MR988IEmT56sd955Rz179tRLL72ka6+9Vtu3b1dGRoYWLVqkRYsWlR8/efJkbdiwQenp6ZKO3UShffv2+uabb7Rr1y5dccUVatOmjUaOHClJys7O1u9///tqL0oKCwvVtWvXKtvvvPNOdenSRT6f73SeklqrURj++c9/Xv7zTTfdFK1aAAAAquX3+9WwYUNJUsOGDeVwOHTGGWdIkho3biy/3x/P8mKqS5cuFX632+3aunWrJGn9+vWa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nSpFbj1gZhGAAA1Avjx4/XggUL4nLuO285LCk2X8d86NAhrV69uvwDcB9++KEee+wxTZs2TYMHD9asWbP01FNP6frrr1dpaakKCgrUq1cv9erVS9OnT9eWLVvUsWNHrV+/Xh988IEmTpxYYfz8/HyNHj26ynkLCgrUsmVLNWrUSK+99pqWLl1aIXj7/X4Fg8HyP2VlZXI6nXI6q8bN6667Tj/60Y/Kf1+xYoWefPJJvfLKKyGXbURTrcPwli1btH79ehUVFSkzM1M9e/ZUTk5OJGurk1JTU+XxeFgmUcnxZRLMmldkGIYCgUDEeiZvMsskQklPr36ZBID644UXXlCfPn3UtGnTkPv37dsX44riw2azKT8/X//3f/+nQCCgVq1a6de//rXGjx8vm82m119/XXfeeacmTJig5ORkTZw4Ub169dKIESO0bds29e/fXwcOHFBGRoamT5+ufv36lY+9YcMGbdq0STfeeGOV87799tu69957dfToUXXp0kV/+ctfyj8MJ0m/+MUv9Kc//an89zlz5mj69Om65557qoyVnJxcvh5Zks444wy5XC61aNEiQs9SzYUdhouLizV27Fj95S9/kWEYSkpKUllZmex2u4YNG6YlS5YoJSUlGrXWCS6XS263mzBciWmastvthOFKDMOIaM/khF4GlnC4eAJQG3/729/05JNPKjc3V1dccYV69uwph8N6F8Opqalau3Zttft79+5dZb2vdCxET58+XdOnT6/2sbm5udXe73f8+PEaP358tY9dtmyZli1bVu3+E+9EUdlNN90Ut9v3hv3qPGHCBK1evVpLlizR4cOHVVJSosOHD+uPf/yjXnnlFU2YMCEadQIAAIt76KGH9OCDD6pZs2Z65JFHNHr0aOXn52vnzp3xLg0JLOyZ4ZUrV2r27NkaNWpU+bbGjRtr9OjRKisr05QpU5Sfnx/RIgEAACSpffv2Gjt2rEaPHq1//vOfevPNN3X77berQ4cOlvrSDURO2GE4KSlJ7du3D7nvzDPPlMvlOu2iAAAATsbpdOqiiy7SRRddpAMHDmjt2rWEYdRK2MskRo0apccee6zKug/TNPXoo49WmDEGAACINo/Ho2HDhmn+/PnxLgUJqEYzw3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033yQMo1xSUlKF+1t36dJFnTt3VkFBgc4880w9+uij+uijjxQMBtW8eXNNmjRJbdu2jWPFqAu++OIL7d69W/369dPrr78uSfL5fPQLQnr22Wd13XXXqUuXLpJU/oUS9AxQe4ThGvjmm29kmqbatWtXvq19+/b68MMP41gV6rqysjJt3bpVV111ldauXasdO3Zo8eLFatSokXbt2qWUlJR4l4g48/v9Wrx4se644w5t27atfDv9glCCwaC++uornX/++brllltUVlam8847T2PGjNF7771HzwC1xAfoaqCsrKzKd5s3atRIpaWlcaoIdZ1hGJo3b57OOussnXfeeXI6nSotLdWuXbtkmqbatGmjpk2bxrtMxNnKlSvVrVs3tW/fvsJ2+gWheL1eBQIB/f3vf9eMGTO0YMECeb1eLV26lJ4BTgMzwzWQlJRUJfiWlJRE5HvTUf+YpqlHH31UBw8eVF5enmw2my677DIdPHhQCxcu1MGDB3XhhRdq9OjRVS6yYB27d+/W22+/rfnz51fZR78glAYNGkiSBgwYoPT0dEnSsGHDNGvWLI0fP56eAWqJmeEaaNWqlSRp586d5dsKCwtZi4UqTNPUokWLVFhYqHvuuaf8gsnhcOjaa6/VI488okceeURff/21/vrXv8a5WsRTQUGBDh06pFtuuUUjR47UkiVLtG3bNo0cOVLff/89/YIqUlJSlJ6eLpvNVmUf/8YAtcfMcA0kJSXpoosu0lNPPaVf/epX2rdvn9544w3dfvvt8S4NdczixYu1efNmzZgxo8KMzOeff67GjRurbdu2SkpKksvlkt3OtaiVXXzxxerevXv57++9957eeecd3X333dq6dSv9gpD69++vV155RT169FCDBg20cuVKnX/++fwbA5wGwnANjRs3TgsWLNBNN92k5ORkXXPNNdxJAhXs3btXr776qlwul0aPHl2+fejQocrIyNBjjz2mAwcOqEGDBurevbuuvvrqOFaLeGvQoEH5297Ssc8hOBwONW3aVJ9//jn9gpCGDRum7777TrfddpscDod69OihMWPG6KOPPqJngFqymaZpxrsIAAAAIB54DwUAAACWRRgGAACAZRGGAQAAYFmEYQAAAFgWYRgAAACWRRgGAACAZRGGA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X2f7tt98qLS0t7PEAANbAMgkAVTgcDnXv3l2rVq2qsP3555+v8Hvr1q1VUFBQYdubb75Zo3OUlpZK+t+srCR98MEH2r59e4Xj3G63vv/++1OOd/HFF2vjxo0VAvGhQ4f01ltv6eKLL65RTQAA6yEMAwjpd7/7nd577z2NGjVKa9as0axZs/TUU09VOGbo0KF67rnn9PDDD2vNmjW68cYb9c0339Ro/AsuuEApKSm67bbb9MYbbyg/P1/XX3+9WrVqVeG4zp07KxAIaP78+froo49Czv5K0qhRo9SuXTsNGDBAy5cv1wsvvKD+/fvL6XRq4sSJtXoOAAD1H2EYQEgDBw7UokWL9Pbbb2vw4MF64403tGLFigrHTJs2TcOHD1deXp5GjBihdu3a6fbbb6/R+BkZGXruuee0d+9eDRo0SPPmzdPixYuVnZ1d4birrrpKt956q+6//3716tVL48aNCzle48aN9e6776pbt24aO3asfvazn6lp06b6+9//XuG2agAAnMhmmqYZ7yIAAACAeGBmGAAAAJZFGAYAAIBlEYYBAABgWYRhAAAAWBZhGAAAAJZFGAYAAIBlEYYBAABgWYRhAAAAWBZhGAAAAJZFGAYAAIBlEYYBAABgWf8PSKefnHWyg6MAAAAASUVORK5CYII=", - "text/plain": [ - "
" - ] - }, - "metadata": {}, - "output_type": "display_data" - }, - { - "data": { - "text/plain": [ - "" - ] - }, - "execution_count": 3, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "with ezpq.Queue(\n", - " max_concurrent=3,\n", - " engine=threading.Thread, # or `mp.Process`\n", - " show_progress=True\n", - ") as queue:\n", - "\n", - " # put, wait, collect.\n", - " finished = queue.map(time.sleep, [1] * 18, show_progress=True)\n", - "\n", - "# plot.\n", - "ezpq.Plot(finished).build()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "> minimal example with decorator.\n", - "\n", - "Same as above, but using the @decorator interface." - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "metadata": {}, - "outputs": [ - { - "name": "stderr", - "output_type": "stream", - "text": [ - "100%|██████████| 18/18 [00:06<00:00, 2.70op/s]\n" - ] - }, - { - "data": { - "image/png": "iVBORw0KGgoAAAANSUhEUgAAAscAAAGuCAYAAAB85ashAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjUuMCwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy8/fFQqAAAACXBIWXMAAA9hAAAPYQGoP6dpAAA6aElEQVR4nO3deXRU9f3/8dcsGbKhMQmERAgJUECkIgSrsis/sFUBl2AVURYRqGJdqqV+XSAIKBUDKlhSqUGolsW1opZScbcVihVEAbEEUFmCxEFCCMnMvb8/ch0YEigTMnMnyfNxDudkPnfm3rf3vM285nM/ueMwTdMUAAAAADntLgAAAACIFoRjAAAAwEI4BgAAACyEYwAAAMBCOAYAAAAshGMAAADAQjgGAAAALG67CwiHsrIybdq0SR07dlR8fLzd5QAAgJPk9XpVVlZWJ/uKj49XUlJSnewLjUeDDMebNm1STk6O1q5dq27dutXZfk3T1IEDB9S0aVM5HI462299ZZqmDMOQ0+nkfIj+OBb9EYz+CEZ/BKM/qni9Xs2ZM0c+n69O9ud2uzVhwgQCMkLSIMNxuJimqdLSUiUmJjbqX15H+/HNDfRHTeiPI+iP6uiPI+iPKmVlZfL5fOratasSExNPaV+lpaX6z3/+o7KyMsIxQkI4BgAAUSUxMZFAC9vwkR0AAACwEI4BAAAAC+EYAAAAsBCOAQAAAAvhGAAAALAQjgEAAAAL4RgAAACwEI4BAAAAC+EYAAAAsBCOAQAAAAvhGAAAALAQjgEAAACL2+4C6pvKykpVVFTI6eRzhWma8vl8MgxDDofD7nJsZxgG/XEU+iMY/RGsvvRH0Q5/RI5jGKZKSvzaX1oupzN6z4ckZWe65PF47C4DCBvCcYi8Xq/cbndU/zKPFNM05ff75XK5OB+qOh/0xxH0RzD6I1h96Y9JM8oifMSdET5e6PLz4pWRkWF3GUDYMH0BAAAAWJg5DlFSUpJSUlK4LKojl0WZCatiGIZ8Ph/9YaE/gtEfwepLf+RNjOS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LyZJqmLrroosC2rKwsFRcX21gdGoqT+g7TZs2a6d///rckKTU1Vc2aNTvhPwAAgHDIzs7WQw89pGeffVbLly8PjJeUlKhp06Y2VhZZc+bMUffu3dWkSRNde+21QdsMw1BeXp5atWqlxMREnX322YFvL3799dfVu3dvJSUlqXnz5rruuuu0Z8+eoNc/8MADatasmU4//XSNGTNGhw8fPqmatm3bJofDocTExMC/8ePHB7aPHz8+aFtsbKycTqe+++47SdLkyZMVExMT9Jz333//VE5TrZzUzPEzzzyjtm3bBn52OBxhLQoAAOB4WrVqpenTp+vBBx/UJ598os6dO+vdd9+tttSiIcvIyND999+vf/zjH4Fw+aMpU6bo7bff1nvvvaesrCxt2bIlcFV///79+t3vfqd+/frJNE2NHz9eI0eO1JtvvilJmj9/vp577jl9/PHHOv300zVkyBA9+OCDmjFjxknX9t133yk2Nrba+Lx58zRv3rzA44kTJ2rt2rVKTU0NjF199dVavHhxSOeirp1UOB4xYkTg55EjR4arFgAAgOM6++yzAz9nZGRo9uzZevnll/XFF1+ob9++jWq98Y+3zf3000+DwrHX69XMmTP1n//8R9nZ2ZKC76AxbNiwoP38+te/DvruisLCQt11111q06aNJGnSpEm6/vrrA+H40UcfVUFBgfbs2aOWLVtq6tSpuvrqq0Ou3+/3a9GiRZo5c2bIrw23kP8gDwAAwA4PPvhg0OPExMTALWbt9ui8062f9pzweaE5XYufDu0Vn332mdxut1555RXl5+crPj5eN910k+69994ar/y/++676ty5c+Dxhg0bdO655wYen3vuudq7d6/27NmjtLQ0ZWdn691331V6erpeeukl3XDDDTr//PPVsmXLwGvatWsnwzDUp08fPfroo2rVqlW147755psqKyur9oHmzTffVEpKipo3b66RI0fqnnvukdN5UquA60xkjwYAAHCKDh8+rK1bt+qLL77Q1q1bT3pNbGPw9ddfa//+/dqwYYO++uorvfnmm/rjH/+ohQsXVnvu6tWrNXXq1KDZ29LS0qAvePvx5wMHDkiScnNzdeaZZ8rpdCo3N1cdOnTQxx9/LKnq79LWrFmjbdu2af369Up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kWmaatWqlc444wy7y0SEvfjii+rSpYuys7ODxukPeL1e+Xw+vffee5o6darmzJkjr9er+fPn0x9AFGDm+CTExsZWC8JlZWV18r3vqN9M09RTTz2lkpIS5eXlyeFw6KKLLlJJSYnmzp2rkpISXXjhhRo9enS1D1houHbu3Km33npLjz/+eLVt9AeaNGkiSbrsssuUmpoqSRo6dKimT5+uCRMm0B+AzZg5PglnnnmmJGnHjh2BsaKiItaANXKmaWrevHkqKirS5MmTAx+WXC6XrrnmGj355JN68skn9fXXX+ull16yuVpE0saNG/X9999r/PjxuvHGG/X0009r69atuvHGG3X48GH6o5FLTExUamqqHA5HtW38/gDsx8zxSYiNjVXPnj21aNEi3Xnnndq7d6/+/ve/6/bbb7e7NNiooKBAmzdv1tSpU4NmddavX6+mTZsqMzNTsbGxiomJkdPJ59DGpFevXurWrVvg8fvvv6+3335bDz74oL766iv6Axo4cKBef/11de/eXU2aNNGLL76on/3sZ/z+AKIA4fgkjRs3TnPmzNHIkSMVFxenq6++mjtVNGLFxcV64403FBMTo9GjRwfGc3NzlZaWpj/84Q/at2+fmjRpom7duumqq66ysVpEWpMmTQKXzqWqv1FwuVw644wztH79evoDGjp0qH744Qfdeuutcrlc6t69u8aMGaM1a9bQH4DNHKZpmnYXAQAAAEQDrtUAAAAAFsIxAAAAYCEcAwAAABbCMQAAAGAhHAMAAAAWwjEAAABgIRwDAAAAFsIxAAAAYCEcAwAAABbCMYCT5vV65XA4tGDBgogd85133tH06dOrjU+ePFmJiYkRqwMA0DgQjgFEteOF4zFjxujtt9+2oSIAQEPmtrsAAI3PoUOHFBcXd0r7aNmypVq2bFlHFQEAUIWZYwDH9fTTTysrK0vx8fHq37+/vvrqq6DtDodDM2fODBqbPXu2HA5H4PE777wjh8Oh119/Xbm5uTrttNM0dOhQSdLChQvVq1cvJScn64wzzlC/fv20evXqwGsnT56svLw8HTx4UA6HQw6HQ/369QtsO3ZZxfbt25Wbm6vTTz9dCQkJuuSSS/TZZ58FPScrK0sTJkzQ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Dx6sefPm6a233tIVV1yhv//971qyZEnQcx544AENGzZMeXl5Gj58uFq3bq3bb7/9pPaflpamZcuWqbi4WEOGDNHs2bNVUFCgdu3aBT1v0KBBuuWWW/Twww/r/PPP17hx42rcX9OmTfXOO++oS5cuGjt2rK6//nqdccYZeu+994Ju4wYAwIk4TNM07S4CAAAAiAbMHAMAAAAWwjEAAABgIRwDAAAAFsIxAAAAYCEcAwAAABbCMQAAAGAhHAMAAAAWwjEAAABgIRwDAAAAFsIxAAAAYCEcAwAAAJb/D1VSxdM+PO7NAAAAAElFTkSuQmCC", - "text/plain": [ - "
" - ] - }, - "metadata": {}, - "output_type": "display_data" - }, - { - "data": { - "text/plain": [ - "" - ] - }, - "execution_count": 5, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "# define.\n", - "@ezpq.Queue(\n", - " max_concurrent=3,\n", - " engine=threading.Thread, # or `mp.Process`\n", - " show_progress=True\n", - ")\n", - "def time_sleep(x):\n", - " time.sleep(x)\n", - "\n", - "# call and collect.\n", - "finished = time_sleep([1] * 18)\n", - "\n", - "# plot.\n", - "ezpq.Plot(finished).build()" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "> verbose form.\n", - "\n", - "`map` is an abstraction to:\n", - "1. `put`\n", - "2. `wait`\n", - "3. `collect` (or `get`)\n", - "\n", - "In addition to using the verbose form, the example below also flips the priority for every-other-job." - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "metadata": {}, - "outputs": [ - { - "name": "stderr", - "output_type": "stream", - "text": [ - "100%|██████████| 18/18 [00:06<00:00, 2.78op/s]\n" - ] - }, - { - "data": { - "image/png": "iVBORw0KGgoAAAANSUhEUgAAAqYAAAGuCAYAAABCwMRvAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjUuMCwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy8/fFQqAAAACXBIWXMAAA9hAAAPYQGoP6dpAAA5FklEQVR4nO3deXSU1f3H8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uwW+3ataNfAMABn3zyiaZNmxbf0m/SpImuu+46jR492uXKKioqKtJNN92kadOmqVWrVpo7d64uuugiffTRR2rTpo0kadWqVerevbsefPBB+Xw+NWvWrMo8Bw8e1HnnnSev16tFixapcePGmjVrls4991y988476tixY/y53zRf3759tXDhQk2cOFG5ubnxne9AIKAxY8boscce04wZM+LfV8XFxVq9erUefPDBVL1NCSUdTI8cOaLx48frqaeeksfjkWVZ+v73v6927drpjjvuUNeuXfWb3/wmFbUCAIATWJcuXfTf//5X3bp1i4/t3LlTXbp0ca+oBIqLi7Vy5UpdcMEFkqRBgwapY8eOeuCBBzRnzhxJX51M/fe//z1hIC2Tm5urnTt36v3339dpp50Wn6tTp06aP3++7rvvvvhzv2m+li1bqmfPnpK+urXrmWeeGX9s/Pjx+s1vfqN169bpBz/4gaSvTiLzer36yU9+Uot3InlJL+NMnjxZGzZs0N/+9jd9+eWXsu3/nZzxwx/+UM8//7yjBQIAAEhSr169NH36dD366KN69tln9eijj2ratGnq2bOnnn/++fgft5100knxUFr28/e+9z29/vrr8bHzzjvva0OpJG3atEmnn356PJRKUigU0uDBg5WXV/EwuOrMdzzf+ta3dN5552np0qXxsdzcXI0cOVItW7as0Zw1lfSK6dNPP63f/va3GjJkiGKxWIXHunTpoh07djhVGwAAQNwHH3ygjh07atu2bdq2bZskqVOnTtq6dau2bt0af973v/99t0qUpIQnYrVt21YFBQUVfv4mBw4cSPi8tm3b6r333qsyVhvXX3+9xowZo3379qmwsFD//ve/df/999dqzppIOpgeOnRImZmZCR87fPhwrQsCAABIpPLJOaZKdPepzz//vEJ+qs45GaFQqELgLj9XKBSqMFbby1hedtlluvnmm/X4449r27Zt6tatmwYNGlSrOWsi6a383r17a9WqVQkfW7t2bYVjFgAAAE40X3zxhTZs2FDh55deeinpmxDl5OTo3XffrRBODxw4oJdeekk5OclfAzwYDEqSSkpKqjzWqFEjXX311VqyZImWL1+usWPHunLN9qSD6dSpU/Xoo4/q6quv1tq1a+XxeLR582ZNmTJFS5cu1a9//etU1AkAAE5w06dPrzJmymWiyguFQrruuuv02GOP6dlnn9UPfvAD2bYdvzFRdY0dO1adO3fW0KFD9eSTT+qvf/2rhgwZIr/fn/RcktSjRw/5fD4tXbpUr732mt54440Kj19//fX6z3/+o3A4rDFjxiQ9vxOSDqZlb05eXp5GjBgh27Z10003acWKFXriiSd04YUXpqJOAABwguvVq1eVsbIzzU2SmZmpBQsWaO7cubr88stVUlKidevWJX0caIsWLbRx40b16dNHEyZM0FVXXaVWrVrp5ZdfrnCpqOrKyMjQwoUL9c9//lMDBw6scD1T6av3skePHhoyZIjat2+f9PxO8NjlT6tP0ocffqh9+/YpFApVuBOU2958803169dPW7ZsUd++fR2b17Is7d7NdSkrq+0F9hsq+qUqeiUxeiUx+iWxhtwvn332mR555BENHDhQaWlptZorHA5r06ZNdX5f+LIL7Fc+Oak++OSTT9S9e3etXLlSP/rRj1ypoVY3lO3Ro4d69OjhVC0AAACoY/v379fWrVt1zz33qHPnzho+fLhrtVQrmN5zzz1JTXrXXXfVqBgAAADUreeee07jxo1T9+7d9fjjj8vvr9W6Za1U65UfeOCBCj9HIhEdPXpUktS4ceP42V1NmjRRo0aNCKYAAOCEtGzZMrdLSNqYMWNcO9mpsmoF0wMHDsT//sYbb2jUqFGaOnWqRo4cqRYtWujgwYNauXKlZs6cqRUrViRdxJo1a7Rhwwbt2LFDZ599tqZMmRJ/bOfOnXrooYe0Y8cOtW3bVhMmTFCfPn2Sfg0AAIBU2bJlS0rm7devX0rmNVXSa7WTJk3SlClTNHbs2PhYixYtNG7cOB09elQTJ07U5s2bk5ozFApp1KhReuutt3Tw4MH4eDQa1YwZMzRkyBDNmTNHr732mubMmaNFixbV+qBoAABQ/+zfv18bN27U3r171aZNG51//vlq1aqV22XBIUkH07fffltdu3ZN+Fi3bt1qdBbaOeecI0natm1bhWD67rvv6tixYxo5cqS8Xq8GDhyo5557Tq+88oqGDh2a9OsAAID665NPPtE999yjvn37atOmTfrud7+rVatWadq0aerevbvb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xW5y7Zt3Xjjjfrss8+0bt26Gt3kxjRJr5h++umn6t27t376059q69at8nq92rp1q37605+qT58++vTTT1NRJwAAOMF17dpVrVu3rjDWunVrnXzyyS5V5B7btjVx4kS99dZb+vvf/95g7rqZ9Irp7bffLkn6z3/+o1NOOSU+vnXrVl188cX62c9+pqeeesq5CgEAACStX79e559/fsLbPL/99ts6ePCgcnJyXKhMeuONLZJScUvSxMeuTpo0Sa+99prWr1+vli1bOvaabkt6xfTFF1/U7NmzK4RSSTrllFM0Y8YMvfDCC44VBwAAUOZ3v/udYrFYwscOHTqkZ599to4rcsfOnTv18MMP6z//+Y86duyo5s2bq3nz5po9e7bbpdVa0ium0WhUTZo0SfhYkyZNjtswAAAAteHxeLRhwwb5/VXjS3FxsbZv3+5CVXWvc+fODfamAkkH0+zsbM2cOVODBg3SSSedFB//4osvNGvWLGVnZztaIAAAQJkXX3wx4Va+pOPeMh31R9LB9L777tO5556rjh076oILLlDbtm21Z88erV+/XoFAQEuXLk1FnQAAAJozZ06VM/PRcCQdTE8//XS9/fbbeuCBB5SXl6f3339foVBI119/vW677TZ16NAhFXUao7S0VJFI5Li/rZ2IbNtWNBqVZVkN4lIVTrEsi36phF5JzOleyc8POlCV+2xbisU88vkkJ9qlf//IcR8LBhvGe9bQ9erVi8+OBq5G1zHt2LGj7r//fqdrqRfC4bD8fj//Y5Rj27ZisZh8Ph/vSzm2bdMvldAriTndKzk5WQ5UZQKPavg1lVBh4b7jPpaV1VDes4Zt1qxZbpeAFKvW//G9e/fW8uXLdfrpp+vb3/72135wejwehUIhDRgwQL/4xS8UCoUcKxYAAJzYjh07pmeeeUa9e/dWr1693C4HDqtWMO3Xr1/8jk79+vX7xt/oDx48qEcffVRbt27VX//611oXaZK0tDSlp6ezNVtO2fYsK4MVWZalaDRKv5RDryTmdK/k5TlQlAGcXmHPyMhwoCq47ejRo1q9erVef/11nXzyyRozZoxR1/H86tqjqKlqBdPc3Nz435ctW1atiVevXq2rr766RkWZLBAIKBgME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V+7tChgwoKCiqMvfjii9V6jaNHj0r632qlJP3rX//Sjh07KjwvGAzq2LFj3zhfTk6O3n333Qrh9MCBA3rppZeUk5NTrZoAAO4imAJI6Ne//rU2bdqksWPHat26dZo9e7b+9Kc/VXjOyJEjtXLlSv3ud7/TunXrdPXVV6uwsLBa85911llq3ry5Jk6cqBdeeEG5ubm64oor1L59+wrPO+200xSNRvXggw8qPz8/4aqoJI0dO1adO3fW0KFD9eSTT+qvf/2rhgwZIr/fr1tvvbVG7wEAoG4RTAEkdMkll2jRokVav369RowYoRdeeEErVqyo8JypU6fqyiuv1PTp0zV69Gh17txZt9xyS7Xmb9u2rVauXKk9e/Zo+PDhmj9/vhYvXqxvfetbFZ43bNgw3XTTTZozZ46++93v6oYbbkg4X4sWLbRx40b16dNHEyZM0FVXXaVWrVrp5ZdfrnCpKACAuTy2bdtuFwEAAACwYgoAAAAjEEwBAABgBIIpAAAAjEAwBQAAgBEIpgAAADACwRQAAABGIJgCAADACARTAAAAGIFgCgAAACMQTAEAAGAEgikAAACM8P+FwDpRWONpwAAAAABJRU5ErkJggg==", - "text/plain": [ - "
" - ] - }, - "metadata": {}, - "output_type": "display_data" - }, - { - "data": { - "text/plain": [ - "" - ] - }, - "execution_count": 7, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "with ezpq.Queue(\n", - " max_concurrent=3,\n", - " engine=threading.Thread, # or `mp.Process`\n", - " show_progress=True\n", - ") as queue:\n", - "\n", - " # put.\n", - " for i in range(18):\n", - " queue.put(time.sleep, 1, priority=(i%2)+1)\n", - " \n", - " # wait.\n", - " queue.wait()\n", - "\n", - " # collect.\n", - " finished = queue.collect()\n", - "\n", - "# plot.\n", - "ezpq.Plot(finished).build(color_by='priority', color_pal=['green', 'blue'])" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "For more examples, view the [tests](tests/EzpqTestCases.py) and docstrings." - ] - } - ], - "metadata": { - "interpreter": { - "hash": "a49d25a860b5c22e587205228cb454744141d023fc8acca5ae0eaeb9b6ed2d85" - }, - "kernelspec": { - "display_name": "Python 3 (ipykernel)", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.9.7" - } - }, - "nbformat": 4, - "nbformat_minor": 4 -} diff --git a/README.md b/README.md index e477cea..c7c470c 100644 --- a/README.md +++ b/README.md @@ -1,198 +1,61 @@ -# ezpq +# ppqueue -> None +> Parallel Process Queue (ppqueue) for Python + +> Formerly known as `ezpq` | Links | | |---------------|------------------------| -| Code Repo | https://www.github.com/fresh2dev/ezpq | -| Mirror Repo | https://www.Fresh2.dev/code/r/ezpq | -| Documentation | https://www.Fresh2.dev/code/r/ezpq/i | -| Changelog | https://www.Fresh2.dev/code/r/ezpq/i/changelog | -| License | https://www.Fresh2.dev/code/r/ezpq/i/license | +| Code Repo | https://www.github.com/fresh2dev/ppqueue | +| Mirror Repo | https://www.Fresh2.dev/code/r/ppqueue | +| Documentation | https://www.Fresh2.dev/code/r/ppqueue/i | +| Changelog | https://www.Fresh2.dev/code/r/ppqueue/i/changelog | +| License | https://www.Fresh2.dev/code/r/ppqueue/i/license | | Funding | https://www.Fresh2.dev/funding | -[![GitHub release (latest SemVer)](https://img.shields.io/github/v/release/fresh2dev/ezpq?color=blue&style=for-the-badge)](https://www.github.com/fresh2dev/ezpq/releases) -[![GitHub Release Date](https://img.shields.io/github/release-date/fresh2dev/ezpq?color=blue&style=for-the-badge)](https://www.github.com/fresh2dev/ezpq/releases) -[![License](https://img.shields.io/github/license/fresh2dev/ezpq?color=blue&style=for-the-badge)](https://www.Fresh2.dev/code/r/ezpq/i/license) -[![GitHub issues](https://img.shields.io/github/issues-raw/fresh2dev/ezpq?color=blue&style=for-the-badge)](https://www.github.com/fresh2dev/ezpq/issues) -[![GitHub pull requests](https://img.shields.io/github/issues-pr-raw/fresh2dev/ezpq?color=blue&style=for-the-badge)](https://www.github.com/fresh2dev/ezpq/pulls) -[![GitHub Repo stars](https://img.shields.io/github/stars/fresh2dev/ezpq?color=blue&style=for-the-badge)](https://star-history.com/#fresh2dev/ezpq&Date) -[![PyPI - Downloads](https://img.shields.io/pypi/dm/ezpq?color=blue&style=for-the-badge)](https://pypi.org/project/ezpq) -[![Docker Pulls](https://img.shields.io/docker/pulls/fresh2dev/ezpq?color=blue&style=for-the-badge)](https://hub.docker.com/r/fresh2dev/ezpq) -[![Docs Website](https://img.shields.io/website?down_message=unavailable&label=docs&style=for-the-badge&up_color=blue&up_message=available&url=https://www.Fresh2.dev/code/r/ezpq/i)](https://www.Fresh2.dev/code/r/ezpq/i) -[![Coverage Website](https://img.shields.io/website?down_message=unavailable&label=coverage&style=for-the-badge&up_color=blue&up_message=available&url=https://www.Fresh2.dev/code/r/ezpq/i/tests/coverage)](https://www.Fresh2.dev/code/r/ezpq/i/tests/coverage) +[![GitHub release (latest SemVer)](https://img.shields.io/github/v/release/fresh2dev/ppqueue?color=blue&style=for-the-badge)](https://www.github.com/fresh2dev/ppqueue/releases) +[![GitHub Release Date](https://img.shields.io/github/release-date/fresh2dev/ppqueue?color=blue&style=for-the-badge)](https://www.github.com/fresh2dev/ppqueue/releases) +[![License](https://img.shields.io/github/license/fresh2dev/ppqueue?color=blue&style=for-the-badge)](https://www.Fresh2.dev/code/r/ppqueue/i/license) +[![GitHub issues](https://img.shields.io/github/issues-raw/fresh2dev/ppqueue?color=blue&style=for-the-badge)](https://www.github.com/fresh2dev/ppqueue/issues) +[![GitHub pull requests](https://img.shields.io/github/issues-pr-raw/fresh2dev/ppqueue?color=blue&style=for-the-badge)](https://www.github.com/fresh2dev/ppqueue/pulls) +[![GitHub Repo stars](https://img.shields.io/github/stars/fresh2dev/ppqueue?color=blue&style=for-the-badge)](https://star-history.com/#fresh2dev/ppqueue&Date) +[![PyPI - Downloads](https://img.shields.io/pypi/dm/ppqueue?color=blue&style=for-the-badge)](https://pypi.org/project/ppqueue) +[![Docs Website](https://img.shields.io/website?down_message=unavailable&label=docs&style=for-the-badge&up_color=blue&up_message=available&url=https://www.Fresh2.dev/code/r/ppqueue/i)](https://www.Fresh2.dev/code/r/ppqueue/i) +[![Coverage Website](https://img.shields.io/website?down_message=unavailable&label=coverage&style=for-the-badge&up_color=blue&up_message=available&url=https://www.Fresh2.dev/code/r/ppqueue/i/tests/coverage)](https://www.Fresh2.dev/code/r/ppqueue/i/tests/coverage) [![Funding](https://img.shields.io/badge/funding-%24%24%24-blue?style=for-the-badge)](https://www.Fresh2.dev/funding) -*Brought to you by...* - - - ---- - -> easy parallel queue ## Overview -`ezpq` is a Python module that serves as an abstraction layer to both `multiprocessing.Process` and `threading.Thread` that offers: -- a unified API for parallel processing using multiprocessing or threading. -- FIFO priority queueing. -- methods for generating plots. -- `tqdm` integration for progress-bars. -- error-handling, logging. -- cross-platform compatibility. - -This project is: -- free, open-source -- **fun**ctional -- interesting -- all I need it to be +`ppqueue` is a Python module that serves as an abstraction layer to both `multiprocessing.Process` and `threading.Thread`. I built `ppqueue` because I too often notice that parallelizing code results in *ugly* code. With this simple Queue, you can parallelize code easily and attractively. ppqueue offers: -This project is **not**: -- production-ready -- super-clean -- thoroughly documented +- a single API for parallel execution using processes or threads. +- FIFO priority queueing. +- Gantt charts of job execution (thanks `plotnine` + `pandas`) +- progress bars (thanks to `tqdm`) -Bug reports and MRs are welcome, though I don't imagine any major enhancements; just enough to keep tests passing. +![](https://img.fresh2.dev/1687407526_84b23a13b5f.svg) ## Install -From PyPi: `pip install ezpq[plot]` - -From source: `git clone ... && pip install .` - -Run tests from source: `make test` - -Build this README with Jupyter: `make builddocs` - -## Examples - -> imports. - - -```python -import ezpq -import threading -import multiprocessing as mp -import time -``` - -> minimal example. - -3 workers, 18 jobs, each job takes 1 second: - - -```python -with ezpq.Queue( - workers=3, - engine=threading.Thread, # or `mp.Process` - show_progress=True -) as queue: - - # put, wait, collect. - finished = queue.map(time.sleep, [1] * 18, show_progress=True) - -# plot. -ezpq.Plot(finished).build() -``` - - - 0%| | 0/18 [00:00 - - - -> minimal example with decorator. - -Same as above, but using the @decorator interface. - - -```python -# define. -@ezpq.Queue( - workers=3, - engine=threading.Thread, # or `mp.Process` - show_progress=True -) -def time_sleep(x): - time.sleep(x) - -# call and collect. -finished = time_sleep([1] * 18) - -# plot. -ezpq.Plot(finished).build() -``` - - - 0%| | 0/18 [00:00 - - - -> verbose form. - -`map` is an abstraction to: -1. `put` -2. `wait` -3. `collect` (or `get`) - -In addition to using the verbose form, the example below also flips the priority for every-other-job. - +Install from PyPi: ```python -with ezpq.Queue( - workers=3, - engine=threading.Thread, # or `mp.Process` - show_progress=True -) as queue: - - # put. - for i in range(18): - queue.put(time.sleep, 1, priority=(i%2)+1) - - # wait. - queue.wait() - - # collect. - finished = queue.collect() - -# plot. -ezpq.Plot(finished).build(color_by='priority', color_pal=['green', 'blue']) +pip install ppqueue[plot] ``` +## Examples - 0%| | 0/18 [00:00 + \ No newline at end of file diff --git a/README_files/README_4_1.png b/README_files/README_4_1.png deleted file mode 100644 index bab1101..0000000 Binary files a/README_files/README_4_1.png and /dev/null differ diff --git a/README_files/README_6_1.png b/README_files/README_6_1.png deleted file mode 100644 index 1f6b71e..0000000 Binary files a/README_files/README_6_1.png and /dev/null differ diff --git a/README_files/README_8_1.png b/README_files/README_8_1.png deleted file mode 100644 index 0a6ccd4..0000000 Binary files a/README_files/README_8_1.png and /dev/null differ diff --git a/config/mkdocs.yml b/config/mkdocs.yml index 71d7318..103160f 100644 --- a/config/mkdocs.yml +++ b/config/mkdocs.yml @@ -1,8 +1,8 @@ -site_name: "ezpq" -site_description: "ezpq Docs" -site_url: !ENV [MKDOCS_SITE_URL, "https://www.Fresh2.dev/code/r/ezpq/i"] -repo_url: "https://www.github.com/fresh2dev/ezpq" -repo_name: "fresh2dev/ezpq" +site_name: "ppqueue" +site_description: "ppqueue Docs" +site_url: !ENV [MKDOCS_SITE_URL, "https://www.Fresh2.dev/code/r/ppqueue/i"] +repo_url: "https://www.github.com/fresh2dev/ppqueue" +repo_name: "fresh2dev/ppqueue" edit_uri: "edit/main/docs" #edit_uri_template: "src/branch/main/docs/{path}" docs_dir: "../docs" @@ -19,11 +19,12 @@ extra: ## https://www.mkdocs.org/user-guide/writing-your-docs/#configure-pages-and-navigation nav: - Home: index.md - - Changelog: changelog.md - - License: license.md - Articles: - - 'page/quickstart.md' + - Examples: 'page/examples.ipynb' + - 'page/related.md' - Reference: reference/ + - Changelog: changelog.md + - License: license.md - Discussion: comments.md watch: @@ -34,13 +35,14 @@ theme: language: en custom_dir: overrides palette: + # https://squidfunk.github.io/mkdocs-material/setup/changing-the-colors/#primary-color - scheme: slate - primary: deep purple + primary: green toggle: icon: material/toggle-switch-off-outline name: Switch to light mode - scheme: default - primary: deep purple + primary: green toggle: icon: material/toggle-switch name: Switch to dark mode @@ -83,6 +85,13 @@ plugins: - search - include_dir_to_nav - autorefs + - mkdocs-jupyter: + ignore_h1_titles: True + include_source: True + execute: false + remove_tag_config: + remove_input_tags: + - hidden - mkdocstrings: default_handler: python handlers: @@ -91,7 +100,7 @@ plugins: options: show_bases: false show_source: false - members_order: 'source' # 'alphabetical' + members_order: 'alphabetical' # 'source' docstring_style: google show_submodules: false show_signature: false diff --git a/config/overrides/main.html b/config/overrides/main.html index 6e5fa8e..08df8bc 100644 --- a/config/overrides/main.html +++ b/config/overrides/main.html @@ -31,3 +31,13 @@ {% endblock %} + +{% block content %} +{% if page.nb_url %} + + {% include ".icons/material/download.svg" %} + +{% endif %} + +{{ super() }} +{% endblock content %} diff --git a/docs/page/.gitkeep b/docs/page/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/docs/page/examples.ipynb b/docs/page/examples.ipynb new file mode 100644 index 0000000..4175f79 --- /dev/null +++ b/docs/page/examples.ipynb @@ -0,0 +1,888 @@ +{ + "cells": [ + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# `ppqueue` Examples\n", + "\n", + "![](https://img.fresh2.dev/1687407526_84b23a13b5f.svg)" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Install\n", + "\n", + "Install from PyPi:\n", + "\n", + "```python\n", + "pip install ppqueue[plot]\n", + "```" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## enqueue, wait, dequeue\n", + "\n", + "ppqueue runs parallel processes (or threads) using a Queue:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "tags": [ + "hidden" + ] + }, + "outputs": [], + "source": [ + "%reset -f" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "data": { + "application/vnd.jupyter.widget-view+json": { + "model_id": "03219a2669274d82a8633031ca9510e8", + "version_major": 2, + "version_minor": 0 + }, + "text/plain": [ + " 0%| | 0/18 [00:00" + ] + }, + "metadata": { + "image/png": { + "height": 480, + "width": 640 + } + }, + "output_type": "display_data" + }, + { + "data": { + "text/plain": [ + "
" + ] + }, + "execution_count": 2, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "from ppqueue import Queue\n", + "from ppqueue.plot import plot_jobs\n", + "\n", + "\n", + "from time import sleep\n", + "\n", + "\n", + "def slowly_square(value: int, sleep_for: float) -> int:\n", + " sleep(sleep_for)\n", + " return value * value\n", + "\n", + "\n", + "with Queue(max_concurrent=3, show_progress=True) as queue:\n", + " # enqueue\n", + " for i in range(18):\n", + " queue.enqueue(slowly_square, [i, 1])\n", + " # OR: queue.put(slowly_square, ...)\n", + "\n", + " # wait\n", + " queue.wait()\n", + "\n", + " # dequeue\n", + " jobs = [queue.dequeue() for _ in range(queue.size())]\n", + " # OR: jobs = [queue.pop() for _ in range(queue.size())]\n", + " # OR: jobs = list(job for job in queue)\n", + " # OR: jobs = queue.collect()\n", + "\n", + "print([job.result for job in jobs])\n", + "\n", + "# plot.\n", + "plot_jobs(jobs, no_legend=True)" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## priority, group\n", + "\n", + "ppqueue makes it easy to process jobs in priority-order. If jobs share the same priority value, then priority is given to the one that entered the queue first." + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": { + "tags": [ + "hidden" + ] + }, + "outputs": [], + "source": [ + "%reset -f" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "data": { + "application/vnd.jupyter.widget-view+json": { + "model_id": "6b541414c14a47e1816f549b37734e3d", + "version_major": 2, + "version_minor": 0 + }, + "text/plain": [ + " 0%| | 0/18 [00:00" + ] + }, + "metadata": { + "image/png": { + "height": 480, + "width": 640 + } + }, + "output_type": "display_data" + }, + { + "data": { + "text/plain": [ + "
" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "from ppqueue import Queue\n", + "from ppqueue.plot import plot_jobs, PlotColorBy\n", + "\n", + "\n", + "from time import sleep\n", + "\n", + "\n", + "with Queue(max_concurrent=3, show_progress=True) as queue:\n", + " # put.\n", + " for i in range(18):\n", + " priority = int(i % 2 == 0) # 0 has priority over 1\n", + " queue.enqueue(sleep, [1], priority=priority)\n", + "\n", + " # wait.\n", + " queue.wait()\n", + "\n", + " # collect.\n", + " jobs = list(job for job in queue)\n", + " # OR: jobs = [queue.dequeue() for _ in range(queue.size())]\n", + " # OR: jobs = [queue.pop() for _ in range(queue.size())]\n", + " # OR: jobs = queue.collect()\n", + "\n", + "# plot.\n", + "plot_jobs(\n", + " jobs,\n", + " color_by=PlotColorBy.PRIORITY,\n", + " color_pal=[\"red\", \"blue\"],\n", + ")" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "You can define various \"groups\", where priority/order is respective to the group." + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": { + "tags": [ + "hidden" + ] + }, + "outputs": [], + "source": [ + "%reset -f" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "data": { + "application/vnd.jupyter.widget-view+json": { + "model_id": "5400afcc25a54ee0a71decdf5b083d2b", + "version_major": 2, + "version_minor": 0 + }, + "text/plain": [ + " 0%| | 0/18 [00:00" + ] + }, + "metadata": { + "image/png": { + "height": 480, + "width": 640 + } + }, + "output_type": "display_data" + }, + { + "data": { + "text/plain": [ + "
" + ] + }, + "execution_count": 6, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "from ppqueue import Queue\n", + "from ppqueue.plot import plot_jobs, PlotColorBy\n", + "\n", + "\n", + "from time import sleep\n", + "\n", + "\n", + "with Queue(max_concurrent=3, show_progress=True) as queue:\n", + " # put.\n", + " for i in range(18):\n", + " group = int(i % 2 == 0) # Odds grouped with odds; evens with evens.\n", + " queue.enqueue(sleep, [1], group=group)\n", + "\n", + " # wait.\n", + " queue.wait()\n", + "\n", + " # collect.\n", + " jobs = list(job for job in queue)\n", + " # OR: jobs = [queue.dequeue() for _ in range(queue.size())]\n", + " # OR: jobs = queue.collect()\n", + "\n", + "# plot.\n", + "plot_jobs(\n", + " jobs,\n", + " color_by=PlotColorBy.GROUP,\n", + " color_pal=[\"red\", \"blue\"],\n", + ")" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## map, starmap, starmapkw, decorator\n", + "\n", + "ppqueue offers `map`, which is similar to the built-in `map()` function and the `multiprocessing.Pool.map()` function.\n", + "\n", + "`map` runs the function for each item in the iterable (`enqueue`), waits until all jobs are complete (`wait`), and returns the results (`dequeue`).\n", + "\n", + "For example, given 3 workers, 18 jobs, each job taking 1 second:" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": { + "tags": [ + "hidden" + ] + }, + "outputs": [], + "source": [ + "%reset -f" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "data": { + "application/vnd.jupyter.widget-view+json": { + "model_id": "4cc69989609c4260b2334c7a2d971726", + "version_major": 2, + "version_minor": 0 + }, + "text/plain": [ + " 0%| | 0/18 [00:00" + ] + }, + "metadata": { + "image/png": { + "height": 480, + "width": 640 + } + }, + "output_type": "display_data" + }, + { + "data": { + "text/plain": [ + "
" + ] + }, + "execution_count": 8, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "from ppqueue import Queue\n", + "from ppqueue.plot import plot_jobs\n", + "\n", + "\n", + "from time import sleep\n", + "\n", + "\n", + "def slowly_square(value: int, sleep_for: float = 1) -> int:\n", + " sleep(sleep_for)\n", + " return value * value\n", + "\n", + "\n", + "with Queue(max_concurrent=3, show_progress=True) as queue:\n", + " # enqueue, wait, dequeue\n", + " jobs = queue.map(slowly_square, range(18))\n", + "\n", + "print([job.result for job in jobs])\n", + "\n", + "# plot.\n", + "plot_jobs(jobs, no_legend=True)" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Provide multiple arguments with `starmap`:" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": { + "tags": [ + "hidden" + ] + }, + "outputs": [], + "source": [ + "%reset -f" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [ + { + "data": { + "application/vnd.jupyter.widget-view+json": { + "model_id": "476def9424f74975adab6803874e63ea", + "version_major": 2, + "version_minor": 0 + }, + "text/plain": [ + " 0%| | 0/18 [00:00" + ] + }, + "metadata": { + "image/png": { + "height": 480, + "width": 640 + } + }, + "output_type": "display_data" + }, + { + "data": { + "text/plain": [ + "
" + ] + }, + "execution_count": 10, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "from ppqueue import Queue\n", + "from ppqueue.plot import plot_jobs\n", + "\n", + "\n", + "from time import sleep\n", + "\n", + "\n", + "def slowly_square(value: int, sleep_for: float) -> int:\n", + " sleep(sleep_for)\n", + " return value * value\n", + "\n", + "\n", + "with Queue(max_concurrent=3, show_progress=True) as queue:\n", + " # enqueue, wait, dequeue\n", + " jobs = queue.starmap(slowly_square, [(i, 1) for i in range(18)])\n", + "\n", + "print([job.result for job in jobs])\n", + "\n", + "# plot.\n", + "plot_jobs(jobs, no_legend=True)" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Provide multiple *keyword* arguments with `starmapkw`:" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": { + "tags": [ + "hidden" + ] + }, + "outputs": [], + "source": [ + "%reset -f" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "data": { + "application/vnd.jupyter.widget-view+json": { + "model_id": "73b77d7211a84cb98311cedcbf69a224", + "version_major": 2, + "version_minor": 0 + }, + "text/plain": [ + " 0%| | 0/18 [00:00" + ] + }, + "metadata": { + "image/png": { + "height": 480, + "width": 640 + } + }, + "output_type": "display_data" + }, + { + "data": { + "text/plain": [ + "
" + ] + }, + "execution_count": 12, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "from ppqueue import Queue\n", + "from ppqueue.plot import plot_jobs\n", + "\n", + "\n", + "from time import sleep\n", + "\n", + "\n", + "def slowly_square(value: int, sleep_for: float) -> int:\n", + " sleep(sleep_for)\n", + " return value * value\n", + "\n", + "\n", + "with Queue(max_concurrent=3, show_progress=True) as queue:\n", + " # enqueue, wait, dequeue\n", + " jobs = queue.starmapkw(\n", + " slowly_square,\n", + " [{\"value\": i, \"sleep_for\": 1} for i in range(18)],\n", + " )\n", + "\n", + "print([job.result for job in jobs])\n", + "\n", + "# plot.\n", + "plot_jobs(jobs, no_legend=True)" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "You can also use the `@Queue` decorator for this sorta thing:" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": { + "tags": [ + "hidden" + ] + }, + "outputs": [], + "source": [ + "%reset -f" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [ + { + "data": { + "application/vnd.jupyter.widget-view+json": { + "model_id": "fbc57ed15e2941569411ecef628b8d5d", + "version_major": 2, + "version_minor": 0 + }, + "text/plain": [ + " 0%| | 0/18 [00:00" + ] + }, + "metadata": { + "image/png": { + "height": 480, + "width": 640 + } + }, + "output_type": "display_data" + }, + { + "data": { + "text/plain": [ + "
" + ] + }, + "execution_count": 14, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "from ppqueue import Queue\n", + "from ppqueue.plot import plot_jobs\n", + "\n", + "from time import sleep\n", + "\n", + "\n", + "@Queue(max_concurrent=3, show_progress=True)\n", + "def sleep_foreach(x: float):\n", + " sleep(x)\n", + "\n", + "\n", + "# call and collect.\n", + "jobs = sleep_foreach([1] * 18)\n", + "\n", + "# plot.\n", + "plot_jobs(jobs, no_legend=True)" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Threads and Processes\n", + "\n", + "It's easy to use processes (`mp.Process`) or threads (`threading.Thread`)." + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": { + "tags": [ + "hidden" + ] + }, + "outputs": [], + "source": [ + "%reset -f" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": {}, + "outputs": [ + { + "data": { + "application/vnd.jupyter.widget-view+json": { + "model_id": "1a6ebab06c3f426da9089375108d0617", + "version_major": 2, + "version_minor": 0 + }, + "text/plain": [ + " 0%| | 0/18 [00:00" + ] + }, + "metadata": { + "image/png": { + "height": 480, + "width": 640 + } + }, + "output_type": "display_data" + }, + { + "data": { + "text/plain": [ + "
" + ] + }, + "execution_count": 16, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "from ppqueue import Queue\n", + "from ppqueue.plot import plot_jobs, PlotColorBy\n", + "\n", + "from threading import Thread\n", + "from multiprocessing import Process\n", + "from time import sleep\n", + "\n", + "\n", + "def slowly_square(value: int, sleep_for: float = 1) -> int:\n", + " sleep(sleep_for)\n", + " return value * value\n", + "\n", + "\n", + "with Queue(\n", + " max_concurrent=3,\n", + " show_progress=True,\n", + " engine=Thread,\n", + " name=\"Thread Queue\",\n", + ") as queue:\n", + " thread_jobs = queue.map(slowly_square, range(18))\n", + "\n", + "with Queue(\n", + " max_concurrent=3,\n", + " show_progress=True,\n", + " engine=Process,\n", + " name=\"Process Queue\",\n", + ") as queue:\n", + " process_jobs = queue.map(slowly_square, range(18))\n", + "\n", + "print([job.result for job in thread_jobs])\n", + "print([job.result for job in process_jobs])\n", + "\n", + "# plot.\n", + "plot_jobs(\n", + " thread_jobs,\n", + " process_jobs,\n", + " color_by=PlotColorBy.QID,\n", + " color_pal=[\"red\", \"blue\"],\n", + ")" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## More Examples\n", + "\n", + "More examples can be found in the reference docs:\n", + "\n", + "https://www.f2dv.com/code/r/ppqueue/i/reference/" + ] + }, + { + "attachments": {}, + "cell_type": "markdown", + "metadata": {}, + "source": [] + } + ], + "metadata": { + "interpreter": { + "hash": "a49d25a860b5c22e587205228cb454744141d023fc8acca5ae0eaeb9b6ed2d85" + }, + "kernelspec": { + "display_name": "ppqueue", + "language": "python", + "name": "ppqueue" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.8.16" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/docs/page/related.md b/docs/page/related.md new file mode 100644 index 0000000..f27fa71 --- /dev/null +++ b/docs/page/related.md @@ -0,0 +1 @@ +# Related Projects diff --git a/docs/reference/01.md b/docs/reference/01.md index 31d67ba..391e448 100644 --- a/docs/reference/01.md +++ b/docs/reference/01.md @@ -1,2 +1,2 @@ -# ezpq -::: ezpq +# ppqueue.Queue +::: ppqueue.Queue diff --git a/docs/reference/02.md b/docs/reference/02.md new file mode 100644 index 0000000..23b4d0a --- /dev/null +++ b/docs/reference/02.md @@ -0,0 +1,2 @@ +# ppqueue.Job +::: ppqueue.Job diff --git a/docs/reference/03.md b/docs/reference/03.md new file mode 100644 index 0000000..e5f17a0 --- /dev/null +++ b/docs/reference/03.md @@ -0,0 +1,2 @@ +# ppqueue.plot +::: ppqueue.plot diff --git a/pyproject.toml b/pyproject.toml index ed237b6..74c849f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -3,11 +3,11 @@ requires = ["setuptools>=64", "build==0.*", "wheel==0.*", "twine==4.*"] build-backend = "setuptools.build_meta" [project] -name = "ezpq" +name = "ppqueue" authors = [ {name = "Donald Mellenbruch", email = "hello@Fresh2.dev"}, ] -description = "None" +description = "Parallel Process Queue (ppqueue) for Python" readme = "README.md" license = {file = "LICENSE"} requires-python = ">=3.8" @@ -17,6 +17,7 @@ classifiers = [ dynamic = ["version"] dependencies = [ "typing-extensions; python_version<'3.10'", + "tqdm==4.*", ] [project.optional-dependencies] @@ -26,15 +27,19 @@ dev = [ "pylint-pytest==1.*", "mypy[reports]==0.*", "ruff==0.*", - "black==23.*", + "black[jupyter]==23.*", "isort==5.*", "bump2version==1.*", - "ipython", "pdbpp", + # python -m ipykernel install --user --name ppqueue + "ipykernel", + "ipywidgets", + "ipython", ] docs = [ "mkdocs==1.*", "mkdocs-material==9.*", + "mkdocs-jupyter==0.24.*", "mkdocstrings[python]==0.20.*", "mkdocs-autorefs==0.*", "mkdocs-include-dir-to-nav==1.*", @@ -51,22 +56,25 @@ tests = [ # "mockish==0.1.*", "tqdm==4.*", - "pandas==1.*", - "plotnine==0.10.*", + "pandas>=1,<=2", + "plotnine==0.*", ] plot = [ - "tqdm==4.*", - "pandas==1.*", - "plotnine==0.10.*", + "pandas>=1,<=2", + "plotnine==0.*", +] +extras = [ + "pandas>=1,<=2", + "plotnine==0.*", ] [project.urls] -Homepage = "https://www.Fresh2.dev/code/r/ezpq/i" -Repository = "https://www.github.com/fresh2dev/ezpq" +Homepage = "https://www.Fresh2.dev/code/r/ppqueue/i" +Repository = "https://www.github.com/fresh2dev/ppqueue" Funding = "https://www.Fresh2.dev/funding" [project.scripts] -ezpq = "ezpq.__main__:main" +ppqueue = "ppqueue.__main__:main" [tool.setuptools.package-data] "*" = ["**"] @@ -77,7 +85,7 @@ exclude = [] namespaces = false [tool.setuptools.dynamic] -version = {attr = "ezpq.__version__.__version__"} +version = {attr = "ppqueue.__version__.__version__"} [tool.pytest.ini_options] minversion = 7.0 @@ -114,7 +122,7 @@ warn_untyped_fields = true [tool.black] line-length = 88 -include = 'src\/.*\.pyi?$|tests\/.*\.pyi?$' +include = 'src\/.*\.pyi?$|tests\/.*\.pyi?|docs\/.*\.ipynb$' [tool.isort] profile = "black" diff --git a/setup.cfg b/setup.cfg deleted file mode 100644 index 6d80d2e..0000000 --- a/setup.cfg +++ /dev/null @@ -1,133 +0,0 @@ -[metadata] -name = ezpq -version = file: VERSION -description = None -long_description = file: README.md -long_description_content_type = text/markdown -author = Donald Mellenbruch -author_email = hello@Fresh2.dev -license_files = LICENSE -classifiers = - Programming Language :: Python :: 3 -url = https://www.github.com/fresh2dev/ezpq -project_urls = - Homepage = https://www.Fresh2.dev/code/r/ezpq/i - Repository = https://www.github.com/fresh2dev/ezpq - Funding = https://www.Fresh2.dev/funding -[options] -package_dir = - =src -packages = find: -python_requires = >=3.7 -install_requires = - typing-extensions; python_version<'3.10' - -[options.package_data] -* = ** - -[options.extras_require] -build = - setuptools>=62.3.0 - build==0.* - wheel==0.* - twine==4.* -docs = - mkdocs==1.* - mkdocs-material==9.* - mkdocstrings[python]==0.20.* - mkdocs-autorefs==0.* - mkdocs-include-dir-to-nav==1.* -dev = - python-lsp-server[rope]==1.* - pylint==2.* - pylint-pytest==1.* - mypy[reports]==0.* - ruff==0.* - black==23.* - isort==5.* - bump2version==1.* - ipython - pdbpp -tests = - pytest==7.* - pytest-cov==4.* - pytest-html==3.* - pytest-sugar==0.* - pytest-custom-exit-code==0.3.* - pylint==2.* - pylint-pytest==1.* - packaging==23.* - mockish==0.1.* -plot = - tqdm==4.62.3 - pandas==1.1.5 - plotnine==0.8.0 - -[options.packages.find] -where = src -exclude = - tests - -[options.entry_points] -console_scripts = - ezpq = ezpq.__main__:main - -[tool:pytest] -minversion = 7.0 -testpaths = - tests - -[mypy] -namespace_packages = True -explicit_package_bases = True -strict = True -plugins = pydantic.mypy -files = src/**/*.py -exclude = tests -[mypy-tests.*] -ignore_errors = True - -[pydantic-mypy] -init_forbid_extra = True -init_typed = True -warn_required_dynamic_aliases = True -warn_untyped_fields = True - -[isort] -profile = black -line_length = 88 -src_paths = src,tests -float_to_top = true -include_trailing_comma = true -honor_noqa = true - -[pylint.MASTER] -load-plugins = pylint_pytest -ignore-paths = ^\.git$, - ^\.venv$, - ^__pycache__$ -[pylint.FORMAT] -max-line-length = 88 -[pylint] -disable = - fixme, - invalid-name, - unnecessary-pass, - unnecessary-ellipsis, - too-few-public-methods, - import-outside-toplevel, - missing-module-docstring - -[tox:tox] -envlist = py3{7,8,9,10,11} -skip_missing_interpreters = false -toxworkdir = /tmp/.tox -minversion = 4.0 -requires = - setuptools>=62.3.0 -[testenv] -recreate = true -extras = tests -commands = - python -m pytest {posargs} - python -m pylint --disable=C,R ./src ./tests diff --git a/src/ezpq/FinishedJob.py b/src/ezpq/FinishedJob.py deleted file mode 100644 index ea8aeba..0000000 --- a/src/ezpq/FinishedJob.py +++ /dev/null @@ -1,62 +0,0 @@ -from datetime import datetime -from typing import Any, Mapping, Sequence - -from ezpq import utils -from ezpq.Job import Job - - -class FinishedJob(object): - # TODO: change sig to: (job: Job, end_time: int, cancelled: bool, output: str, exception: str, exitcode: int, callback_output) - def __init__(self, job: Job): - self.qid: str = job.qid - self.idx: int = job.idx - self.name: str = job.name - self.priority: int = job.priority - self.lane: int = job.lane - self.timeout: int = job.timeout - self.function: str = job.fun.__name__ - self.args: Sequence[Any] = job.args - self.kwargs: Mapping[str, Any] = job.kwargs - self.submitted: datetime = job.get_submit_time() - self.started: datetime = job.get_start_time() - self.ended: datetime = job.get_end_time() - self.processed: datetime = job.get_processed_time() - self.exitcode: int = job.exitcode - self.cancelled: bool = job._cancelled - self.runtime: float = job.running_time() - self.output: Any = job.output - self.exception: str = job.exception_txt - - # TODO: use a dedicated property name `callback_output` - self.callback: Any = job.callback - - def compare(self, job) -> int: - """compares two jobs by priority or index. - - Arguments: - job {ezpq.Job} - - Returns: - int -- `1` if `self` is greater than comparison, - `-1` if `self` is less than, - `0` if equal. - """ - return utils.compare_by(self, job, by=["priority", "idx"]) - - def __eq__(self, job): - return self.compare(job) == 0 - - def __ne__(self, job): - return self.compare(job) != 0 - - def __lt__(self, job): - return self.compare(job) < 0 - - def __le__(self, job): - return self.compare(job) <= 0 - - def __gt__(self, job): - return self.compare(job) > 0 - - def __ge__(self, job): - return self.compare(job) >= 0 diff --git a/src/ezpq/Job.py b/src/ezpq/Job.py deleted file mode 100644 index 10225f4..0000000 --- a/src/ezpq/Job.py +++ /dev/null @@ -1,261 +0,0 @@ -import logging as log -import time -from datetime import datetime -from typing import Any, Callable, Mapping, Optional, Sequence - -from ezpq import utils - - -class Job: - """used internally in `ezpq.Queue`. - defines what to run, with what priority, and other options. - """ - - def __init__( - self, - fun: Callable, - args: Sequence[Any] = None, - kwargs: Mapping[str, Any] = None, - name: Optional[str] = None, - priority: Optional[int] = 100, - lane: Optional[int] = None, - timeout: Optional[int] = 0, - suppress_errors: Optional[bool] = False, - skip_on_lane_error: Optional[bool] = False, - ): - """ - Required Arguments: - fun {Callable} - - Keyword Arguments: - args {Sequence[Any]} -- (default: {None}) - kwargs {Mapping[str, Any]} -- (default: {None}) - name {Optional[str]} -- (default: {None}) - priority {Optional[int]} -- (default: {100}) - lane {Optional[int]} -- (default: {None}) - suppress_errors {Optional[bool]} -- (default: {False}) - skip_on_lane_error {Optional[bool]} -- (default: {False}) - """ - self._qid = None # automatically assigned during processing. - self._idx = None # automatically assigned during processing. - self.name = name - self.lane = lane - self.timeout = timeout - self.fun = fun - - if args is None: - self.args = None - elif not hasattr(args, "__iter__"): - self.args = [args] - else: - self.args = list(args) - - if kwargs is None: - self.kwargs = None - else: - self.kwargs = dict(kwargs) - - self._priority = priority - self._suppress_errors = suppress_errors - self._skip_on_lane_error = skip_on_lane_error - self._inner_job = None - self._cancelled = False - self._submit_time = None - self._start_time = None - self._finish_time = None - self._process_time = None - self._output = None - self._exitcode = None - self._exception_txt = None - self._callback = None - - def compare(self, job) -> int: - """compares two jobs by priority or index. - - Arguments: - job {ezpq.Job} - - Returns: - int -- `1` if `self` is greater than comparison, - `-1` if `self` is less than, - `0` if equal. - """ - return utils.compare_by(self, job, by=["priority", "idx"]) - - def __eq__(self, job) -> bool: - return self.compare(job) == 0 - - def __ne__(self, job) -> bool: - return self.compare(job) != 0 - - def __lt__(self, job) -> bool: - return self.compare(job) < 0 - - def __le__(self, job) -> bool: - return self.compare(job) <= 0 - - def __gt__(self, job) -> bool: - return self.compare(job) > 0 - - def __ge__(self, job) -> bool: - return self.compare(job) >= 0 - - def is_running(self) -> bool: - """`True` if the inner job/thread is alive, - else `False`.""" - return self._inner_job is not None and self._inner_job.is_alive() - - def is_expired(self) -> bool: - """`True` if the job is running and its timeout is exceeded, - else `False`.""" - return ( - self.is_running() - and self.timeout > 0 - and self._start_time is not None - and self._finish_time is None - and self._start_time + self.timeout < time.time() - ) - - def join(self) -> None: - """waits for the job/thread to complete. - - Returns: - None - """ - if self._inner_job is not None: - self._inner_job.join() - - @property - def exitcode(self): - if ( - self._inner_job is not None - and hasattr(self._inner_job, "exitcode") - and self._inner_job.exitcode is not None - and not self._suppress_errors - ): - return self._inner_job.exitcode - else: - return self._exitcode - - def terminate(self): - if self._inner_job is not None: - self._inner_job.terminate() - - def stop(self): - """Terminates an existing process. Does not work for threads.""" - if self.is_running(): - if not hasattr(self._inner_job, "terminate"): - log.error("Unable to terminate thread.") - else: - self._inner_job.terminate() - self._inner_job.join() - self._finish_time = time.time() - self._cancelled = True - log.debug("Stopped data: '%d'", self._idx) - - def running_time(self): - """Returns the runtime of a finished data. - Includes actual start time to finish time, not any overhead after. - """ - if self._finish_time: - return self._finish_time - self._start_time - return None - - def waiting_time(self): - """Returns the amount of time a data has spent in the waiting queue.""" - if self._start_time: - return self._start_time - self._submit_time - return time.time() - self._submit_time - - def total_time(self): - """Returns the total time a finished data spent in the ezpq.Queue system. - Includes actual submit time to finish time, not any overhead after. - """ - if self._finish_time: - return self._finish_time - self._submit_time - return time.time() - self._submit_time - - def get_submit_time(self): - """Returns a datetime object of the time this data was submitted.""" - if self._submit_time: - return datetime.utcfromtimestamp(self._submit_time) - return None - - def get_start_time(self): - """Returns a datetime object of the time this data was started.""" - if self._start_time: - return datetime.utcfromtimestamp(self._start_time) - return None - - def get_end_time(self): - """Returns a datetime object of the time this data finished.""" - if self._finish_time: - return datetime.utcfromtimestamp(self._finish_time) - return None - - def get_processed_time(self): - """Returns a datetime object of the time this data was processed.""" - if self._process_time: - return datetime.utcfromtimestamp(self._process_time) - return None - - def is_processed(self): - """Returns true if this data has been processed; false otherwise. - A processed data is one that has had its output gathered, callback called, - before being removed from the working dictionary. - """ - return self._process_time is not None - - def __str__(self): - return str(self.__dict__) - - def __repr__(self): - return self.__str__() - - @property - def cancelled(self): - return self._cancelled - - @cancelled.setter - def cancelled(self, value): - self._cancelled = value - - @property - def idx(self): - return self._idx - - @idx.setter - def idx(self, value: int): - self._idx = value - - @property - def suppress_errors(self): - return self._suppress_errors - - @suppress_errors.setter - def suppress_errors(self, value: bool): - self._suppress_errors = value - - @property - def priority(self): - return self._priority - - @priority.setter - def priority(self, value: int): - self._priority = value - - @property - def qid(self): - return self._qid - - @property - def output(self): - return self._output - - @property - def exception_txt(self): - return self._exception_txt - - @property - def callback(self): - return self._callback diff --git a/src/ezpq/Plot.py b/src/ezpq/Plot.py deleted file mode 100644 index 8e1647d..0000000 --- a/src/ezpq/Plot.py +++ /dev/null @@ -1,226 +0,0 @@ -import logging as log -from typing import List, Optional, Union - -from ezpq.FinishedJob import FinishedJob - -try: - import pandas as pd - import plotnine as gg -except ImportError as e: - print("Unable to import optional plot dependencies; continuing.") - - -class Plot: - """Functions to produce Gantt chart from finished a `ezpq.FinishedJob`""" - - def __init__(self, jobs: Union[List[FinishedJob], pd.DataFrame]): - """[summary] - - Arguments: - jobs {Union[List[FinishedJob], pd.DataFrame]} -- list of `ezpq.FinishedJob` objects. - """ - - df = ( - jobs - if isinstance(jobs, pd.DataFrame) - else pd.DataFrame([j.__dict__ for j in jobs]) - ) - df.lane.fillna(value="", inplace=True) - min_time = df["submitted"].min() - df["submitted_offset"] = df["submitted"] - min_time - df["started_offset"] = df["started"] - min_time - df["ended_offset"] = df["ended"] - min_time - df["processed_offset"] = df["processed"] - min_time - self.jobs_df = df - - @staticmethod - def _plot_theme( - grid_axis: str = "both", - grid_lines: str = "both", - theme: str = "bw", - ): - """Internal fun provides consistent theme across plots. - Currently a slightly modified version of theme_bw() with configurable grid lines. - - Args: - grid_axis: controls the axis on which to draw grid lines - - Accepts: None, 'x', 'y', 'both' - - Default: 'both' - grid_lines: controls whether major or minor grid lines are drawn - - Accepts: None, 'major', 'minor', 'both' - - Default: 'both' - theme: - - Accepts: 'bw', 'classic', 'gray', 'grey', 'seaborn', '538', 'dark', 'matplotlib', 'minimal', 'xkcd', 'light' - - Default: 'bw' - Returns: - A theme object to be added to a plotnine.ggplot() object. - """ - - assert grid_axis in [None, "x", "y", "both"] - assert grid_lines in [None, "major", "minor", "both"] - assert theme in [ - "bw", - "classic", - "gray", - "grey", - "seaborn", - "538", - "dark", - "matplotlib", - "minimal", - "xkcd", - "light", - ] - - drop_grid = set() - - if grid_axis is None or grid_lines is None: - drop_grid.update(["panel_grid_major", "panel_grid_minor"]) - elif grid_axis == "x": - drop_grid.update(["panel_grid_major_y", "panel_grid_minor_y"]) - if grid_lines == "major": - drop_grid.add("panel_grid_minor_y") - elif grid_lines == "minor": - drop_grid.add("panel_grid_major_y") - elif grid_axis == "y": - drop_grid.update(["panel_grid_major_x", "panel_grid_minor_x"]) - if grid_lines == "major": - drop_grid.add("panel_grid_minor_x") - elif grid_lines == "minor": - drop_grid.add("panel_grid_major_x") - - grid_opt = {} - for x in drop_grid: - grid_opt[x] = gg.element_blank() - - return getattr(gg, "theme_" + theme)() + gg.theme( - panel_border=gg.element_blank(), - axis_line=gg.element_line(color="black"), - **grid_opt, - ) - - def build( - self, - color_by: Optional[str] = "qid", - facet_by: Optional[str] = "qid", - facet_scale: Optional[str] = "fixed", - show_legend: Optional[bool] = True, - bar_width: Optional[bool] = 1, - title: Optional[str] = None, - color_pal: Optional[str] = None, - theme: Optional[str] = "bw", - ) -> gg.theme: - # TODO: update me - """Produces a plot based on the data and options provided to a `ezpq.Plot()` object. - - Args: - color_pal: - color_by: controls the column to use for coloring the bars. - - Accepts: one of 'qid', 'priority', 'lane', 'cancelled', 'exitcode', 'name', 'output' - - Default: 'qid' - facet_by: controls the column to use for facetting the plot. - - Accepts: one of 'qid', 'priority', 'lane', 'cancelled', 'exitcode', 'name', 'output' - - Default: 'qid' - facet_scale: controls the scale of the x/y axis across facets. - - Accepts: one of 'fixed', 'free', 'free_x', 'free_y' - - Default: 'fixed' - show_legend: controls whether the legend is drawn. - - Accepts: bool - - Default: True - bar_width: controls the bar width - - Accepts: float - - Default: 1 - title: optional title to be drawn above the plot. - - Accepts: str, None - - Default: None - theme: - - Accepts: 'bw', 'classic', 'gray', 'grey', 'seaborn', '538', 'dark', 'matplotlib', 'minimal', 'xkcd', 'light' - - Default: 'bw' - Returns: - The plot produced from plotnine.ggplot(). - """ - - assert color_by in [ - "qid", - "priority", - "lane", - "cancelled", - "exitcode", - "name", - "output", - ] - assert facet_by in [ - "qid", - "priority", - "lane", - "cancelled", - "exitcode", - "name", - "output", - ] - assert facet_scale in ["fixed", "free", "free_x", "free_y"] - - df2 = self.jobs_df.loc[ - :, - { - "qid", - "idx", - color_by, - facet_by, - "submitted_offset", - "started_offset", - "ended_offset", - "processed_offset", - }, - ].melt(id_vars={"qid", "idx", color_by, facet_by}) - df2 = df2[df2["value"].notnull()] - - df_submit_start = df2[ - (df2["variable"] == "submitted_offset") - | (df2["variable"] == "started_offset") - ] - df_start_end = df2[ - (df2["variable"] == "started_offset") | (df2["variable"] == "ended_offset") - ] - df_end_processed = df2[ - (df2["variable"] == "ended_offset") - | (df2["variable"] == "processed_offset") - ] - - labs = {"x": "duration", "y": "job index"} - if title is not None: - labs["title"] = title - - gg_obj = ( - gg.ggplot(gg.aes(x="value", y="idx", group="factor(idx)")) - + gg.geom_line(df_submit_start, color="gray", size=bar_width, alpha=0.2) - + gg.geom_line( - df_start_end, - gg.aes(color=f"factor({color_by})"), - size=bar_width, - show_legend=bool(show_legend), - ) - + gg.geom_line(df_end_processed, color="gray", size=bar_width, alpha=0.2) - + gg.labs(**labs) - + gg.labs(color=color_by) - + Plot._plot_theme(grid_axis="x", theme=theme) - + gg.facet_grid( - facets=facet_by + "~", - labeller="label_both", - scales=facet_scale, - as_table=True, - ) - ) - - if color_pal is None or not isinstance(color_pal, list): - gg_obj += gg.scale_color_hue(h=0.65) - else: - n_colors = self.jobs_df[color_by].unique().size - - if len(color_pal) < n_colors: - log.warning("Insufficient number of colors; need at least %d", n_colors) - gg_obj += gg.scale_color_hue(h=0.65) - else: - gg_obj += gg.scale_color_manual(color_pal[:n_colors]) - - return gg_obj diff --git a/src/ezpq/Queue.py b/src/ezpq/Queue.py deleted file mode 100644 index cb97835..0000000 --- a/src/ezpq/Queue.py +++ /dev/null @@ -1,821 +0,0 @@ -import logging -import multiprocessing as mp -import threading -import time -import traceback -from collections import defaultdict -from heapq import heappop, heappush -from typing import Any, Callable, Dict, List, Optional, Sequence, Type, Union -from uuid import uuid4 - -from ezpq.FinishedJob import FinishedJob -from ezpq.Job import Job -from ezpq.utils import get_logger, is_windows_os, log_csv - -try: - from tqdm.auto import tqdm -except ImportError as e: - print("Unable to import `tqdm`; continuing.") - - -LOG = get_logger(__name__, level=logging.INFO) - - -class Queue(object): - class RepeatedTimer(object): - """Periodically runs a function in a background thread. - from: https://stackoverflow.com/a/13151299 - - used to run `ezpq.Queue._pulse` asynchronously. - """ - - def __init__(self, interval_ms: int, fun: Callable, *args, **kwargs): - self._timer: Optional[threading.Timer] = None - self._interval: int = interval_ms - self._function: Callable = fun - self._args: Sequence[Any] = args - self._kwargs: Dict[str, Any] = kwargs - self._is_enabled: bool = False - self._is_running: bool = False - - def _run(self): - self._is_running = False - self.start() - self._function(*self._args, **self._kwargs) - - def start(self): - if not self._is_running: - self._timer = threading.Timer(self._interval / 1000, self._run) - self._timer.start() - self._is_running = True - - self._is_enabled = True - - def stop(self): - if self._timer is not None: - self._timer.cancel() - - self._is_enabled = False - self._is_running = False - - @property - def is_running(self) -> bool: - return self._is_running - - @property - def is_enabled(self) -> bool: - return self._is_enabled - - DEFAULT_LANE: Optional[str] = None - - def __init__( - self, - max_concurrent: int = mp.cpu_count(), - engine: Union[threading.Thread, mp.Process] = threading.Thread, - name: Optional[str] = None, - drop_finished: bool = False, - start: bool = True, - stop_when_idle: bool = False, - callback: Optional[Callable] = None, - output_file: Optional[str] = None, - pulse_freq_ms: int = 100, - show_progress: bool = False, - max_size: int = 0, - ): - """Implements a parallel queueing system. - - Args: - max_concurrent: the max number of concurrent jobs. - - Accepts: int - - Default: cpu_count() - max_size: when > 0, will throw an exception the number of enqueued jobs exceeds this value. Otherwise, no limit. - - Accepts: int - - Default: 0 (unlimited) - engine: the class to use to invoke new jobs. - - Accepts: multiprocessing.Process, threading.Thread - - Default: multiprocessing.Process - drop_finished: controls whether jobs are discarded of after completion. - - Accepts: bool - - Default: False - start: controls whether the queue system "pulse" is started upon instantiation (default), or manually. - - Accepts: bool - - Default: True - stop_when_idle: controls whether the queue system "pulse" stops itself after all jobs are complete. - - Accepts: bool - - Default: False - callback: optional fun to execute synchronously immediately after a data completes. - - Accepts: fun object - - Default: None - output_file: if file path is specified, job data is written to this path in CSV format. - - Accepts: str - - Default: None - pulse_freq_ms: controls the pulse frequency; the amount of time slept between operations. - - Accepts: float - - Default: 0.1 - - Returns: - ezpq.Queue object. - """ - - self._qid: str = name if name else str(uuid4())[:8] - - self.show_progress: bool = show_progress - self._max_size: int = max_size - self._count_input: int = 0 - self._count_output: int = 0 - self._max_concurrent: int = max_concurrent - self._callback: Callable = callback - self._log_file: str = output_file - - self._lock: threading.Lock = ( - threading.Lock() - ) # https://opensource.com/article/17/4/grok-gil - - if engine is mp.Process and is_windows_os(): - LOG.warning( - ( - "multiprocessing performance is degraded on Windows systems. see: " - "https://docs.python.org/3/library/multiprocessing.html?highlight=process#the-spawn-and-forkserver-start-methods" - ), - ) - - self._engine: Union[mp.Process, threading.Thread] = engine - - self._waiting_lanes: Dict[Optional[str], List[Job]] = {None: []} - self._working_queue: Dict[int, Job] = {} - self._finished_queue: List[FinishedJob] = [] - - self._drop_finished: bool = drop_finished - self._mp_manager: Optional[mp.Manager] = None - - if self._engine is mp.Process: - self._mp_manager = mp.Manager() - self._output = self._mp_manager.dict() - else: - self._output = {} - - LOG.debug("Initialized queue with %d max_concurrent.", self._max_concurrent) - - self._pulse_freq_ms: int = pulse_freq_ms - self._timer: Queue.RepeatedTimer = Queue.RepeatedTimer( - interval_ms=self._pulse_freq_ms, - fun=self._pulse, - ) - - if start is True: - self.start() - - self._stop_when_idle: bool = stop_when_idle - - LOG.debug("Initialized pulse.") - - def __call__(self, fun, *args, **kwargs): - """Decorator guided by http://scottlobdell.me/2015/04/decorators-arguments-python/""" - - self.start() - - def wrapped_f(iterable, *args, **kwargs): - for x in iterable: - self.put(fun=fun, args=[x] + list(args), kwargs=kwargs) - self.wait() - job_data = self.collect() - self.dispose() - return job_data - - return wrapped_f - - def __del__(self): - self.dispose() - - def start(self): - """Starts the queue system pulse.""" - LOG.debug("Starting pulse.") - self._timer.start() - - def stop(self): - """Stops the queue system pulse.""" - LOG.debug("Stopping pulse.") - self._timer.stop() - - def dispose(self): - """Clears all output and stops the queue system pulse.""" - LOG.debug("Disposing") - - if self.is_running: - self.stop_all(wait=True) - self.stop() - - LOG.debug("Removed jobs.") - self._output = None - LOG.debug("Removed output.") - self._finished_queue.clear() # [:] = [] - LOG.debug("Removed finished.") - self._count_input = 0 - self._count_output = 0 - LOG.debug("Reset counters.") - - if self._mp_manager is not None: - self._mp_manager.shutdown() - - def clear_waiting(self): - LOG.debug("Clearing waiting queue") - with self._lock: - keys = list(self._waiting_lanes.keys()) - for k in keys: - lane_jobs = self._waiting_lanes.get(k) - for _ in range(len(lane_jobs)): - job = heappop(lane_jobs) - job._cancelled = True - job._process_time = time.time() - if not self._drop_finished: - heappush(self._finished_queue, FinishedJob(job)) - else: - self._count_output += 1 - del self._waiting_lanes[k] - - def stop_all(self, wait=True): - """Stops working jobs and clears waiting jobs.""" - - self.clear_waiting() - - keys = list(self._working_queue.keys()) - for k in keys: - job = self._working_queue.get(k) - if job is not None: - job.stop() - - if wait: - self.wait() - - def __enter__(self): - LOG.debug("Entered context manager") - return self - - def __exit__(self, *args): - LOG.debug("Exiting context manager") - self.dispose() - - def _pulse(self): - # TODO: document this better. - """Used internally; manages the queue system operations.""" - - with self._lock: - try: - if self._stop_when_idle and self.is_idle(): - self.stop() - else: - # stop expired jobs. - for job_id, job in self._working_queue.items(): - if job.is_expired(): - job.stop() - - for job_id in list(self._working_queue.keys()): - job = self._working_queue[job_id] - - if not job.is_running() and not job.is_processed(): - job.join() - if not job.cancelled: - try: - job_data = self._output.pop(job.idx) - job._finish_time = job_data["_finish_time"] - job._output = job_data["_output"] - job._exitcode = job_data["_exitcode"] - job._exception_txt = job_data["_exception_txt"] - except KeyError as ex: - job._finish_time = time.time() - job._output = None - job._exitcode = 1 - job._exception_txt = Exception( - "{}\n\nNo data for data; it may have exited" - " unexpectedly.".format( - str(ex), - ), - ) - - if self._callback is not None: - # TODO: write this to a new property. - try: - job._callback = self._callback(job) - except Exception as ex: - job._callback = str(ex) - - job._process_time = time.time() - - LOG.debug("Completed job: %d", job.idx) - - finished_job = FinishedJob(job) - - if not self._drop_finished: - heappush(self._finished_queue, finished_job) - else: - self._count_output += 1 - - if self._log_file is not None: - # TODO: use a persistent file connection. - log_csv(data=finished_job.__dict__, path=self._log_file) - - del self._working_queue[job_id] - - if job.lane is not None and job.lane != Queue.DEFAULT_LANE: - lane_jobs: List[Job] = self._waiting_lanes.get(job.lane) - if lane_jobs is not None: - next_job = None - parent_exitcode = job.exitcode - while len(lane_jobs) > 0: - next_job = heappop(lane_jobs) - - if ( - parent_exitcode == 0 - or not next_job._skip_on_lane_error - ): - break - else: - next_job._cancelled = True - next_job._exitcode = parent_exitcode - next_job._exception_txt = ( - "skip_on_lane_error = True and" - " preceding data ({}) exit code is {}" - .format( - job.idx, - parent_exitcode, - ) - ) - next_job._process_time = time.time() - if not self._drop_finished: - heappush( - self._finished_queue, - FinishedJob(next_job), - ) - else: - self._count_output += 1 - next_job = None - continue - - if len(lane_jobs) == 0: - del self._waiting_lanes[job.lane] - - if next_job is not None: - self._working_queue[next_job.idx] = next_job - self._start_job(job=next_job) - - while ( - len(self._waiting_lanes[Queue.DEFAULT_LANE]) > 0 - and self.max_concurrent - self.count_working() > 0 - ): - job = heappop(self._waiting_lanes[Queue.DEFAULT_LANE]) - self._working_queue[job.idx] = job - self._start_job(job=job) - except: - self.stop() - LOG.error(traceback.format_exc()) - finally: - LOG.debug( - "waiting={}; working={}; finished={}.".format( - self.count_waiting(), - self.count_working(), - self.count_finished(), - ), - ) - - def count_input(self) -> int: - return self._count_input - - def count_output(self) -> int: - return self._count_output - - def count_waiting(self) -> int: - return sum(len(v) for _, v in self._waiting_lanes.items()) - - def count_working(self) -> int: - return len(self._working_queue) - - def count_finished(self) -> int: - return len(self._finished_queue) - - def count_remaining(self) -> int: - return sum(self.count_queues(waiting=True, working=True)) - - def __len__(self): - return self.size() - - def size(self, *args, **kwargs) -> List[int]: - return sum(self.count_queues(*args, **kwargs)) - - def count_queues(self, waiting=False, working=False, finished=False) -> List[int]: - """Returns the number of jobs in the corresponding queue(s). - - Args: - waiting: include jobs in the waiting queue? - - Accepts: bool - - Default: False - working: include jobs in the working table? - - Accepts: bool - - Default: False - finished: include jobs in the completed queue? - - Accepts: bool - - Default: False - - Note: when all are False, all jobs are counted (default). - - Returns: - int - """ - - counts = defaultdict(lambda: -1) - - is_locked = False - - try: - to_tally = sum([waiting, working, finished]) - if to_tally != 1: - if to_tally == 0: - waiting, working, finished = True, True, True - is_locked = ( - self._lock.acquire() - ) # must lock when more than 1 component included. - - if waiting: - counts["waiting"] = self.count_waiting() - if working: - counts["working"] = self.count_working() - if finished: - counts["finished"] = self.count_finished() - finally: - if is_locked: - self._lock.release() - - return [v for _, v in counts.items() if v != -1] - - def is_idle(self) -> bool: - return self.count_waiting() == 0 and self.count_working() == 0 - - def is_busy(self) -> bool: - """True if max concurrent limit is reached or if there are waiting jobs.""" - return self.count_waiting() > 0 or self.max_concurrent <= self.count_working() - - def empty(self): - """True if there are no jobs in the queue system.""" - return self.size() == 0 - - def full(self): - """True if the number of jobs in the queue system is equal to max_size.""" - return 0 < self._max_size <= self.size() - - def join(self, *args, **kwargs): - self.wait(*args, **kwargs) - - def wait( - self, - timeout: Optional[int] = 0, - poll_ms: Optional[int] = 0, - show_progress: Optional[bool] = None, - _fun: Optional[Callable] = None, - _target_value: Optional[int] = None, - _comparator: Optional[int] = None, - ): - """Waits for jobs to be finished by the queue system. - - Args: - _comparator: - _target_value: - _fun: - poll_ms: the time, in seconds, between checks. - - Accepts: float - - Default: ezpq.Queue.poll_ms - timeout: when > 0, the maximum time to wait, in seconds. Otherwise, no limit. - - Accepts: float - - Default: 0 (unlimited) - show_progress: show `tqdm` progress bar; (pass static_args to `waitpb`) - - Accepts: bool - - Default: False - - Returns: - 0 if the expected number of jobs finished. > 0 otherwise. - """ - - if poll_ms is None or poll_ms <= 0: - poll_ms = self._pulse_freq_ms - elif poll_ms < self._pulse_freq_ms: - raise ValueError("`poll_ms` must be >= `ezpq.Queue.pulse_freq_ms`") - - if show_progress is None: - show_progress = self.show_progress - - if _fun is None: - _fun = self.count_remaining - - if _target_value is None: - _target_value = 0 - - if _comparator is None: - _comparator = int.__le__ - - current_value: int = _fun() - - if not _comparator(current_value, _target_value): - start = time.time() - - pb = None - - try: - if show_progress: - pb = tqdm(total=current_value, unit="op") - - while not _comparator(current_value, _target_value) and ( - timeout == 0 or time.time() - start < timeout - ): - time.sleep(poll_ms / 1000) - - tmp_value = _fun() - if pb is None: - current_value = tmp_value - else: - diff_value = current_value - tmp_value - if diff_value > 0: - current_value = tmp_value - pb.update(diff_value) - finally: - if pb: - pb.close() - - return current_value - - # TODO: return a `FinishedJob` - @staticmethod - def _job_wrapper(_job: Job, _output, *args, **kwargs): - """Used internally to wrap a data, capture output and any exception.""" - out = None - ex_obj: Optional[object] = None - ex_msg: Optional[str] = None - code: int = 0 - - try: - out = _job.fun(*args, **kwargs) - except Exception as ex: - ex_obj = ex - ex_msg = traceback.format_exc() - code = -1 - finally: - # TODO: create class of this. - _output.update( - { - _job.idx: { - "_finish_time": time.time(), - "_output": out, - "_exception_txt": ex_msg, - "_exitcode": code, - }, - }, - ) - - if not _job.suppress_errors and ex_obj is not None: - raise ex_obj - - def _start_job(self, job): - """Internal; invokes jobs.""" - - job_args = {} - - if job.args is not None: - # if not isinstance(data.static_args, list): - # job_args['static_args'] = [data, self._output, data.static_args] - # else: - job_args["args"] = [job, self._output] + job.args - - if job.kwargs is None: - job_args["kwargs"] = {} - else: - job_args["kwargs"] = dict(job.kwargs) - - if job.args is None: - job_args["kwargs"].update({"_job": job, "_output": self._output}) - - j: Union[Type[mp.Process], Type[threading.Thread]] = self._engine( - name=str(job.idx), - target=Queue._job_wrapper, - **job_args, - ) - - LOG.debug("starting job %d (name=%s)", job.idx, job.name) - j.start() - - job._start_time = time.time() - job._inner_job = j - - def submit(self, job): - """Submits a data into the ezpq.Queue system. - - Throws an exception if: - 1. the Queue uses a Thread job_runner and this data has a timeout (can't terminate Threads), - 2. the Queue max_size will be exceeded after adding this data. - - Returns: - The number of jobs submitted to the queue. - """ - - assert not (self._engine is threading.Thread and job.timeout > 0) - - if self.full(): - raise OverflowError("Max size exceeded.") - - job._submit_time = time.time() - - job._qid = self._qid - self._count_input += 1 - job.idx = self._count_input - - if job.name is None: - job.name = job.idx - - LOG.debug("queuing job %d (name=%s)", job.idx, job.name) - - lane_jobs = self._waiting_lanes.get(job.lane) - if lane_jobs is not None: - heappush(lane_jobs, job) - else: - lane_jobs = [] - self._waiting_lanes[job.lane] = lane_jobs - - # if this is the first job in this lane, - # it should be pushed to the default lane. - heappush(self._waiting_lanes[Queue.DEFAULT_LANE], job) - - return job.idx - - def put(self, *args, **kwargs): - """Creates a job and submits it to an ezpq queue. - see `help(ezpq.Job.__init__)`""" - - job = Job(*args, **kwargs) - - return self.submit(job) - - def map( - self, - fun, - iterable, - static_args=None, - static_kwargs=None, - timeout=0, - show_progress=None, - ): - assert hasattr(iterable, "__iter__") - - if static_args is None: - static_args = [None] - elif not hasattr(static_args, "__iter__"): - static_args = [None] + [static_args] - elif len(static_args) == 0: - static_args = [None] - else: - static_args = [None] + list(static_args) - - for x in iterable: - static_args[0] = x - job = Job( - fun=fun, - args=list(static_args), - kwargs=static_kwargs, - timeout=timeout, - ) - self.submit(job) - - self.wait(show_progress=show_progress) - - return self.collect() - - def starmap( - self, - fun, - iterable, - static_args=None, - static_kwargs=None, - timeout=0, - show_progress=None, - ): - assert hasattr(iterable, "__iter__") - - if static_args is None: - static_args = [] - elif not isinstance(static_args, list): - static_args = list(static_args) - - for x in iterable: - job = Job( - fun=fun, - args=list(x) + static_args, - kwargs=static_kwargs, - timeout=timeout, - ) - self.submit(job) - - self.wait(show_progress=show_progress) - - return self.collect() - - def starmapkw( - self, - fun, - iterable, - static_args=None, - static_kwargs=None, - timeout=0, - show_progress=None, - ): - assert hasattr(iterable, "__iter__") - - if static_kwargs is None: - static_kwargs = {} - elif not isinstance(static_kwargs, dict): - static_kwargs = dict(static_kwargs) - - for x in iterable: - job = Job( - fun=fun, - args=static_args, - kwargs={**x, **static_kwargs}, - timeout=timeout, - ) - self.submit(job) - - self.wait(show_progress=show_progress) - - return self.collect() - - def get(self, wait: Optional[bool] = False, **kwargs) -> Optional[FinishedJob]: - """Pops the highest priority item from the finished queue. - - Args: - wait: - poll_ms: when > 0, time between checks - - Accepts: float - - Default: 0 (no wait) - timeout: the maximum time, in seconds, to wait for a data to complete. - - Accepts: float - - Default: 0 (no wait/unlimited wait) - - Notes: - - when both poll_ms and timeout are 0, only one check is done; - - when either is > 0, the method will block until output is available. - - Returns: - Dictionary of the most recently finished, highest priority data. - """ - - if self._drop_finished: - raise ValueError("`get` is not applicable when `drop_finished` is True.") - - if self.count_finished() == 0: - if wait: - kwargs["show_progress"] = False - self.wait( - _fun=self.count_finished, - _target_value=1, - _comparator=int.__ge__, - **kwargs, - ) - else: - return None - - job: FinishedJob = heappop(self._finished_queue) - self._count_output += 1 - return job - - def collect(self, n=0): - """Repeatedly calls `get()` and returns a list of job data. - - Args: - n: the number of jobs to pop from the finished queue. - - Accepts: int - - Default: 0 (all) - - Returns: - a list of dictionary objects. - """ - - if n <= 0: - n = self.count_finished() - else: - n = min(n, self.count_finished()) - - return [self.get() for _ in range(n)] - - @property - def max_concurrent(self) -> int: - return self._max_concurrent - - @max_concurrent.setter - def max_concurrent(self, value: int): - self._max_concurrent = value - - @property - def max_size(self) -> int: - return self._max_size - - @max_size.setter - def max_size(self, value: int) -> None: - self._max_size = value - - @property - def is_running(self) -> bool: - return self._timer.is_enabled diff --git a/src/ezpq/__init__.py b/src/ezpq/__init__.py deleted file mode 100644 index 554afb4..0000000 --- a/src/ezpq/__init__.py +++ /dev/null @@ -1,4 +0,0 @@ -from .FinishedJob import FinishedJob -from .Job import Job -from .Plot import Plot -from .Queue import Queue diff --git a/src/ppqueue/__init__.py b/src/ppqueue/__init__.py new file mode 100644 index 0000000..59a9ed4 --- /dev/null +++ b/src/ppqueue/__init__.py @@ -0,0 +1,4 @@ +from .job import Job +from .queue import Queue + +__all__ = ["Job", "Queue"] diff --git a/src/ezpq/__version__.py b/src/ppqueue/__version__.py similarity index 100% rename from src/ezpq/__version__.py rename to src/ppqueue/__version__.py diff --git a/src/ezpq/exceptions.py b/src/ppqueue/exceptions.py similarity index 100% rename from src/ezpq/exceptions.py rename to src/ppqueue/exceptions.py diff --git a/src/ppqueue/job.py b/src/ppqueue/job.py new file mode 100644 index 0000000..b3b36f4 --- /dev/null +++ b/src/ppqueue/job.py @@ -0,0 +1,236 @@ +from __future__ import annotations + +import logging as log +import time +from collections.abc import Iterable +from dataclasses import dataclass, field +from datetime import datetime +from enum import Enum, auto +from multiprocessing import Process +from threading import Thread +from typing import Any, Callable, Sequence + +from .utils import compare_by + + +class JobState(Enum): + UNSUBMITTED = auto() + QUEUED = auto() + RUNNING = auto() + CANCELLED = auto() + FINISHED = auto() + UNKNOWN = auto() + + +@dataclass +class Job(object): + """Represents a job returned by a Queue.""" + + fun: Callable[..., Any] + args: Sequence[Any] | None = field(default_factory=list) + kwargs: dict[str, Any] | None = field(default_factory=dict) + name: str | None = None + priority: int = 100 + group: int | None = None + timeout: float = 0 + suppress_errors: bool = False + skip_on_group_error: bool = False + # automatically assigned during processing. + qid: str | None = field(default=None, init=False) + """The ID of the queue that ran this job.""" + idx: int | None = field(default=None, init=False) + """The ID of this job.""" + cancelled: bool = field(default=False, init=False) + """Did this job timeout or was it cancelled?""" + submit_timestamp: float | None = field(default=None, init=False) + """Unix timestamp of when this job was submitted.""" + start_timestamp: float | None = field(default=None, init=False) + """Unix timestamp of when this job started.""" + finish_timestamp: float | None = field(default=None, init=False) + """Unix timestamp of when this job finished.""" + process_timestamp: float | None = field(default=None, init=False) + """Unix timestamp of when this job was processed from the working queue.""" + result: Any = field(default=None, init=False) + """Result of this job, if it exited gracefully.""" + callback_result: str | None = field(default=None, init=False) + """Result of the callback for this job.""" + error: str | None = field(default=None, init=False) + """Exception text for this job, if an error occurred.""" + exitcode: int | None = field(default=None, init=False) + inner_job: Process | Thread | None = field(default=None, init=False) + + def __post_init__(self) -> None: + if self.args is None: + self.args = [] + elif isinstance(self.args, str) or not isinstance(self.args, Iterable): + self.args = [self.args] + + if self.kwargs is None: + self.kwargs = {} + + def _compare(self, job: object) -> int: + """compares two jobs by priority or index. + + Arguments: + job {ppqueue.Job} + + Returns: + int -- `1` if `self` is greater than comparison, + `-1` if `self` is less than, + `0` if equal. + """ + return compare_by(self, job, by=["priority", "idx"]) + + def __eq__(self, job: object) -> bool: + return self._compare(job) == 0 + + def __ne__(self, job: object) -> bool: + return self._compare(job) != 0 + + def __lt__(self, job: object) -> bool: + return self._compare(job) < 0 + + def __le__(self, job: object) -> bool: + return self._compare(job) <= 0 + + def __gt__(self, job: object) -> bool: + return self._compare(job) > 0 + + def __ge__(self, job: object) -> bool: + return self._compare(job) >= 0 + + def is_running(self) -> bool: + return self.inner_job is not None and self.inner_job.is_alive() + + def is_expired(self) -> bool: + return ( + self.is_running() + and self.timeout > 0 + and self.start_timestamp is not None + and self.finish_timestamp is None + and self.start_timestamp + self.timeout < time.time() + ) + + def join(self, *args, **kwargs) -> None: + # waits for the job to complete. + if self.inner_job is not None: + self.inner_job.join(*args, **kwargs) + + def get_exit_code(self) -> int | None: + """Exit code of the job.""" + if ( + not self.inner_job + or not hasattr(self.inner_job, "exitcode") + or self.inner_job.exitcode is None + ): + return None + return self.inner_job.exitcode + + def terminate(self) -> None: + if self.inner_job is not None: + self.inner_job.terminate() + + def stop(self) -> None: + # Terminates an existing process. Does not work for threads. + if not self.inner_job or not self.is_running(): + return + elif not hasattr(self.inner_job, "terminate"): + log.error("Unable to terminate thread.") + else: + self.inner_job.terminate() + self.inner_job.join() + self.finish_timestamp = time.time() + self.cancelled = True + log.debug("Stopped data: '%d'", self.idx) + + def get_seconds_running(self) -> float | None: + """The number of seconds a job was running for. + + Examples: + >>> from ppqueue import Queue + >>> from time import sleep + ... + >>> with Queue() as queue: + ... for i in range(5): + ... jobs = queue.map(sleep, [1, 2, 3]) + ... + >>> [int(job.get_seconds_running()) for job in jobs] + [1, 2, 3] + """ + if not self.start_timestamp or not self.finish_timestamp: + return None + return self.finish_timestamp - self.start_timestamp + + def get_seconds_waiting(self) -> float | None: + """The amount of time a data has spent in the waiting queue. + + Examples: + >>> job.get_seconds_waiting() # doctest: +SKIP + """ + if not self.submit_timestamp: + return None + + if not self.start_timestamp: + return time.time() - self.submit_timestamp + + return self.start_timestamp - self.submit_timestamp + + def get_seconds_total(self) -> float | None: + """Returns the waiting + running duration of this job. + + Examples: + >>> job.get_seconds_total() # doctest: +SKIP + """ + if not self.submit_timestamp: + return None + + if not self.finish_timestamp: + return time.time() - self.submit_timestamp + + return self.finish_timestamp - self.submit_timestamp + + def get_submit_timestamp(self) -> datetime | None: + """The time this job was submitted. + + Examples: + >>> job.get_submit_timestamp() # doctest: +SKIP + """ + if self.submit_timestamp: + return datetime.utcfromtimestamp(self.submit_timestamp) + return None + + def get_start_timestamp(self) -> datetime | None: + """Returns a datetime object of the time this data was started.""" + if self.start_timestamp: + return datetime.utcfromtimestamp(self.start_timestamp) + return None + + def get_finish_timestamp(self) -> datetime | None: + """Returns a datetime object of the time this data finished.""" + if self.finish_timestamp: + return datetime.utcfromtimestamp(self.finish_timestamp) + return None + + def get_processed_timestamp(self) -> datetime | None: + """Returns a datetime object of the time this data was processed.""" + if self.process_timestamp: + return datetime.utcfromtimestamp(self.process_timestamp) + return None + + def is_processed(self) -> bool: + # Returns true if this data has been processed; false otherwise. + # A processed data is one that has had its output gathered, callback called, + # before being removed from the working dictionary. + + return self.process_timestamp is not None + + def get_state(self) -> JobState: + if not self.submit_timestamp: + return JobState.UNSUBMITTED + if self.is_running(): + return JobState.RUNNING + if self.cancelled: + return JobState.CANCELLED + if self.finish_timestamp: + return JobState.FINISHED + return JobState.UNKNOWN diff --git a/src/ppqueue/plot.py b/src/ppqueue/plot.py new file mode 100644 index 0000000..4c2c82b --- /dev/null +++ b/src/ppqueue/plot.py @@ -0,0 +1,267 @@ +from __future__ import annotations + +import logging as log +from enum import Enum, auto + +import pandas as pd +import plotnine as gg + +from .job import Job +from .utils import dedupe_list + +__all__ = [ + "plot_jobs", + "PlotColorBy", + "PlotFacetBy", + "PlotFacetScale", + "PlotGridLines", + "PlotTheme", +] + + +class PlotColorBy(Enum): + """Enum used to define color groups using this job property.""" + + QID = auto() + PRIORITY = auto() + GROUP = auto() + CANCELLED = auto() + EXITCODE = auto() + NAME = auto() + RESULT = auto() + CALLBACK_RESULT = auto() + + +class PlotFacetBy(Enum): + """Enum used to facet the plot by this job property.""" + + QID = auto() + PRIORITY = auto() + GROUP = auto() + CANCELLED = auto() + EXITCODE = auto() + NAME = auto() + RESULT = auto() + CALLBACK_RESULT = auto() + + +class PlotTheme(Enum): + """Enum used to expose supported plot themes.""" + + BW = auto() + CLASSIC = auto() + GRAY = auto() + GREY = auto() + SEABORN = auto() + DARK = auto() + MATPLOTLIB = auto() + MINIMAL = auto() + XKCD = auto() + LIGHT = auto() + + +class PlotFacetScale(Enum): + FIXED = auto() + FREE = auto() + FREE_X = auto() + FREE_Y = auto() + + +class PlotGridLines(Enum): + NONE = auto() + MAJOR = auto() + MINOR = auto() + BOTH = auto() + + +class Plot: + def __init__(self, *args: list[Job]): + df = pd.DataFrame([j.__dict__ for jobs in args for j in jobs]) + df.group.fillna(value="", inplace=True) + min_time = df["submit_timestamp"].min() + df["submitted_offset"] = df["submit_timestamp"] - min_time + df["started_offset"] = df["start_timestamp"] - min_time + df["ended_offset"] = df["finish_timestamp"] - min_time + df["processed_offset"] = df["process_timestamp"] - min_time + self.jobs_df = df + + @staticmethod + def _plot_theme( + theme: PlotTheme, + grid_lines: PlotGridLines, + grid_axis: str | None, + ) -> gg.theme: + # Used to provide a consistent theme across plots. + + drop_grid = set() + + if grid_axis is None or grid_lines == PlotGridLines.NONE: + drop_grid.update(["panel_grid_major", "panel_grid_minor"]) + elif grid_axis == "x": + drop_grid.update(["panel_grid_major_y", "panel_grid_minor_y"]) + if grid_lines == PlotGridLines.MAJOR: + drop_grid.add("panel_grid_minor_y") + elif grid_lines == PlotGridLines.MINOR: + drop_grid.add("panel_grid_major_y") + elif grid_axis == "y": + drop_grid.update(["panel_grid_major_x", "panel_grid_minor_x"]) + if grid_lines == PlotGridLines.MAJOR: + drop_grid.add("panel_grid_minor_x") + elif grid_lines == PlotGridLines.MINOR: + drop_grid.add("panel_grid_major_x") + + grid_opt = {} + for x in drop_grid: + grid_opt[x] = gg.element_blank() + + return getattr(gg, "theme_" + theme.name.lower())() + gg.theme( + panel_border=gg.element_blank(), + axis_line=gg.element_line(color="black"), + **grid_opt, + ) + + def build( + self, + title: str | None, + color_by: PlotColorBy, + facet_by: PlotFacetBy, + facet_scale: PlotFacetScale, + theme: PlotTheme, + no_legend: bool, + bar_width: int, + color_pal: list[str] | None, + ) -> gg.ggplot: + df2 = self.jobs_df.loc[ + :, + dedupe_list( + [ + "qid", + "idx", + color_by.name.lower(), + facet_by.name.lower(), + "submitted_offset", + "started_offset", + "ended_offset", + "processed_offset", + ], + ), + ].melt( + id_vars=dedupe_list( + ["qid", "idx", color_by.name.lower(), facet_by.name.lower()], + ), + ) + + df2 = df2[df2["value"].notnull()] + + df_submit_start = df2[ + (df2["variable"] == "submitted_offset") + | (df2["variable"] == "started_offset") + ] + df_start_end = df2[ + (df2["variable"] == "started_offset") | (df2["variable"] == "ended_offset") + ] + df_end_processed = df2[ + (df2["variable"] == "ended_offset") + | (df2["variable"] == "processed_offset") + ] + + labs = {"x": "duration", "y": "job index"} + if title is not None: + labs["title"] = title + + gg_obj = ( + gg.ggplot(gg.aes(x="value", y="idx", group="factor(idx)")) + + gg.geom_line(df_submit_start, color="gray", size=bar_width, alpha=0.2) + + gg.geom_line( + df_start_end, + gg.aes(color=f"factor({color_by.name.lower()})"), + size=bar_width, + show_legend=not bool(no_legend), + ) + + gg.geom_line(df_end_processed, color="gray", size=bar_width, alpha=0.2) + + gg.labs(**labs) + + gg.labs(color=color_by.name.lower()) + + Plot._plot_theme( + theme=theme, + grid_lines=PlotGridLines.BOTH, + grid_axis="x", + ) + + gg.facet_grid( + facets=facet_by.name.lower() + "~", + labeller="label_both", + scales=facet_scale.name.lower(), + as_table=True, + ) + ) + + if not color_pal: + gg_obj += gg.scale_color_hue(h=0.65) + else: + n_colors = self.jobs_df[color_by.name.lower()].unique().size + + if len(color_pal) < n_colors: + log.warning("Insufficient number of colors; need at least %d", n_colors) + gg_obj += gg.scale_color_hue(h=0.65) + else: + gg_obj += gg.scale_color_manual(color_pal[:n_colors]) + + return gg_obj + + +def plot_jobs( + *args: list[Job], + title: str | None = None, + color_by: PlotColorBy = PlotColorBy.QID, + facet_by: PlotFacetBy = PlotFacetBy.QID, + facet_scale: PlotFacetScale = PlotFacetScale.FIXED, + theme: PlotTheme = PlotTheme.BW, + no_legend: bool = False, + bar_width: int = 1, + color_pal: list[str] | None = None, +) -> gg.ggplot: + """ + + Args: + title: + color_by: + facet_by: + facet_scale: + theme: + no_legend: + bar_width: + color_pal: a sequence of colors used to color each group of `color_by`. + + Examples: + >>> from ppqueue import Queue + >>> from ppqueue.plot import plot_jobs + >>> from time import sleep + ... + >>> with Queue() as queue: + ... q1_jobs = queue.map(sleep, [1, 2, 3, 4, 5]) + ... + >>> with Queue() as queue: + ... q2_jobs = queue.map(sleep, [1, 2, 3, 4, 5]) + ... + >>> plot = plot_jobs( + ... q1_jobs, q2_jobs, + ... title='Demo', + ... color_by=PlotColorBy.QID, + ... facet_by=PlotFacetBy.QID, + ... theme=PlotTheme.DARK, + ... bar_width=2, + ... color_pal=['red', 'blue'] + ... ) + ... + >>> print(plot) # doctest: +SKIP + """ + + return Plot(*args).build( + color_by=color_by, + facet_by=facet_by, + facet_scale=facet_scale, + no_legend=no_legend, + bar_width=bar_width, + title=title, + color_pal=color_pal, + theme=theme, + ) diff --git a/src/ezpq/py.typed b/src/ppqueue/py.typed similarity index 100% rename from src/ezpq/py.typed rename to src/ppqueue/py.typed diff --git a/src/ppqueue/queue.py b/src/ppqueue/queue.py new file mode 100644 index 0000000..384ccb4 --- /dev/null +++ b/src/ppqueue/queue.py @@ -0,0 +1,996 @@ +from __future__ import annotations + +import logging +import multiprocessing as mp +import threading +import time +import traceback +from heapq import heappop, heappush +from typing import Any, Callable, Sequence, Type +from uuid import uuid4 + +from tqdm.auto import tqdm + +from .job import Job +from .utils import get_logger, is_windows_os + +LOG = get_logger(__name__, level=logging.INFO) + + +class PulseTimer: + """Periodically runs a function in a background thread. + + ref: https://stackoverflow.com/a/13151299 + """ + + def __init__( + self, + *args: Any, + interval_ms: int, + fun: Callable[..., Any], + **kwargs: Any, + ): + self._timer: threading.Timer | None = None + self._interval: int = interval_ms + self._function: Callable[..., Any] = fun + self._args: tuple[Any, ...] = args + self._kwargs: dict[str, Any] = kwargs + self._is_enabled: bool = False + self._is_running: bool = False + + def _run(self) -> None: + self._is_running = False + self.start() + self._function(*self._args, **self._kwargs) + + def start(self) -> None: + if not self._is_running: + self._timer = threading.Timer(self._interval / 1000, self._run) + self._timer.start() + self._is_running = True + + self._is_enabled = True + + def stop(self) -> None: + if self._timer is not None: + self._timer.cancel() + + self._is_enabled = False + self._is_running = False + + @property + def is_running(self) -> bool: + return self._is_running + + @property + def is_enabled(self) -> bool: + return self._is_enabled + + +class Queue: + DEFAULT_GROUP: int | None = None + + def __init__( + self, + max_concurrent: int = mp.cpu_count(), + *, + max_size: int = 0, + engine: Type[threading.Thread] | Type[mp.Process] = threading.Thread, + name: str | None = None, + callback: Callable[[Job], Any] | None = None, + show_progress: bool = False, + drop_finished: bool = False, + stop_when_idle: bool = False, + pulse_freq_ms: int = 100, + no_start: bool = False, + ): + """ + + Args: + max_concurrent: max number of concurrently running jobs. + max_size: max size of the queue (default=0, unlimited). + engine: the engine used to run jobs; threads (default) or processes. + name: an identifier for this queue. + callback: a callable that is called immediately after each job is finished. + show_progress: global setting for showing progress bars. + drop_finished: if True, the queue will not store finished jobs for retrieval. + stop_when_idle: if True, the queue will stop the pulse when all jobs are finished. + pulse_freq_ms: the interval at which jobs are transitioned between internal queues. + no_start: if True, do not start the queue pulse on instantiation. + + Examples: + >>> from ppqueue import Queue + >>> from time import sleep + ... + >>> with Queue() as queue: + ... jobs = queue.map(sleep, [1, 2, 3, 4, 5]) + ... + >>> len(jobs) + 5 + """ + + self._qid: str = name if name else str(uuid4())[:8] + + self.show_progress: bool = show_progress + self._max_size: int = max_size + self._count_input: int = 0 + self._count_output: int = 0 + self._max_concurrent: int = max_concurrent + self._callback: Callable[..., Any] | None = callback + + self._lock: threading.Lock = ( + threading.Lock() + ) # https://opensource.com/article/17/4/grok-gil + + if engine is mp.Process and is_windows_os(): + LOG.warning( + ( + "multiprocessing performance is degraded on Windows systems. see: " + "https://docs.python.org/3/library/multiprocessing.html?highlight=process#the-spawn-and-forkserver-start-methods" + ), + ) + + self._engine: Type[mp.Process] | Type[threading.Thread] = engine + + self._waiting_groups: dict[int | None, list[Job]] = {None: []} + self._working_queue: dict[int | None, Job] = {} + self._finished_queue: list[Job] = [] + + self._drop_finished: bool = drop_finished + self._mp_manager: mp.Manager | None = None + + self._output: dict[int, Job] + + if self._engine is mp.Process: + self._mp_manager = mp.Manager() + self._output = self._mp_manager.dict() + else: + self._output = {} + + LOG.debug("Initialized queue with %d max_concurrent.", self._max_concurrent) + + self._pulse_freq_ms: int = pulse_freq_ms + self._timer: PulseTimer = PulseTimer( + interval_ms=self._pulse_freq_ms, + fun=self._pulse, + ) + + if not no_start: + self.start() + + self._stop_when_idle: bool = stop_when_idle + + LOG.debug("Initialized pulse.") + + # decorator + def __call__(self, fun: Callable[..., Any], *args: Any, **kwargs: Any): + self.start() + + def wrapped_f(iterable: Sequence[Any], *args: Any, **kwargs: Any) -> list[Job]: + for x in iterable: + self.enqueue(fun, args=[x, *args], kwargs=kwargs) + self.wait() + job_data = self.collect() + self.dispose() + return job_data + + return wrapped_f + + def __del__(self) -> None: + self.dispose() + + def start(self) -> None: + """Start the queue pulse.""" + self._timer.start() + + def stop(self) -> None: + """Stop the queue pulse.""" + self._timer.stop() + + def dispose(self) -> None: + """Stop running jobs, then clear the queue, then stop the queue pulse.""" + LOG.debug("Disposing") + + if self.is_running: + self._stop_all(wait=True) + self.stop() + + LOG.debug("Removed jobs.") + self._output = None + LOG.debug("Removed output.") + self._finished_queue.clear() # [:] = [] + LOG.debug("Removed finished.") + self._count_input = 0 + self._count_output = 0 + LOG.debug("Reset counters.") + + if self._mp_manager is not None: + self._mp_manager.shutdown() + + def _clear_waiting(self) -> None: + """Clear the queue of pending jobs.""" + + LOG.debug("Clearing waiting queue") + with self._lock: + keys = list(self._waiting_groups.keys()) + for k in keys: + group_jobs = self._waiting_groups.get(k) + for _ in range(len(group_jobs)): + job = heappop(group_jobs) + job.cancelled = True + job.process_timestamp = time.time() + if not self._drop_finished: + heappush(self._finished_queue, job) + else: + self._count_output += 1 + del self._waiting_groups[k] + + def _stop_all(self, *, wait: bool = True) -> None: + """Stop and remove all running and waiting jobs.""" + + self._clear_waiting() + + keys = list(self._working_queue.keys()) + for k in keys: + job = self._working_queue.get(k) + if job is not None: + job.stop() + + if wait: + self.wait() + + def __enter__(self) -> Queue: + return self + + def __exit__(self, *args: Any) -> None: + self.dispose() + + def __iter__(self) -> Queue: + return self + + def __next__(self) -> Job: + job: Job | None = self.dequeue() + if job is None: + raise StopIteration + return job + + def _pulse(self) -> None: + # TODO: document this better. + """Used internally; manages the queue system operations.""" + + with self._lock: + try: + if self._stop_when_idle and self.is_idle(): + self.stop() + else: + # stop expired jobs. + for job_id, job in self._working_queue.items(): + if job.is_expired(): + job.stop() + + for job_id in list(self._working_queue.keys()): + job = self._working_queue[job_id] + + if not job.is_running() and not job.is_processed(): + job.join() + if not job.cancelled: + try: + ( + stdout, + stderr, + exitcode, + timestamp, + ) = self._output.pop(job.idx) + job.result = stdout + job.error = stderr + job.exitcode = exitcode + job.finish_timestamp = timestamp + except KeyError: + job.exception_txt = str( + Exception( + "{}\n\nNo data for data; it may have exited" + " unexpectedly.".format(job.idx), + ), + ) + + if self._callback is not None: + try: + job.callback_result = self._callback(job) + except ( + Exception # pylint: disable=broad-exception-caught + ) as ex: + job.callback_result = str(ex) + + job.process_timestamp = time.time() + + LOG.debug("Completed job: %d", job.idx) + + if not self._drop_finished: + heappush(self._finished_queue, job) + else: + self._count_output += 1 + + del self._working_queue[job_id] + + if ( + job.group is not None + and job.group != self.DEFAULT_GROUP + ): + group_jobs: list[Job] = self._waiting_groups.get( + job.group, + ) + if group_jobs is not None: + next_job = None + parent_exitcode = job.exitcode + while len(group_jobs) > 0: + next_job = heappop(group_jobs) + + if ( + parent_exitcode == 0 + or not next_job.skip_on_group_error + ): + break + else: + next_job.cancelled = True + next_job.exitcode = parent_exitcode + next_job.error = ( + "skip_on_group_error = True and" + " preceding data ({}) exit code is {}".format( + job.idx, + parent_exitcode, + ) + ) + next_job.process_timestamp = time.time() + if not self._drop_finished: + heappush( + self._finished_queue, + next_job, + ) + else: + self._count_output += 1 + next_job = None + continue + + if len(group_jobs) == 0: + del self._waiting_groups[job.group] + + if next_job is not None: + self._working_queue[next_job.idx] = next_job + self._start_job(next_job) + + while ( + len(self._waiting_groups[self.DEFAULT_GROUP]) > 0 + and self.max_concurrent - self._count_working() > 0 + ): + job = heappop(self._waiting_groups[self.DEFAULT_GROUP]) + self._working_queue[job.idx] = job + self._start_job(job) + except: # pylint: disable=bare-except + self.stop() + LOG.error(traceback.format_exc()) + finally: + LOG.debug( + "waiting=%d; working=%d; finished=%d.", + self._count_waiting(), + self._count_working(), + self._count_finished(), + ) + + def _count_waiting(self) -> int: + """Get the number of pending jobs.""" + return sum(len(v) for _, v in self._waiting_groups.items()) + + def _count_working(self) -> int: + """Get the number of running jobs.""" + return len(self._working_queue) + + def _count_finished(self) -> int: + """Get the number of completed jobs.""" + return len(self._finished_queue) + + def _count_remaining(self) -> int: + """Get the number of unfinished jobs (i.e., waiting + working).""" + return self.size(waiting=True, working=True) + + def _sizes( + self, + *, + waiting: bool = False, + working: bool = False, + finished: bool = False, + ) -> list[int]: + """Returns the number of jobs in the corresponding queue(s). + + Args: + waiting: include jobs in the waiting queue? + - Accepts: bool + - Default: False + working: include jobs in the working table? + - Accepts: bool + - Default: False + finished: include jobs in the completed queue? + - Accepts: bool + - Default: False + + Note: when all are False, all jobs are counted (default). + + Returns: + int + """ + + counts = {} + + is_locked = False + + try: + to_tally = sum([waiting, working, finished]) + if to_tally != 1: + if to_tally == 0: + waiting, working, finished = True, True, True + # must lock when more than 1 component included. + is_locked = self._lock.acquire() + + if waiting: + counts["waiting"] = self._count_waiting() + if working: + counts["working"] = self._count_working() + if finished: + counts["finished"] = self._count_finished() + finally: + if is_locked: + self._lock.release() + + return list(counts.values()) + + def __len__(self) -> int: + return self.size() + + def size( + self, + *, + waiting: bool = False, + working: bool = False, + finished: bool = False, + ) -> int: + """Get the number of jobs in the queue in state: waiting, working, and/or finished. + + If no options are given, the total number of jobs in the queue is returned. + + Args: + waiting: include waiting jobs. + working: include working jobs. + finished: include finished jobs. + + Examples: + >>> from ppqueue import Queue + ... + >>> def add_nums(x: int, y: int) -> int: + ... return x + y + ... + >>> with Queue() as queue: + ... for i in range(5): + ... _ = queue.enqueue(add_nums, args=[i, 100]) + ... print(queue.size()) + 1 + 2 + 3 + 4 + 5 + """ + return sum(self._sizes(waiting=waiting, working=working, finished=finished)) + + def is_idle(self) -> bool: + return self._count_waiting() == 0 and self._count_working() == 0 + + def is_busy(self) -> bool: + """True if max concurrent limit is reached or if there are waiting jobs.""" + return self._count_waiting() > 0 or self.max_concurrent <= self._count_working() + + def is_empty(self) -> bool: + """True if there are no jobs in the queue system.""" + return self.size() == 0 + + def is_full(self) -> bool: + """True if the number of jobs in the queue system is equal to max_size.""" + return 0 < self._max_size <= self.size() + + def join(self, *args, **kwargs) -> int: + return self.wait(*args, **kwargs) + + def wait( + self, + *, + n: int = 0, + timeout: float = 0, + poll_ms: int = 0, + show_progress: bool | None = None, + ) -> int: + """Wait for jobs to finish. + + Args: + n: the number of jobs to wait for (default=0, all). + timeout: seconds to wait before raising `TimeoutError` (default=0, indefinitely). + poll_ms: milliseconds to pause between checks (default=100). + show_progress: if True, present a progress bar. + """ + if poll_ms is None or poll_ms <= 0: + poll_ms = self._pulse_freq_ms + elif poll_ms < self._pulse_freq_ms: + err: str = "`poll_ms` must be >= `ppqueue.Queue.pulse_freq_ms`" + raise ValueError(err) + + if show_progress is None: + show_progress = self.show_progress + + _fun: Callable[..., Any] | None = None + _target_value: int | None = None + _comparator: Callable[..., bool] | None = None + + if n <= 0: + _fun = self._count_remaining + _target_value = 0 + _comparator = int.__le__ + else: + _fun = self._count_finished + _target_value = n + _comparator = int.__ge__ + + current_value: int = _fun() + + if not _comparator(current_value, _target_value): + start = time.time() + + pb = None + + try: + if show_progress: + pb = tqdm(total=current_value, unit="op") + + while not _comparator(current_value, _target_value) and ( + timeout == 0 or time.time() - start < timeout + ): + time.sleep(poll_ms / 1000) + + tmp_value = _fun() + if pb is None: + current_value = tmp_value + else: + diff_value = current_value - tmp_value + if diff_value > 0: + current_value = tmp_value + pb.update(diff_value) + finally: + if pb: + pb.close() + + return current_value + + @staticmethod + def _job_wrapper( + _job: Job, + _output: dict[int, tuple[str | None, str | None, int, float]], + /, + *args: Any, + **kwargs: Any, + ) -> tuple[str | None, str | None, int, float]: + """Used internally to wrap data, capture output and any exception.""" + stdout: str | None = None + stderr: str | None = None + exitcode: int + timestamp: float + + try: + stdout = _job.fun(*args, **kwargs) + exitcode = 0 + except Exception as ex: # pylint: disable=broad-exception-caught + stderr = traceback.format_exc() + exitcode = -1 + if not _job.suppress_errors: + raise ex + finally: + timestamp = time.time() + _output[_job.idx] = (stdout, stderr, exitcode, timestamp) + + def _start_job(self, job: Job, /) -> None: + inner_job: mp.Process | threading.Thread = self._engine( + name=str(job.idx), + target=self._job_wrapper, + args=[job, self._output, *job.args], + kwargs=job.kwargs, + ) + + LOG.debug("starting job %d (name=%s)", job.idx, job.name) + inner_job.start() + + job.start_timestamp = time.time() + job.inner_job = inner_job + + def _submit(self, job: Job, /) -> int: + """Submits a job into the ppqueue.Queue system. + + Throws an exception if: + 1. the Queue uses a Thread job_runner and this data has a timeout (can't terminate Threads), + 2. the Queue max_size will be exceeded after adding this job. + + Returns: + The number of jobs submitted to the queue. + """ + + assert not (self._engine is threading.Thread and job.timeout > 0) + + if self.is_full(): + raise OverflowError("Max queue size exceeded.") + + job.submit_timestamp = time.time() + + job.qid = self._qid + self._count_input += 1 + job.idx = self._count_input + + if job.name is None: + job.name = job.idx + + LOG.debug("queuing job %d (name=%s)", job.idx, job.name) + + group_jobs = self._waiting_groups.get(job.group) + if group_jobs is not None: + heappush(group_jobs, job) + else: + group_jobs = [] + self._waiting_groups[job.group] = group_jobs + + # if this is the first job in this group, + # it should be pushed to the default group. + heappush(self._waiting_groups[self.DEFAULT_GROUP], job) + + return job.idx + + def enqueue( + self, + fun: Callable[..., Any], + /, + args: Sequence[Any] | None = None, + kwargs: dict[str, Any] | None = None, + name: str | None = None, + priority: int = 100, + group: int | None = None, + timeout: float = 0, + suppress_errors: bool = False, + skip_on_group_error: bool = False, + ) -> int: + """Adds a job to the queue. + + Args: + args: + kwargs: + name: + priority: + group: + timeout: + suppress_errors: + skip_on_group_error: + + Examples: + >>> from ppqueue import Queue + ... + >>> def add_nums(x: int, y: int) -> int: + ... return x + y + ... + >>> with Queue() as queue: + ... for i in range(5): + ... _ = queue.enqueue(add_nums, args=[i, 100]) + ... + ... jobs = queue.collect(wait=True) + ... + >>> [job.result for job in jobs] + [100, 101, 102, 103, 104] + """ + job = Job( + fun=fun, + args=args, + kwargs=kwargs, + name=name, + priority=priority, + group=group, + timeout=timeout, + suppress_errors=suppress_errors, + skip_on_group_error=skip_on_group_error, + ) + + return self._submit(job) + + def put(self, *args, **kwargs) -> int: + """Alias for `enqueue`. Adds a job to the queue. + + Examples: + >>> from ppqueue import Queue + ... + >>> def add_nums(x: int, y: int) -> int: + ... return x + y + ... + >>> with Queue() as queue: + ... for i in range(5): + ... _ = queue.put(add_nums, args=[i, 100]) + ... jobs = queue.collect(wait=True) + ... + >>> [job.result for job in jobs] + [100, 101, 102, 103, 104] + """ + + return self.enqueue(*args, **kwargs) + + def map( + self, + fun: Callable[..., Any], + iterable: Sequence[Any], + /, + *args: Any, + timeout: float = 0, + show_progress: bool | None = None, + **kwargs: Any, + ) -> list[Job]: + """Submits many jobs to the queue -- one for each item in the iterable. Waits for all to finish, then returns the results. + + Args: + fun: + iterable: + timeout: + show_progress: + + Examples: + >>> from ppqueue import Queue + >>> from time import sleep + ... + >>> with Queue() as queue: + ... jobs = queue.map(sleep, [1, 2, 3, 4, 5]) + ... + >>> len(jobs) + 5 + """ + for x in iterable: + job = Job( + fun=fun, + args=[x, *args], + kwargs=dict(kwargs), + timeout=timeout, + ) + self._submit(job) + + return self.collect(wait=True, show_progress=show_progress) + + def starmap( + self, + fun: Callable[..., Any], + iterable: Sequence[Sequence[Any]], + /, + *args: Any, + timeout: float = 0, + show_progress: bool | None = None, + **kwargs: Any, + ) -> list[Job]: + """Submits many jobs to the queue -- one for each sequence in the iterable. Waits for all to finish, then returns the results. + + Args: + fun: + iterable: + timeout: + show_progress: + + Examples: + >>> from ppqueue import Queue + ... + >>> def add_nums(x: int, y: int) -> int: + ... return x + y + ... + >>> with Queue() as queue: + ... jobs = queue.starmap( + ... add_nums, [(1, 2), (3, 4)] + ... ) + ... + >>> [job.result for job in jobs] + [3, 7] + """ + for x in iterable: + job = Job( + fun=fun, + args=[*x, *args], + kwargs=dict(kwargs), + timeout=timeout, + ) + self._submit(job) + + return self.collect(wait=True, show_progress=show_progress) + + def starmapkw( + self, + fun: Callable[..., Any], + iterable: Sequence[dict[str, Any]], + /, + *args: Any, + timeout: float = 0, + show_progress: bool | None = None, + **kwargs: Any, + ) -> list[Job]: + """Submits many jobs to the queue -- one for each dictionary in the iterable. Waits for all to finish, then returns the results. + + Args: + fun: + iterable: + timeout: + show_progress: + + Examples: + >>> from ppqueue import Queue + >>> from time import sleep + ... + >>> def add_nums(x: int, y: int) -> int: + ... return x + y + ... + >>> with Queue() as queue: + ... jobs = queue.starmapkw( + ... add_nums, [{'x': 1, 'y': 2}, {'x': 3, 'y': 4}] + ... ) + ... + >>> [job.result for job in jobs] + [3, 7] + """ + for x in iterable: + job = Job( + fun=fun, + args=list(args), + kwargs={**x, **kwargs}, + timeout=timeout, + ) + self._submit(job) + + return self.collect(wait=True, show_progress=show_progress) + + def dequeue( + self, + *, + wait: bool = False, + _peek: bool = False, + **kwargs: Any, + ) -> Job | None: + """Removes and returns the job with the highest priority from the queue. + + Args: + wait: + **kwargs: passed to `Queue.wait` + + Examples: + >>> from ppqueue import Queue + ... + >>> def add_nums(x: int, y: int) -> int: + ... return x + y + ... + >>> with Queue() as queue: + ... for i in range(5): + ... _ = queue.enqueue(add_nums, args=[i, 100]) + ... + ... jobs = [queue.dequeue(wait=True) for _ in range(queue.size())] + ... + >>> [job.result for job in jobs] + [100, 101, 102, 103, 104] + """ + + if self._count_finished() == 0: + if not wait: + return None + + kwargs["show_progress"] = False + self.wait(n=1, **kwargs) + + job: Job + if _peek: + job = self._finished_queue[0] + else: + job = heappop(self._finished_queue) + self._count_output += 1 + + return job + + def pop(self, *args: Any, **kwargs: Any) -> Job | None: + """Alias for `dequeue`. Removes and returns the job with the highest priority from the queue. + + Examples: + >>> from ppqueue import Queue + ... + >>> def add_nums(x: int, y: int) -> int: + ... return x + y + ... + >>> with Queue() as queue: + ... for i in range(5): + ... _ = queue.put(add_nums, args=[i, 100]) + ... + ... jobs = [queue.pop(wait=True) for _ in range(queue.size())] + ... + >>> [job.result for job in jobs] + [100, 101, 102, 103, 104] + """ + return self.dequeue(*args, **kwargs) + + def peek(self, *args: Any, **kwargs: Any) -> Job | None: + """Returns the job with the highest priority from the queue. Similar to `enqueue` / `pop`, but the job remains in the queue. + + Args: + *args: + **kwargs: + + Examples: + >>> from ppqueue import Queue + ... + >>> def add_nums(x: int, y: int) -> int: + ... return x + y + ... + >>> with Queue() as queue: + ... for i in range(5): + ... _ = queue.put(add_nums, args=[i, 100]) + ... + ... print('Before:', queue.size()) + ... + ... job = queue.peek(wait=True) + ... + ... print('After:', queue.size()) + ... + Before: 5 + After: 5 + >>> job.result + 100 + """ + return self.dequeue(*args, **kwargs, _peek=True) + + def collect(self, n: int = 0, wait: bool = False, **kwargs: Any) -> list[Job]: + """Removes and returns all finished jobs from the queue. + + Args: + n: collect this many jobs (default=0, all) + wait: If True, block until this many jobs are finished. Else, immediately return all finished. + **kwargs: kwargs given to `Queue.wait`. + + Examples: + >>> from ppqueue import Queue + ... + >>> def add_nums(x: int, y: int) -> int: + ... return x + y + ... + >>> with Queue() as queue: + ... for i in range(5): + ... _ = queue.enqueue(add_nums, args=[i, 100]) + ... + ... jobs = queue.collect(wait=True) + ... + >>> type(jobs) + + >>> len(jobs) + 5 + """ + + if wait: + self.wait(n=n, **kwargs) + + n_finished: int = self._count_finished() + + n_to_collect: int = min(n, n_finished) if n > 0 else n_finished + + return list(next(self) for _ in range(n_to_collect)) + + @property + def max_concurrent(self) -> int: + return self._max_concurrent + + @max_concurrent.setter + def max_concurrent(self, value: int): + self._max_concurrent = value + + @property + def max_size(self) -> int: + return self._max_size + + @max_size.setter + def max_size(self, value: int) -> None: + self._max_size = value + + @property + def is_running(self) -> bool: + return self._timer.is_enabled diff --git a/src/ezpq/utils.py b/src/ppqueue/utils.py similarity index 81% rename from src/ezpq/utils.py rename to src/ppqueue/utils.py index 1edf314..bb1e6c6 100644 --- a/src/ezpq/utils.py +++ b/src/ppqueue/utils.py @@ -1,7 +1,8 @@ -import csv +from __future__ import annotations + import logging import os -from typing import Any, Dict, List, Optional, Union +from typing import List, Optional, TypeVar, Union def get_logger(name: str, level: Optional[int] = None) -> logging.Logger: @@ -91,18 +92,8 @@ def compare_by(object1: object, object2: object, by: List[str], _state: int = 0) return diff -def log_csv(data: Dict[str, Any], path: str = "ezpq.log", append: bool = True): - csv_exists: bool = os.path.exists(path) - - mode: str = "x" # create - - if csv_exists: - mode = "a" if append else "w" # append else write. - - with open(path, mode, encoding="utf8") as f: - writer = csv.DictWriter(f, fieldnames=list(data.keys())) +T = TypeVar("T") - if not csv_exists: - writer.writeheader() - writer.writerow(data) +def dedupe_list(l: list[T]) -> list[T]: + return list(dict.fromkeys(l).keys()) diff --git a/tests/EzpqTestCases.py b/tests/common.py similarity index 51% rename from tests/EzpqTestCases.py rename to tests/common.py index a2bdd88..2cffae8 100644 --- a/tests/EzpqTestCases.py +++ b/tests/common.py @@ -2,12 +2,15 @@ from typing import List, Tuple from unittest import TestCase -import ezpq -from ezpq.utils import get_logger +import ppqueue +from ppqueue.utils import get_logger LOG = get_logger(__name__) +# pylint: disable=protected-access + + def return_me(x): return x @@ -22,10 +25,10 @@ def get_sample_data(n: int = 31) -> Tuple[int, ...]: return tuple(sample) -class EzpqTestCases(object): +class PPQueueTestCases(object): def setUp(self): - self.queue: ezpq.Queue - self.input: Tuple[int] + self.queue: ppqueue.Queue + self.input: Tuple[int, ...] raise NotImplementedError() def test_priority(self): @@ -36,8 +39,8 @@ def test_priority(self): TestCase().assertFalse(self.queue.is_running) for i, x in enumerate(self.input): - self.queue.put( - fun=return_me, + self.queue.enqueue( + return_me, args=x, priority=-i, ) # should result in reversed inputs. @@ -48,101 +51,101 @@ def test_priority(self): self.queue.wait() - output = tuple(job.output for job in self.queue.collect()) + output = tuple(job.result for job in self.queue.collect()) TestCase().assertTupleEqual(tuple(reversed(self.input)), output) - TestCase().assertEqual(len(self.input), self.queue.count_input()) - TestCase().assertEqual(self.queue.count_input(), self.queue.count_output()) + TestCase().assertEqual(len(self.input), self.queue._count_input) + TestCase().assertEqual(self.queue._count_input, self.queue._count_output) def test_map(self): - job_data = self.queue.map(fun=return_me, iterable=self.input) + job_data = self.queue.map(return_me, self.input) - output = tuple(job.output for job in job_data) + output = tuple(job.result for job in job_data) TestCase().assertTupleEqual(self.input, output) - TestCase().assertEqual(len(self.input), self.queue.count_input()) - TestCase().assertEqual(self.queue.count_input(), self.queue.count_output()) + TestCase().assertEqual(len(self.input), self.queue._count_input) + TestCase().assertEqual(self.queue._count_input, self.queue._count_output) def test_starmap(self): - job_data = self.queue.starmap(fun=return_me, iterable=[[x] for x in self.input]) + job_data = self.queue.starmap(return_me, [[x] for x in self.input]) - output = tuple(job.output for job in job_data) + output = tuple(job.result for job in job_data) TestCase().assertTupleEqual(self.input, output) - TestCase().assertEqual(len(self.input), self.queue.count_input()) - TestCase().assertEqual(self.queue.count_input(), self.queue.count_output()) + TestCase().assertEqual(len(self.input), self.queue._count_input) + TestCase().assertEqual(self.queue._count_input, self.queue._count_output) def test_starmapkw(self): job_data = self.queue.starmapkw( - fun=return_me, - iterable=[{"x": x} for x in self.input], + return_me, + [{"x": x} for x in self.input], ) - output = tuple(job.output for job in job_data) + output = tuple(job.result for job in job_data) TestCase().assertTupleEqual(self.input, output) - TestCase().assertEqual(len(self.input), self.queue.count_input()) - TestCase().assertEqual(self.queue.count_input(), self.queue.count_output()) + TestCase().assertEqual(len(self.input), self.queue._count_input) + TestCase().assertEqual(self.queue._count_input, self.queue._count_output) - def test_lanes(self): + def test_groups(self): for i, x in enumerate(self.input): - self.queue.put( - fun=return_me, + self.queue.enqueue( + return_me, args=x, - lane=i % self.queue.max_concurrent, + group=i % self.queue.max_concurrent, ) # returns in order self.queue.wait() - output = tuple(x.output for x in self.queue.collect()) + output = tuple(x.result for x in self.queue.collect()) TestCase().assertTupleEqual(self.input, output) - TestCase().assertEqual(len(self.input), self.queue.count_input()) - TestCase().assertEqual(self.queue.count_input(), self.queue.count_output()) + TestCase().assertEqual(len(self.input), self.queue._count_input) + TestCase().assertEqual(self.queue._count_input, self.queue._count_output) - def test_lane_error(self): + def test_group_error(self): this_input = list(self.input) this_input[int(len(this_input) / 2)] = 0 for i, x in enumerate(this_input): - self.queue.put( + self.queue.enqueue( reciprocal, x, - lane=i % 3, + group=i % 3, suppress_errors=True, - skip_on_lane_error=True, + skip_on_group_error=True, ) self.queue.wait() output = self.queue.collect() TestCase().assertGreater( len(self.input), - len([x for x in output if x.started is not None]), + len([x for x in output if x.start_timestamp is not None]), ) def test_size(self): for x in self.input: - self.queue.put(fun=return_me, args=x) + self.queue.enqueue(return_me, args=x) sizes = [ self.queue.size() for _ in range(len(self.input)) - for _ in [self.queue.get(wait=True)] + for _ in [self.queue.dequeue(wait=True)] ] # numbers in `sizes` should decrement by 1 until reaching 0. TestCase().assertListEqual(sizes, list(reversed(range(len(self.input))))) - TestCase().assertEqual(len(self.input), self.queue.count_input()) - TestCase().assertEqual(self.queue.count_input(), self.queue.count_output()) + TestCase().assertEqual(len(self.input), self.queue._count_input) + TestCase().assertEqual(self.queue._count_input, self.queue._count_output) def test_terminate(self): for x in self.input: - self.queue.put(fun=return_me, args=x, priority=x) - self.queue.stop_all() + self.queue.enqueue(return_me, args=x, priority=x) + self.queue._stop_all() output = self.queue.collect() TestCase().assertListEqual( @@ -152,4 +155,4 @@ def test_terminate(self): def test_empty(self): TestCase().assertEqual(self.queue.size(), 0) - TestCase().assertTrue(self.queue.empty()) + TestCase().assertTrue(self.queue.is_empty()) diff --git a/tests/conftest.py b/tests/conftest.py deleted file mode 100644 index f1efeb3..0000000 --- a/tests/conftest.py +++ /dev/null @@ -1,69 +0,0 @@ -import os -import re -import shutil -from pathlib import Path -from typing import Dict, Generator, Pattern - -import pytest -from _pytest.config import Config -from packaging.version import VERSION_PATTERN - - -@pytest.fixture(name="root_dir", scope="session") -def fixture_root_dir(pytestconfig: Config) -> Path: - test_dir: Path - test_paths: None | str | list[str] = pytestconfig.inicfg.get("testpaths") - if not test_paths: - default_dir: Path = Path("tests") - if not pytestconfig.args: - test_dir = default_dir - else: - first_arg: Path = Path(pytestconfig.args[0]) - test_dir = first_arg if first_arg.is_dir() else default_dir - elif isinstance(test_paths, list): - test_dir = Path(test_paths[0]) - else: - assert isinstance(test_paths, str) - test_dir = Path(test_paths) - - test_dir = (pytestconfig.rootpath / test_dir).absolute() - assert test_dir.is_dir() - return test_dir - - -@pytest.fixture(name="resources_dir", scope="session") -def fixture_resources_dir(root_dir: Path) -> Path: - res_dir: Path = root_dir / "resources" - assert res_dir.is_dir() - return res_dir - - -@pytest.fixture(name="version_pattern", scope="session") -def fixture_version_pattern() -> Pattern: - return re.compile( - r"^\s*" + VERSION_PATTERN + r"\s*$", - flags=re.VERBOSE | re.IGNORECASE, - ) - - -@pytest.fixture(name="clean_dir") -def _fixture_clean_dir(tmp_path: Path) -> Generator[None, None, None]: - cwd_og: Path = Path.cwd() - if tmp_path.exists(): - shutil.rmtree(tmp_path) - tmp_path.mkdir() - os.chdir(tmp_path) - - yield - os.chdir(cwd_og) - shutil.rmtree(tmp_path) - - -@pytest.fixture(name="env", autouse=True) -def _fixture_env() -> Generator[None, None, None]: - env_og: Dict[str, str] = os.environ.copy() - - yield - - os.environ.clear() - os.environ.update(env_og) diff --git a/tests/test_ezpq.py b/tests/test_ezpq.py deleted file mode 100644 index 2b69632..0000000 --- a/tests/test_ezpq.py +++ /dev/null @@ -1,42 +0,0 @@ -import unittest -from multiprocessing import Process -from threading import Thread -from typing import Tuple - -import ezpq -from ezpq.utils import get_logger, is_windows_os -from tests.EzpqTestCases import EzpqTestCases, get_sample_data - -LOG = get_logger(__name__) - - -class TestThreading(unittest.TestCase, EzpqTestCases): - def setUp(self): - LOG.info(self.id()) - self.input: Tuple[int] = get_sample_data() - self.queue = ezpq.Queue(engine=Thread, max_concurrent=3) - - def tearDown(self): - self.queue.dispose() - self.assertFalse(self.queue.is_running) - del self.queue - - -@unittest.skipIf( - is_windows_os(), - "multiprocessing tests are reliable on a windows os; skipping.", -) -class TestProcessing(unittest.TestCase, EzpqTestCases): - def setUp(self): - LOG.info(self.id()) - self.input: Tuple[int] = get_sample_data() - self.queue = ezpq.Queue(engine=Process, max_concurrent=3) - - def tearDown(self): - self.queue.dispose() - self.assertFalse(self.queue.is_running) - del self.queue - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_plot.py b/tests/test_plot.py index 1e6ba6d..3b561bc 100644 --- a/tests/test_plot.py +++ b/tests/test_plot.py @@ -3,9 +3,11 @@ from typing import Tuple from unittest.case import TestCase -import ezpq -from ezpq.utils import get_logger -from tests.EzpqTestCases import get_sample_data +import ppqueue +from ppqueue.plot import plot_jobs +from ppqueue.utils import get_logger + +from .common import get_sample_data LOG = get_logger(__name__) @@ -20,11 +22,11 @@ def setUp(self): self.input: Tuple[int] = get_sample_data() def test_plot(self): - with ezpq.Queue(engine=threading.Thread, max_concurrent=3) as queue: + with ppqueue.Queue(engine=threading.Thread, max_concurrent=3) as queue: job_data = queue.map(return_me, self.input) TestCase().assertEqual(len(self.input), len(job_data)) - plot = ezpq.Plot(job_data).build() + plot = plot_jobs(job_data) TestCase().assertIsNotNone(plot) diff --git a/tests/test_queue_processes.py b/tests/test_queue_processes.py new file mode 100644 index 0000000..56e626a --- /dev/null +++ b/tests/test_queue_processes.py @@ -0,0 +1,30 @@ +import unittest +from multiprocessing import Process +from typing import Tuple + +from ppqueue import Queue +from ppqueue.utils import get_logger, is_windows_os + +from .common import PPQueueTestCases, get_sample_data + +LOG = get_logger(__name__) + + +@unittest.skipIf( + is_windows_os(), + "multiprocessing tests are reliable on a windows os; skipping.", +) +class TestProcessing(unittest.TestCase, PPQueueTestCases): + def setUp(self): + LOG.info(self.id()) + self.input: Tuple[int, ...] = get_sample_data() + self.queue = Queue(engine=Process, max_concurrent=3) + + def tearDown(self): + self.queue.dispose() + self.assertFalse(self.queue.is_running) + del self.queue + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_queue_threads.py b/tests/test_queue_threads.py new file mode 100644 index 0000000..0036003 --- /dev/null +++ b/tests/test_queue_threads.py @@ -0,0 +1,26 @@ +import unittest +from threading import Thread +from typing import Tuple + +from ppqueue import Queue +from ppqueue.utils import get_logger + +from .common import PPQueueTestCases, get_sample_data + +LOG = get_logger(__name__) + + +class TestThreading(unittest.TestCase, PPQueueTestCases): + def setUp(self): + LOG.info(self.id()) + self.input: Tuple[int, ...] = get_sample_data() + self.queue = Queue(engine=Thread, max_concurrent=3) + + def tearDown(self): + self.queue.dispose() + self.assertFalse(self.queue.is_running) + del self.queue + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_utils.py b/tests/test_utils.py index f229043..1e09902 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -2,8 +2,8 @@ import unittest from unittest.case import TestCase -from ezpq import Job -from ezpq.utils import compare, compare_by, get_logger +from ppqueue import Job +from ppqueue.utils import compare, compare_by, dedupe_list, get_logger LOG = get_logger(__name__) @@ -32,13 +32,15 @@ def test_compare_by(self): obj1: Job = Job(fun=None) obj2: Job = Job(fun=None) - obj1._priority = 1 - obj2._priority = 1 - obj1._idx = 1 - obj2._idx = 1 + obj1.priority = 1 + obj2.priority = 1 + obj1.idx = 1 + obj2.idx = 1 TestCase().assertEqual(0, compare_by(obj1, obj2, by=["priority", "idx"])) - obj2._idx = 2 + obj2.idx = 2 TestCase().assertEqual(-1, compare_by(obj1, obj2, by=["priority", "idx"])) - # TODO: `test_log_csv` + def test_dedupe_list(self): + TestCase().assertEqual([1, 2, 3], dedupe_list([1, 2, 3])) + TestCase().assertEqual([1, 2, 3], dedupe_list([1, 2, 3, 2, 1]))