# HG changeset patch
# User goeckslab
# Date 1765324187 0
# Node ID 375c36923da1995276ab4b118c8d2211ad48cdc0
planemo upload for repository https://github.com/goeckslab/gleam.git commit 1c6c1ad7a1b2bd3645aa0eafa2167784820b52e0
diff -r 000000000000 -r 375c36923da1 Dockerfile
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/Dockerfile Tue Dec 09 23:49:47 2025 +0000
@@ -0,0 +1,89 @@
+FROM nvidia/cuda:11.8.0-cudnn8-runtime-ubuntu22.04
+
+ENV DEBIAN_FRONTEND=noninteractive
+ENV NVIDIA_VISIBLE_DEVICES=all
+ENV NVIDIA_DRIVER_CAPABILITIES=compute,utility
+
+# Install system dependencies, Python, and Chromium bits needed for Kaleido
+RUN apt-get update && apt-get install -y --no-install-recommends \
+ python3 \
+ python3-pip \
+ python3-dev \
+ python3-venv \
+ ca-certificates \
+ build-essential \
+ gnupg \
+ libblas-dev \
+ liblapack-dev \
+ libgomp1 \
+ libopenblas-dev \
+ unzip \
+ pkg-config \
+ libfreetype6-dev \
+ libpng-dev \
+ libqhull-dev \
+ fonts-liberation \
+ libasound2 \
+ libatk-bridge2.0-0 \
+ libatk1.0-0 \
+ libcairo2 \
+ libcups2 \
+ libdbus-1-3 \
+ libexpat1 \
+ libfontconfig1 \
+ libgbm1 \
+ libgcc1 \
+ libglib2.0-0 \
+ libgtk-3-0 \
+ libnspr4 \
+ libnss3 \
+ libpango-1.0-0 \
+ libpangocairo-1.0-0 \
+ libstdc++6 \
+ libx11-6 \
+ libx11-xcb1 \
+ libxcb1 \
+ libxcomposite1 \
+ libxcursor1 \
+ libxdamage1 \
+ libxext6 \
+ libxfixes3 \
+ libxi6 \
+ libxrandr2 \
+ libxrender1 \
+ libxtst6 \
+ lsb-release \
+ wget \
+ xdg-utils \
+ && ln -sf /usr/bin/python3 /usr/bin/python \
+ && ln -sf /usr/bin/pip3 /usr/bin/pip \
+ && rm -rf /var/lib/apt/lists/*
+
+# Pin setuptools <81 to avoid pkg_resources warnings and upgrade pip/wheel
+RUN pip install --no-cache-dir 'setuptools<81.0.0' && \
+ pip install --no-cache-dir --upgrade pip wheel
+
+# Install GPU-enabled PyTorch stack before AutoGluon so it picks up CUDA
+RUN pip install --no-cache-dir \
+ --index-url https://download.pytorch.org/whl/cu118 \
+ --extra-index-url https://pypi.org/simple \
+ torch==2.1.2 \
+ torchvision==0.16.2 \
+ torchaudio==2.1.2
+
+# Core Python dependencies
+RUN pip install --no-cache-dir \
+ autogluon==1.4.0 \
+ pyarrow==20.0.0 \
+ matplotlib \
+ seaborn \
+ shap
+
+# Update kaleido for plotting support
+RUN pip install --no-cache-dir --upgrade kaleido
+
+RUN apt-get update && apt-get install -y curl \
+ && curl -fsSL https://deb.nodesource.com/setup_18.x | bash - \
+ && apt-get install -y nodejs \
+ && npm install -g yarn \
+ && rm -rf /var/lib/apt/lists/*
diff -r 000000000000 -r 375c36923da1 LICENSE
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/LICENSE Tue Dec 09 23:49:47 2025 +0000
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+
+ Copyright (C)
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ Copyright (C)
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+.
diff -r 000000000000 -r 375c36923da1 README.md
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/README.md Tue Dec 09 23:49:47 2025 +0000
@@ -0,0 +1,2 @@
+# Galaxy-AutoGluon
+This repository provides tools to integrate Autogluon, an automated machine learning framework, into the Galaxy workflow environment
diff -r 000000000000 -r 375c36923da1 feature_help_modal.py
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/feature_help_modal.py Tue Dec 09 23:49:47 2025 +0000
@@ -0,0 +1,130 @@
+import base64
+
+
+def get_metrics_help_modal() -> str:
+ # The HTML structure of the modal
+ modal_html = """
+
+
+ ×
+
How to read this Multimodal Learner report
+
+
Tabs & layout
+
Model Metric Summary and Config: Top-level metrics and the key run settings (target column, backbones, presets).
+
Train and Validation Summary: Learning curves plus combined ROC/PR/Calibration (binary), and any remaining diagnostics.
+
Test Summary: Test metrics table followed by the ROC/PR charts with your chosen threshold marked, and the Prediction Confidence histogram.
+
+
Dataset Overview
+
Shows label counts across Train/Validation/Test so you can quickly spot imbalance or missing splits.
+
+
Learning curves
+
Label Accuracy & Loss: Train (blue) and Validation (orange) trends. Parallel curves that plateau suggest stable training; large gaps can indicate overfitting.
+
+
Binary diagnostics (Train vs Validation)
+
ROC Curve: Both splits on one plot. Higher and leftward is better. The red “x” marks the decision threshold when provided.
+
Precision–Recall: Both splits on one plot; more informative on imbalance. Red marker shows the threshold point.
+
Calibration: Ideally near the diagonal; deviations show over/under-confidence.
+
Threshold Plot (Validation): Explore precision/recall/F1 vs threshold; use to pick a balanced operating point.
+
+
Test tab highlights
+
Metrics table: Thresholded metrics for the test set.
+
ROC & PR: Thick lines, red marker and annotation for the selected threshold.
+
Prediction Confidence: Histogram of max predicted probabilities (as % of samples) to spot over/under-confidence.
+
+
Threshold tips
+
+
Use the Validation curves to choose a threshold that balances precision/recall for your use case.
+
Threshold marker/annotation appears on ROC/PR plots when you pass --threshold (binary tasks).
+
+
+
When to worry
+
+
Huge train/val gaps on learning curves → possible overfitting.
+
Calibration far from diagonal → predicted probabilities may be poorly calibrated.
+
Very imbalanced label counts → focus on PR curves and per-class metrics (if enabled).
+
+
+
+
+"""
+ # The CSS needed to style and hide/show the modal
+ modal_css = """
+
+"""
+ # The JavaScript to open/close the modal on button click
+ modal_js = """
+
+"""
+ return modal_css + modal_html + modal_js
+
+
+def encode_image_to_base64(image_path):
+ with open(image_path, "rb") as img_file:
+ return base64.b64encode(img_file.read()).decode("utf-8")
+
+
+def generate_feature_importance(*args, **kwargs):
+ return "
Feature importance visualizations are not supported for this MultiModal workflow.
"
diff -r 000000000000 -r 375c36923da1 feature_importance.py
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/feature_importance.py Tue Dec 09 23:49:47 2025 +0000
@@ -0,0 +1,11 @@
+"""Feature importance visualization utilities."""
+
+import pandas as pd
+
+
+def build_feature_importance_html(predictor, df_train: pd.DataFrame, label_column: str) -> str:
+ """Feature importance is not currently available for the MultiModal workflow."""
+ return (
+ "
Feature importance visualization is not supported for the current "
+ "MultiModal workflow.
"
+ )
diff -r 000000000000 -r 375c36923da1 metrics_logic.py
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/metrics_logic.py Tue Dec 09 23:49:47 2025 +0000
@@ -0,0 +1,313 @@
+from collections import OrderedDict
+from typing import Dict, Optional, Tuple
+
+import numpy as np
+import pandas as pd
+from sklearn.metrics import (
+ accuracy_score,
+ average_precision_score,
+ cohen_kappa_score,
+ confusion_matrix,
+ f1_score,
+ log_loss,
+ matthews_corrcoef,
+ mean_absolute_error,
+ mean_squared_error,
+ median_absolute_error,
+ precision_score,
+ r2_score,
+ recall_score,
+ roc_auc_score,
+)
+
+
+# -------------------- Transparent Metrics (task-aware) -------------------- #
+
+def _safe_y_proba_to_array(y_proba) -> Optional[np.ndarray]:
+ """Convert predictor.predict_proba output (array/DataFrame/dict) to np.ndarray or None."""
+ if y_proba is None:
+ return None
+ if isinstance(y_proba, pd.DataFrame):
+ return y_proba.values
+ if isinstance(y_proba, (list, tuple)):
+ return np.asarray(y_proba)
+ if isinstance(y_proba, np.ndarray):
+ return y_proba
+ if isinstance(y_proba, dict):
+ try:
+ return np.vstack([np.asarray(v) for _, v in sorted(y_proba.items())]).T
+ except Exception:
+ return None
+ return None
+
+
+def _specificity_from_cm(cm: np.ndarray) -> float:
+ """Specificity (TNR) for binary confusion matrix."""
+ if cm.shape != (2, 2):
+ return np.nan
+ tn, fp, fn, tp = cm.ravel()
+ denom = (tn + fp)
+ return float(tn / denom) if denom > 0 else np.nan
+
+
+def _compute_regression_metrics(y_true: np.ndarray, y_pred: np.ndarray) -> "OrderedDict[str, float]":
+ mse = mean_squared_error(y_true, y_pred)
+ rmse = float(np.sqrt(mse))
+ mae = mean_absolute_error(y_true, y_pred)
+ # Avoid division by zero using clip
+ mape = float(np.mean(np.abs((y_true - y_pred) / np.clip(np.abs(y_true), 1e-12, None))) * 100.0)
+ r2 = r2_score(y_true, y_pred)
+ medae = median_absolute_error(y_true, y_pred)
+
+ metrics = OrderedDict()
+ metrics["MSE"] = mse
+ metrics["RMSE"] = rmse
+ metrics["MAE"] = mae
+ metrics["MAPE_%"] = mape
+ metrics["R2"] = r2
+ metrics["MedianAE"] = medae
+ return metrics
+
+
+def _compute_binary_metrics(
+ y_true: pd.Series,
+ y_pred: pd.Series,
+ y_proba: Optional[np.ndarray],
+ predictor
+) -> "OrderedDict[str, float]":
+ metrics = OrderedDict()
+ classes_sorted = np.sort(pd.unique(y_true))
+ # Choose the lexicographically larger class as "positive"
+ pos_label = classes_sorted[-1]
+
+ metrics["Accuracy"] = accuracy_score(y_true, y_pred)
+ metrics["Precision"] = precision_score(y_true, y_pred, pos_label=pos_label, zero_division=0)
+ metrics["Recall_(Sensitivity/TPR)"] = recall_score(y_true, y_pred, pos_label=pos_label, zero_division=0)
+ metrics["F1-Score"] = f1_score(y_true, y_pred, pos_label=pos_label, zero_division=0)
+
+ try:
+ cm = confusion_matrix(y_true, y_pred, labels=classes_sorted)
+ metrics["Specificity_(TNR)"] = _specificity_from_cm(cm)
+ except Exception:
+ metrics["Specificity_(TNR)"] = np.nan
+
+ # Probabilistic metrics
+ if y_proba is not None:
+ # pick column of positive class
+ if y_proba.ndim == 1:
+ pos_scores = y_proba
+ else:
+ pos_col_idx = -1
+ try:
+ if hasattr(predictor, "class_labels") and predictor.class_labels:
+ pos_col_idx = list(predictor.class_labels).index(pos_label)
+ except Exception:
+ pos_col_idx = -1
+ pos_scores = y_proba[:, pos_col_idx]
+ try:
+ metrics["ROC-AUC"] = roc_auc_score(y_true == pos_label, pos_scores)
+ except Exception:
+ metrics["ROC-AUC"] = np.nan
+ try:
+ metrics["PR-AUC"] = average_precision_score(y_true == pos_label, pos_scores)
+ except Exception:
+ metrics["PR-AUC"] = np.nan
+ try:
+ if y_proba.ndim == 1:
+ y_proba_ll = np.column_stack([1 - pos_scores, pos_scores])
+ else:
+ y_proba_ll = y_proba
+ metrics["LogLoss"] = log_loss(y_true, y_proba_ll, labels=classes_sorted)
+ except Exception:
+ metrics["LogLoss"] = np.nan
+ else:
+ metrics["ROC-AUC"] = np.nan
+ metrics["PR-AUC"] = np.nan
+ metrics["LogLoss"] = np.nan
+
+ try:
+ metrics["MCC"] = matthews_corrcoef(y_true, y_pred)
+ except Exception:
+ metrics["MCC"] = np.nan
+
+ return metrics
+
+
+def _compute_multiclass_metrics(
+ y_true: pd.Series,
+ y_pred: pd.Series,
+ y_proba: Optional[np.ndarray]
+) -> "OrderedDict[str, float]":
+ metrics = OrderedDict()
+ metrics["Accuracy"] = accuracy_score(y_true, y_pred)
+ metrics["Macro Precision"] = precision_score(y_true, y_pred, average="macro", zero_division=0)
+ metrics["Macro Recall"] = recall_score(y_true, y_pred, average="macro", zero_division=0)
+ metrics["Macro F1"] = f1_score(y_true, y_pred, average="macro", zero_division=0)
+ metrics["Weighted Precision"] = precision_score(y_true, y_pred, average="weighted", zero_division=0)
+ metrics["Weighted Recall"] = recall_score(y_true, y_pred, average="weighted", zero_division=0)
+ metrics["Weighted F1"] = f1_score(y_true, y_pred, average="weighted", zero_division=0)
+
+ try:
+ metrics["Cohen_Kappa"] = cohen_kappa_score(y_true, y_pred)
+ except Exception:
+ metrics["Cohen_Kappa"] = np.nan
+ try:
+ metrics["MCC"] = matthews_corrcoef(y_true, y_pred)
+ except Exception:
+ metrics["MCC"] = np.nan
+
+ # Probabilistic metrics
+ classes_sorted = np.sort(pd.unique(y_true))
+ if y_proba is not None and y_proba.ndim == 2:
+ try:
+ metrics["LogLoss"] = log_loss(y_true, y_proba, labels=classes_sorted)
+ except Exception:
+ metrics["LogLoss"] = np.nan
+ # Macro ROC-AUC / PR-AUC via OVR
+ try:
+ class_to_index = {c: i for i, c in enumerate(classes_sorted)}
+ y_true_idx = np.vectorize(class_to_index.get)(y_true)
+ metrics["ROC-AUC_macro"] = roc_auc_score(y_true_idx, y_proba, multi_class="ovr", average="macro")
+ except Exception:
+ metrics["ROC-AUC_macro"] = np.nan
+ try:
+ Y_true_ind = np.zeros_like(y_proba)
+ idx_map = {c: i for i, c in enumerate(classes_sorted)}
+ Y_true_ind[np.arange(y_proba.shape[0]), np.vectorize(idx_map.get)(y_true)] = 1
+ metrics["PR-AUC_macro"] = average_precision_score(Y_true_ind, y_proba, average="macro")
+ except Exception:
+ metrics["PR-AUC_macro"] = np.nan
+ else:
+ metrics["LogLoss"] = np.nan
+ metrics["ROC-AUC_macro"] = np.nan
+ metrics["PR-AUC_macro"] = np.nan
+
+ return metrics
+
+
+def aggregate_metrics(list_of_dicts):
+ """Aggregate a list of metrics dicts (per split) into mean/std."""
+ agg_mean = {}
+ agg_std = {}
+ for split in ("Train", "Validation", "Test", "Test (external)"):
+ keys = set()
+ for m in list_of_dicts:
+ if isinstance(m, dict) and split in m:
+ keys.update(m[split].keys())
+ if not keys:
+ continue
+ agg_mean[split] = {}
+ agg_std[split] = {}
+ for k in keys:
+ vals = [m[split][k] for m in list_of_dicts if split in m and k in m[split]]
+ numeric_vals = []
+ for v in vals:
+ try:
+ numeric_vals.append(float(v))
+ except Exception:
+ pass
+ if numeric_vals:
+ agg_mean[split][k] = float(np.mean(numeric_vals))
+ agg_std[split][k] = float(np.std(numeric_vals, ddof=0))
+ else:
+ agg_mean[split][k] = vals[-1] if vals else None
+ agg_std[split][k] = None
+ return agg_mean, agg_std
+
+
+def compute_metrics_for_split(
+ predictor,
+ df: pd.DataFrame,
+ target_col: str,
+ problem_type: str,
+ threshold: Optional[float] = None, # <— NEW
+) -> "OrderedDict[str, float]":
+ """Compute transparency metrics for one split (Train/Val/Test) based on task type."""
+ # Prepare inputs
+ features = df.drop(columns=[target_col], errors="ignore")
+ y_true_series = df[target_col].reset_index(drop=True)
+
+ # Probabilities (if available)
+ y_proba = None
+ try:
+ y_proba_raw = predictor.predict_proba(features)
+ y_proba = _safe_y_proba_to_array(y_proba_raw)
+ except Exception:
+ y_proba = None
+
+ # Labels (optionally thresholded for binary)
+ y_pred_series = None
+ if problem_type == "binary" and (threshold is not None) and (y_proba is not None):
+ classes_sorted = np.sort(pd.unique(y_true_series))
+ pos_label = classes_sorted[-1]
+ neg_label = classes_sorted[0]
+ if y_proba.ndim == 1:
+ pos_scores = y_proba
+ else:
+ pos_col_idx = -1
+ try:
+ if hasattr(predictor, "class_labels") and predictor.class_labels:
+ pos_col_idx = list(predictor.class_labels).index(pos_label)
+ except Exception:
+ pos_col_idx = -1
+ pos_scores = y_proba[:, pos_col_idx]
+ y_pred_series = pd.Series(np.where(pos_scores >= float(threshold), pos_label, neg_label)).reset_index(drop=True)
+ else:
+ # Fall back to model's default label prediction (argmax / 0.5 equivalent)
+ y_pred_series = pd.Series(predictor.predict(features)).reset_index(drop=True)
+
+ if problem_type == "regression":
+ y_true_arr = np.asarray(y_true_series, dtype=float)
+ y_pred_arr = np.asarray(y_pred_series, dtype=float)
+ return _compute_regression_metrics(y_true_arr, y_pred_arr)
+
+ if problem_type == "binary":
+ return _compute_binary_metrics(y_true_series, y_pred_series, y_proba, predictor)
+
+ # multiclass
+ return _compute_multiclass_metrics(y_true_series, y_pred_series, y_proba)
+
+
+def evaluate_all_transparency(
+ predictor,
+ train_df: Optional[pd.DataFrame],
+ val_df: Optional[pd.DataFrame],
+ test_df: Optional[pd.DataFrame],
+ target_col: str,
+ problem_type: str,
+ threshold: Optional[float] = None,
+) -> Tuple[pd.DataFrame, Dict[str, Dict[str, float]]]:
+ """
+ Evaluate Train/Val/Test with the transparent metrics suite.
+ Returns:
+ - metrics_table: DataFrame with index=Metric, columns subset of [Train, Validation, Test]
+ - raw_dict: nested dict {split -> {metric -> value}}
+ """
+ split_results: Dict[str, Dict[str, float]] = {}
+ splits = []
+
+ # IMPORTANT: do NOT apply threshold to Train/Val
+ if train_df is not None and len(train_df):
+ split_results["Train"] = compute_metrics_for_split(predictor, train_df, target_col, problem_type, threshold=None)
+ splits.append("Train")
+ if val_df is not None and len(val_df):
+ split_results["Validation"] = compute_metrics_for_split(predictor, val_df, target_col, problem_type, threshold=None)
+ splits.append("Validation")
+ if test_df is not None and len(test_df):
+ split_results["Test"] = compute_metrics_for_split(predictor, test_df, target_col, problem_type, threshold=threshold)
+ splits.append("Test")
+
+ # Preserve order from the first split; include any extras from others
+ order_source = split_results[splits[0]] if splits else {}
+ all_metrics = list(order_source.keys())
+ for s in splits[1:]:
+ for m in split_results[s].keys():
+ if m not in all_metrics:
+ all_metrics.append(m)
+
+ metrics_table = pd.DataFrame(index=all_metrics, columns=splits, dtype=float)
+ for s in splits:
+ for m, v in split_results[s].items():
+ metrics_table.loc[m, s] = v
+
+ return metrics_table, split_results
diff -r 000000000000 -r 375c36923da1 multimodal_learner.py
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/multimodal_learner.py Tue Dec 09 23:49:47 2025 +0000
@@ -0,0 +1,391 @@
+#!/usr/bin/env python
+"""
+Main entrypoint for AutoGluon multimodal training wrapper.
+"""
+
+import argparse
+import logging
+import os
+import sys
+from typing import List, Optional
+
+import pandas as pd
+from metrics_logic import aggregate_metrics
+from plot_logic import infer_problem_type
+from report_utils import write_outputs
+from sklearn.model_selection import KFold, StratifiedKFold
+from split_logic import split_dataset
+from test_pipeline import run_autogluon_test_experiment
+from training_pipeline import autogluon_hyperparameters, handle_missing_images, run_autogluon_experiment
+# ------------------------------------------------------------------
+# Local imports (your split utilities)
+# ------------------------------------------------------------------
+from utils import (
+ absolute_path_expander,
+ enable_deterministic_mode,
+ enable_tensor_cores_if_available,
+ ensure_local_tmp,
+ load_file,
+ prepare_image_search_dirs,
+ set_seeds,
+ str2bool,
+)
+
+# ------------------------------------------------------------------
+# Logger setup
+# ------------------------------------------------------------------
+logger = logging.getLogger(__name__)
+
+
+# ------------------------------------------------------------------
+# Argument parsing (unchanged from your original, only minor fixes)
+# ------------------------------------------------------------------
+def parse_args(argv=None):
+ parser = argparse.ArgumentParser(description="Train & report an AutoGluon model")
+
+ parser.add_argument("--input_csv_train", dest="train_dataset", required=True)
+ parser.add_argument("--input_csv_test", dest="test_dataset", default=None)
+ parser.add_argument("--target_column", required=True)
+ parser.add_argument("--output_json", default="results.json")
+ parser.add_argument("--output_html", default="report.html")
+ parser.add_argument("--output_config", default=None)
+ parser.add_argument("--images_zip", nargs="*", default=None,
+ help="One or more ZIP files that contain image assets")
+ parser.add_argument("--missing_image_strategy", default="false",
+ help="true/false: remove rows with missing images or use placeholder")
+ parser.add_argument("--threshold", type=float, default=None)
+ parser.add_argument("--time_limit", type=int, default=None)
+ parser.add_argument("--deterministic", action="store_true", default=False,
+ help="Enable deterministic algorithms to reduce run-to-run variance")
+ parser.add_argument("--random_seed", type=int, default=42)
+ parser.add_argument("--cross_validation", type=str, default="false")
+ parser.add_argument("--num_folds", type=int, default=5)
+ parser.add_argument("--epochs", type=int, default=None)
+ parser.add_argument("--learning_rate", type=float, default=None)
+ parser.add_argument("--batch_size", type=int, default=None)
+ parser.add_argument("--backbone_image", type=str, default="swin_base_patch4_window7_224")
+ parser.add_argument("--backbone_text", type=str, default="microsoft/deberta-v3-base")
+ parser.add_argument("--validation_size", type=float, default=0.2)
+ parser.add_argument("--split_probabilities", type=float, nargs=3,
+ default=[0.7, 0.1, 0.2], metavar=("train", "val", "test"))
+ parser.add_argument("--preset", choices=["medium_quality", "high_quality", "best_quality"],
+ default="medium_quality")
+ parser.add_argument("--eval_metric", default="roc_auc")
+ parser.add_argument("--hyperparameters", default=None)
+
+ args, unknown = parser.parse_known_args(argv)
+ if unknown:
+ logger.warning("Ignoring unknown CLI tokens: %s", unknown)
+
+ # -------------------------- Validation --------------------------
+ if not (0.0 <= args.validation_size <= 1.0):
+ parser.error("--validation_size must be in [0, 1]")
+ if len(args.split_probabilities) != 3 or abs(sum(args.split_probabilities) - 1.0) > 1e-6:
+ parser.error("--split_probabilities must be three numbers summing to 1.0")
+ if args.cross_validation.lower() == "true" and (args.num_folds < 2):
+ parser.error("--num_folds must be >= 2 when --cross_validation is true")
+
+ return args
+
+
+def run_cross_validation(
+ args,
+ df_full: pd.DataFrame,
+ test_dataset: Optional[pd.DataFrame],
+ image_cols: List[str],
+ ag_config: dict,
+):
+ """Cross-validation loop returning aggregated metrics and last predictor."""
+ df_full = df_full.drop(columns=["split"], errors="ignore")
+ y = df_full[args.target_column]
+ try:
+ use_stratified = y.dtype == object or y.nunique() <= 20
+ except Exception:
+ use_stratified = False
+
+ kf = StratifiedKFold(n_splits=int(args.num_folds), shuffle=True, random_state=int(args.random_seed)) if use_stratified else KFold(n_splits=int(args.num_folds), shuffle=True, random_state=int(args.random_seed))
+
+ raw_folds = []
+ ag_folds = []
+ folds_info = []
+ last_predictor = None
+ last_data_ctx = None
+
+ for fold_idx, (train_idx, val_idx) in enumerate(kf.split(df_full, y if use_stratified else None), start=1):
+ logger.info(f"CV fold {fold_idx}/{args.num_folds}")
+ df_tr = df_full.iloc[train_idx].copy()
+ df_va = df_full.iloc[val_idx].copy()
+
+ df_tr["split"] = "train"
+ df_va["split"] = "val"
+ fold_dataset = pd.concat([df_tr, df_va], ignore_index=True)
+
+ predictor_fold, data_ctx = run_autogluon_experiment(
+ train_dataset=fold_dataset,
+ test_dataset=test_dataset,
+ target_column=args.target_column,
+ image_columns=image_cols,
+ ag_config=ag_config,
+ )
+ last_predictor = predictor_fold
+ last_data_ctx = data_ctx
+ problem_type = infer_problem_type(predictor_fold, df_tr, args.target_column)
+ eval_results = run_autogluon_test_experiment(
+ predictor=predictor_fold,
+ data_ctx=data_ctx,
+ target_column=args.target_column,
+ eval_metric=args.eval_metric,
+ ag_config=ag_config,
+ problem_type=problem_type,
+ )
+
+ raw_metrics_fold = eval_results.get("raw_metrics", {})
+ ag_by_split_fold = eval_results.get("ag_eval", {})
+ raw_folds.append(raw_metrics_fold)
+ ag_folds.append(ag_by_split_fold)
+ folds_info.append(
+ {
+ "fold": int(fold_idx),
+ "predictor_path": getattr(predictor_fold, "path", None),
+ "raw_metrics": raw_metrics_fold,
+ "ag_eval": ag_by_split_fold,
+ }
+ )
+
+ raw_metrics_mean, raw_metrics_std = aggregate_metrics(raw_folds)
+ ag_by_split_mean, ag_by_split_std = aggregate_metrics(ag_folds)
+ return (
+ last_predictor,
+ raw_metrics_mean,
+ ag_by_split_mean,
+ raw_folds,
+ ag_folds,
+ raw_metrics_std,
+ ag_by_split_std,
+ folds_info,
+ last_data_ctx,
+ )
+
+
+# ------------------------------------------------------------------
+# Main execution
+# ------------------------------------------------------------------
+def main():
+ args = parse_args()
+
+ # ------------------------------------------------------------------
+ # Debug output
+ # ------------------------------------------------------------------
+ logger.info("=== AutoGluon Training Wrapper Started ===")
+ logger.info(f"Working directory: {os.getcwd()}")
+ logger.info(f"Command line: {' '.join(sys.argv)}")
+ logger.info(f"Parsed args: {vars(args)}")
+
+ # ------------------------------------------------------------------
+ # Reproducibility & performance
+ # ------------------------------------------------------------------
+ set_seeds(args.random_seed)
+ if args.deterministic:
+ enable_deterministic_mode(args.random_seed)
+ logger.info("Deterministic mode enabled (seed=%s)", args.random_seed)
+ ensure_local_tmp()
+ enable_tensor_cores_if_available()
+
+ # ------------------------------------------------------------------
+ # Load datasets
+ # ------------------------------------------------------------------
+ train_dataset = load_file(args.train_dataset)
+ test_dataset = load_file(args.test_dataset) if args.test_dataset else None
+
+ logger.info(f"Train dataset loaded: {len(train_dataset)} rows")
+ if test_dataset is not None:
+ logger.info(f"Test dataset loaded: {len(test_dataset)} rows")
+
+ # ------------------------------------------------------------------
+ # Resolve target column by name; if Galaxy passed a numeric index,
+ # translate it to the corresponding header so downstream checks pass.
+ # Galaxy's data_column widget is 1-based.
+ # ------------------------------------------------------------------
+ if args.target_column not in train_dataset.columns and str(args.target_column).isdigit():
+ idx = int(args.target_column) - 1
+ if 0 <= idx < len(train_dataset.columns):
+ resolved = train_dataset.columns[idx]
+ logger.info(f"Target column '{args.target_column}' not found; using column #{idx + 1} header '{resolved}' instead.")
+ args.target_column = resolved
+ else:
+ logger.error(f"Numeric target index '{args.target_column}' is out of range for dataset with {len(train_dataset.columns)} columns.")
+ sys.exit(1)
+
+ # ------------------------------------------------------------------
+ # Image handling (ZIP extraction + absolute path expansion)
+ # ------------------------------------------------------------------
+ extracted_imgs_path = prepare_image_search_dirs(args)
+
+ image_cols = absolute_path_expander(train_dataset, extracted_imgs_path, None)
+ if test_dataset is not None:
+ absolute_path_expander(test_dataset, extracted_imgs_path, image_cols)
+
+ # ------------------------------------------------------------------
+ # Handle missing images
+ # ------------------------------------------------------------------
+ train_dataset = handle_missing_images(
+ train_dataset,
+ image_columns=image_cols,
+ strategy=args.missing_image_strategy,
+ )
+ if test_dataset is not None:
+ test_dataset = handle_missing_images(
+ test_dataset,
+ image_columns=image_cols,
+ strategy=args.missing_image_strategy,
+ )
+
+ logger.info(f"After cleanup → train: {len(train_dataset)}, test: {len(test_dataset) if test_dataset is not None else 0}")
+
+ # ------------------------------------------------------------------
+ # Dataset splitting logic (adds 'split' column to train_dataset)
+ # ------------------------------------------------------------------
+ split_dataset(
+ train_dataset=train_dataset,
+ test_dataset=test_dataset,
+ target_column=args.target_column,
+ split_probabilities=args.split_probabilities,
+ validation_size=args.validation_size,
+ random_seed=args.random_seed,
+ )
+
+ logger.info("Preprocessing complete — ready for AutoGluon training!")
+ logger.info(f"Final split counts:\n{train_dataset['split'].value_counts().sort_index()}")
+
+ # Verify target/image/text columns exist
+ if args.target_column not in train_dataset.columns:
+ logger.error(f"Target column '{args.target_column}' not found in training data.")
+ sys.exit(1)
+ if test_dataset is not None and args.target_column not in test_dataset.columns:
+ logger.error(f"Target column '{args.target_column}' not found in test data.")
+ sys.exit(1)
+
+ # Threshold is only meaningful for binary classification; ignore otherwise.
+ threshold_for_run = args.threshold
+ unique_labels = None
+ target_looks_binary = False
+ try:
+ unique_labels = train_dataset[args.target_column].nunique(dropna=True)
+ target_looks_binary = unique_labels == 2
+ except Exception:
+ logger.warning("Could not inspect target column '%s' for threshold validation; proceeding without binary check.", args.target_column)
+
+ if threshold_for_run is not None:
+ if target_looks_binary:
+ threshold_for_run = float(threshold_for_run)
+ logger.info("Applying custom decision threshold %.4f for binary evaluation.", threshold_for_run)
+ else:
+ logger.warning(
+ "Threshold %.3f provided but target '%s' does not appear binary (unique labels=%s); ignoring threshold.",
+ threshold_for_run,
+ args.target_column,
+ unique_labels if unique_labels is not None else "unknown",
+ )
+ threshold_for_run = None
+ args.threshold = threshold_for_run
+ # Image columns are auto-inferred; image_cols already resolved to absolute paths.
+ # ------------------------------------------------------------------
+ # Build AutoGluon configuration from CLI knobs
+ # ------------------------------------------------------------------
+ ag_config = autogluon_hyperparameters(
+ threshold=args.threshold,
+ time_limit=args.time_limit,
+ random_seed=args.random_seed,
+ epochs=args.epochs,
+ learning_rate=args.learning_rate,
+ batch_size=args.batch_size,
+ backbone_image=args.backbone_image,
+ backbone_text=args.backbone_text,
+ preset=args.preset,
+ eval_metric=args.eval_metric,
+ hyperparameters=args.hyperparameters,
+ )
+ logger.info(f"AutoGluon config prepared: fit={ag_config.get('fit')}, hyperparameters keys={list(ag_config.get('hyperparameters', {}).keys())}")
+
+ cv_enabled = str2bool(args.cross_validation)
+ if cv_enabled:
+ (
+ predictor,
+ raw_metrics,
+ ag_by_split,
+ raw_folds,
+ ag_folds,
+ raw_metrics_std,
+ ag_by_split_std,
+ folds_info,
+ data_ctx,
+ ) = run_cross_validation(
+ args=args,
+ df_full=train_dataset,
+ test_dataset=test_dataset,
+ image_cols=image_cols,
+ ag_config=ag_config,
+ )
+ if predictor is None:
+ logger.error("All CV folds failed. Exiting.")
+ sys.exit(1)
+ eval_results = {
+ "raw_metrics": raw_metrics,
+ "ag_eval": ag_by_split,
+ "fit_summary": None,
+ }
+ else:
+ predictor, data_ctx = run_autogluon_experiment(
+ train_dataset=train_dataset,
+ test_dataset=test_dataset,
+ target_column=args.target_column,
+ image_columns=image_cols,
+ ag_config=ag_config,
+ )
+ logger.info("AutoGluon training finished. Model path: %s", getattr(predictor, "path", None))
+
+ # Evaluate predictor on Train/Val/Test splits
+ problem_type = infer_problem_type(predictor, train_dataset, args.target_column)
+ eval_results = run_autogluon_test_experiment(
+ predictor=predictor,
+ data_ctx=data_ctx,
+ target_column=args.target_column,
+ eval_metric=args.eval_metric,
+ ag_config=ag_config,
+ problem_type=problem_type,
+ )
+ raw_metrics = eval_results.get("raw_metrics", {})
+ ag_by_split = eval_results.get("ag_eval", {})
+ raw_folds = ag_folds = raw_metrics_std = ag_by_split_std = None
+
+ logger.info("Transparent metrics by split: %s", eval_results["raw_metrics"])
+ logger.info("AutoGluon evaluate() by split: %s", eval_results["ag_eval"])
+
+ if "problem_type" in eval_results:
+ problem_type_final = eval_results["problem_type"]
+ else:
+ problem_type_final = infer_problem_type(predictor, train_dataset, args.target_column)
+
+ write_outputs(
+ args=args,
+ predictor=predictor,
+ problem_type=problem_type_final,
+ eval_results=eval_results,
+ data_ctx=data_ctx,
+ raw_folds=raw_folds,
+ ag_folds=ag_folds,
+ raw_metrics_std=raw_metrics_std,
+ ag_by_split_std=ag_by_split_std,
+ )
+
+
+if __name__ == "__main__":
+ logging.basicConfig(
+ level=logging.INFO,
+ format="%(asctime)s | %(levelname)s | %(message)s",
+ datefmt="%H:%M:%S"
+ )
+ # Quiet noisy image parsing logs (e.g., PIL.PngImagePlugin debug streams)
+ logging.getLogger("PIL").setLevel(logging.WARNING)
+ logging.getLogger("PIL.PngImagePlugin").setLevel(logging.WARNING)
+ main()
diff -r 000000000000 -r 375c36923da1 multimodal_learner.xml
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/multimodal_learner.xml Tue Dec 09 23:49:47 2025 +0000
@@ -0,0 +1,316 @@
+
+ Train and evaluate an AutoGluon Multimodal model (tabular + image + text)
+
+
+ quay.io/goeckslab/multimodal-learner:1.4.0
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ 0
+ #set $images_zip_cli = " ".join(["'%s'" % z for z in $image_zip_paths])
+#else
+ #set $images_zip_cli = None
+#end if
+
+set -e;
+ln -sf '$input_csv' 'train_input.csv';
+#if $test_dataset_conditional.has_test_dataset == "yes"
+ln -sf '$test_dataset_conditional.input_test' 'test_input.csv';
+#end if
+
+python '$__tool_directory__/multimodal_learner.py'
+ --input_csv_train 'train_input.csv'
+ #if $test_dataset_conditional.has_test_dataset == "yes"
+ --input_csv_test 'test_input.csv'
+ #end if
+ --target_column '$target_column'
+
+ #if $use_images_conditional.use_images == "yes"
+ #if $images_zip_cli
+ --images_zip $images_zip_cli
+ #end if
+ --missing_image_strategy '$use_images_conditional.missing_image_strategy'
+ #if $use_images_conditional.backbone_image
+ --backbone_image '$use_images_conditional.backbone_image'
+ #end if
+ #end if
+
+ #if $backbone_text not in ("", None)
+ --backbone_text '$backbone_text'
+ #end if
+
+ --preset '$preset'
+ --eval_metric '$eval_metric'
+
+ --random_seed '$random_seed'
+ #if $time_limit
+ --time_limit $time_limit
+ #end if
+ #if $deterministic == "true"
+ --deterministic
+ #end if
+
+ #if $customize_defaults_conditional.customize_defaults == "yes"
+ #if $customize_defaults_conditional.validation_size not in ("", None)
+ --validation_size $customize_defaults_conditional.validation_size
+ #end if
+ #if $customize_defaults_conditional.split_probabilities and str($customize_defaults_conditional.split_probabilities).strip()
+ --split_probabilities #echo " ".join([str(float(x)) for x in str($customize_defaults_conditional.split_probabilities).replace(",", " ").split() if x.strip()]) #
+ #end if
+ #if $customize_defaults_conditional.cross_validation == "true"
+ --cross_validation true
+ --num_folds $customize_defaults_conditional.num_folds
+ #end if
+ #if $customize_defaults_conditional.epochs
+ --epochs $customize_defaults_conditional.epochs
+ #end if
+ #if $customize_defaults_conditional.learning_rate
+ --learning_rate $customize_defaults_conditional.learning_rate
+ #end if
+ #if $customize_defaults_conditional.batch_size
+ --batch_size $customize_defaults_conditional.batch_size
+ #end if
+ #if $customize_defaults_conditional.threshold
+ --threshold $customize_defaults_conditional.threshold
+ #end if
+ #if $customize_defaults_conditional.hyperparameters
+ --hyperparameters '$customize_defaults_conditional.hyperparameters'
+ #end if
+ #end if
+
+ --output_json '$output_json'
+ --output_html '$output_html'
+ --output_config '$output_config'
+]]>
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+@article{AutoGluon2023,
+ author = {Erickson, Nick and Mueller, Jonas and Wang, Yizhou and others},
+ title = {AutoGluon-Tabular: Robust and Accurate AutoML for Structured Data},
+ journal = {arXiv preprint arXiv:2003.06505},
+ year = {2023}
+}
+
+
+
diff -r 000000000000 -r 375c36923da1 plot_logic.py
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/plot_logic.py Tue Dec 09 23:49:47 2025 +0000
@@ -0,0 +1,1697 @@
+from __future__ import annotations
+
+import html
+import os
+from html import escape as _escape
+from typing import Any, Dict, List, Mapping, Optional, Sequence, Tuple, Union
+
+import matplotlib.pyplot as plt
+import numpy as np
+import pandas as pd
+import plotly.express as px
+import plotly.graph_objects as go
+import shap
+from feature_help_modal import get_metrics_help_modal
+from report_utils import build_tabbed_html, get_html_closing, get_html_template
+from sklearn.calibration import calibration_curve
+from sklearn.metrics import (
+ auc,
+ average_precision_score,
+ classification_report,
+ confusion_matrix,
+ log_loss,
+ precision_recall_curve,
+ roc_auc_score,
+ roc_curve,
+)
+from sklearn.model_selection import learning_curve as skl_learning_curve
+from sklearn.preprocessing import label_binarize
+
+# =========================
+# Utilities
+# =========================
+
+
+def plot_with_table_style_title(fig, title: str) -> str:
+ """
+ Render a Plotly figure with a report-style
header so it matches the
+ green table section headers.
+ """
+ # kill Plotly’s built-in title
+ fig.update_layout(title=None)
+
+ # figure HTML without PlotlyJS (we load it once globally)
+ plot_html = fig.to_html(full_html=False, include_plotlyjs=False)
+
+ # use
+
+""".strip())
+
+ # Model Configuration
+
+ # Remove Predictor type and Framework, and ensure Model Architecture is present
+ base_rows: list[tuple[str, str]] = []
+ if extra_run_rows:
+ # Remove any rows with keys 'Predictor type' or 'Framework'
+ base_rows.extend([(k, v) for (k, v) in extra_run_rows if k not in ("Predictor type", "Framework")])
+
+ def _fmt(v):
+ if v is None or v == "":
+ return "—"
+ return _escape(str(v))
+
+ rows_html = "\n".join(
+ f"
{_escape(str(k))}
{_fmt(v)}
"
+ for k, v in base_rows
+ )
+
+ sections.append(f"""
+
+
Model Configuration
+
+
+
Key
Value
+
+ {rows_html}
+
+
+
+
+""".strip())
+
+ return "\n".join(sections).strip()
+
+
+def build_feature_importance_html(predictor, df_train: pd.DataFrame, label_column: str) -> str:
+ """Build a visualization of feature importance."""
+ try:
+ # Try to get feature importance from predictor
+ fi = None
+ if hasattr(predictor, "feature_importance") and callable(predictor.feature_importance):
+ try:
+ fi = predictor.feature_importance(df_train)
+ except Exception as e:
+ return f"
Could not compute feature importance: {e}
"
+
+ if fi is None or (isinstance(fi, pd.DataFrame) and fi.empty):
+ return "
Feature importance not available for this model.
"
+
+ # Format as a sortable table
+ rows = []
+ if isinstance(fi, pd.DataFrame):
+ fi = fi.sort_values("importance", ascending=False)
+ for _, row in fi.iterrows():
+ feat = row.index[0] if isinstance(row.index, pd.Index) else row["feature"]
+ imp = float(row["importance"])
+ rows.append(f"
{_escape(str(feat))}
{imp:.4f}
")
+ else:
+ # Handle other formats (dict, etc)
+ for feat, imp in sorted(fi.items(), key=lambda x: float(x[1]), reverse=True):
+ rows.append(f"
")
+
+ # Previously: Modalities & Inputs and/or Class Balance may have been here.
+ # Only render them if flags are True.
+ if include_modalities:
+ from report_utils import build_modalities_html
+ modalities_html = build_modalities_html(predictor, df_train, label_column)
+ sections.append(f"
Modalities & Inputs
{modalities_html}
")
+
+ if include_class_balance:
+ from report_utils import build_class_balance_html
+ cb_html = build_class_balance_html(df_train, label_column)
+ sections.append(f"
Class Balance (Train Full)
{cb_html}
")
+
+ return "\n".join(sections)
+
+
+def assemble_full_html_report(
+ summary_html: str,
+ train_html: str,
+ test_html: str,
+ plots: List[str],
+ feature_html: str,
+) -> str:
+ """
+ Wrap the four tabs using utils.build_tabbed_html and return full HTML.
+ """
+ # Append plots under the Test tab (already wrapped with titles)
+ test_full = test_html + "".join(plots)
+
+ tabs = build_tabbed_html(summary_html, train_html, test_full, feature_html, explainer_html=None)
+
+ html_out = get_html_template()
+
+ # 🔧 Ensure Plotly JS is available (we render plots with include_plotlyjs=False)
+ html_out += '\n\n'
+
+ # Optional: centering tweaks
+ html_out += """
+
+"""
+ # Help modal HTML/JS
+ html_out += get_metrics_help_modal()
+
+ html_out += tabs
+ html_out += get_html_closing()
+ return html_out
diff -r 000000000000 -r 375c36923da1 report_utils.py
--- /dev/null Thu Jan 01 00:00:00 1970 +0000
+++ b/report_utils.py Tue Dec 09 23:49:47 2025 +0000
@@ -0,0 +1,1116 @@
+import base64
+import html
+import json
+import logging
+import os
+import platform
+import shutil
+import sys
+import tempfile
+from datetime import datetime
+from typing import Any, Dict, List, Optional
+
+import numpy as np
+import pandas as pd
+import yaml
+from utils import verify_outputs
+
+logger = logging.getLogger(__name__)
+
+
+def _escape(s: Any) -> str:
+ return html.escape(str(s))
+
+
+def _write_predictor_path(predictor):
+ try:
+ pred_path = getattr(predictor, "path", None)
+ if pred_path:
+ with open("predictor_path.txt", "w") as pf:
+ pf.write(str(pred_path))
+ logger.info("Wrote predictor path → predictor_path.txt")
+ return pred_path
+ except Exception:
+ logger.warning("Could not write predictor_path.txt")
+ return None
+
+
+def _copy_config_if_available(pred_path: Optional[str], output_config: Optional[str]):
+ if not output_config:
+ return
+ try:
+ config_yaml_path = os.path.join(pred_path, "config.yaml") if pred_path else None
+ if config_yaml_path and os.path.isfile(config_yaml_path):
+ shutil.copy2(config_yaml_path, output_config)
+ logger.info(f"Wrote AutoGluon config → {output_config}")
+ else:
+ with open(output_config, "w") as cfg_out:
+ cfg_out.write("# config.yaml not found for this run\n")
+ logger.warning(f"AutoGluon config.yaml not found; created placeholder at {output_config}")
+ except Exception as e:
+ logger.error(f"Failed to write config output '{output_config}': {e}")
+ try:
+ with open(output_config, "w") as cfg_out:
+ cfg_out.write(f"# Failed to copy config.yaml: {e}\n")
+ except Exception:
+ pass
+
+
+def _load_config_yaml(args, predictor) -> dict:
+ """
+ Load config.yaml either from the predictor path or the exported output_config.
+ """
+ candidates = []
+ pred_path = getattr(predictor, "path", None)
+ if pred_path:
+ cfg_path = os.path.join(pred_path, "config.yaml")
+ if os.path.isfile(cfg_path):
+ candidates.append(cfg_path)
+ if args.output_config and os.path.isfile(args.output_config):
+ candidates.append(args.output_config)
+
+ for p in candidates:
+ try:
+ with open(p, "r") as f:
+ return yaml.safe_load(f) or {}
+ except Exception:
+ continue
+ return {}
+
+
+def _summarize_config(cfg: dict, args) -> List[tuple[str, str]]:
+ """
+ Build rows describing model components and key hyperparameters from a loaded config.yaml.
+ Falls back to CLI args when config values are missing.
+ """
+ rows: List[tuple[str, str]] = []
+ model_cfg = cfg.get("model", {}) if isinstance(cfg, dict) else {}
+ names = model_cfg.get("names") or []
+ if names:
+ rows.append(("Model components", ", ".join(names)))
+
+ # Tabular backbone with data types
+ tabular_val = "—"
+ for k, v in model_cfg.items():
+ if k in ("names", "hf_text", "timm_image"):
+ continue
+ if isinstance(v, dict) and "data_types" in v:
+ dtypes = v.get("data_types") or []
+ if any(t in ("categorical", "numerical") for t in dtypes):
+ dt_str = ", ".join(dtypes) if dtypes else ""
+ tabular_val = f"{k} ({dt_str})" if dt_str else k
+ break
+ rows.append(("Tabular backbone", tabular_val))
+
+ image_val = model_cfg.get("timm_image", {}).get("checkpoint_name") or "—"
+ rows.append(("Image backbone", image_val))
+
+ text_val = model_cfg.get("hf_text", {}).get("checkpoint_name") or "—"
+ rows.append(("Text backbone", text_val))
+
+ fusion_val = "—"
+ for k in model_cfg.keys():
+ if str(k).startswith("fusion"):
+ fusion_val = k
+ break
+ rows.append(("Fusion backbone", fusion_val))
+
+ # Optimizer block
+ optim_cfg = cfg.get("optim", {}) if isinstance(cfg, dict) else {}
+ optim_map = [
+ ("optim_type", "Optimizer"),
+ ("lr", "Learning rate"),
+ ("weight_decay", "Weight decay"),
+ ("lr_decay", "LR decay"),
+ ("max_epochs", "Max epochs"),
+ ("max_steps", "Max steps"),
+ ("patience", "Early-stop patience"),
+ ("check_val_every_n_epoch", "Val check every N epochs"),
+ ("top_k", "Top K checkpoints"),
+ ("top_k_average_method", "Top K averaging"),
+ ]
+ for key, label in optim_map:
+ if key in optim_cfg:
+ rows.append((label, optim_cfg[key]))
+
+ env_cfg = cfg.get("env", {}) if isinstance(cfg, dict) else {}
+ if "batch_size" in env_cfg:
+ rows.append(("Global batch size", env_cfg["batch_size"]))
+
+ return rows
+
+
+def write_outputs(
+ args,
+ predictor,
+ problem_type: str,
+ eval_results: dict,
+ data_ctx: dict,
+ raw_folds=None,
+ ag_folds=None,
+ raw_metrics_std=None,
+ ag_by_split_std=None,
+):
+ from plot_logic import (
+ build_summary_html,
+ build_test_html_and_plots,
+ build_feature_html,
+ assemble_full_html_report,
+ build_train_html_and_plots,
+ )
+ from autogluon.multimodal import MultiModalPredictor
+ from metrics_logic import aggregate_metrics
+
+ raw_metrics = eval_results.get("raw_metrics", {})
+ ag_by_split = eval_results.get("ag_eval", {})
+ fit_summary_obj = eval_results.get("fit_summary")
+
+ df_train = data_ctx.get("train")
+ df_val = data_ctx.get("val")
+ df_test_internal = data_ctx.get("test_internal")
+ df_test_external = data_ctx.get("test_external")
+ df_test = df_test_external if df_test_external is not None else df_test_internal
+ df_train_full = df_train if df_val is None else pd.concat([df_train, df_val], ignore_index=True)
+
+ # Aggregate folds if provided without stds
+ if raw_folds and raw_metrics_std is None:
+ raw_metrics, raw_metrics_std = aggregate_metrics(raw_folds)
+ if ag_folds and ag_by_split_std is None:
+ ag_by_split, ag_by_split_std = aggregate_metrics(ag_folds)
+
+ # Inject AG eval into raw metrics for visibility
+ def _inject_ag(src: dict, dst: dict):
+ for k, v in (src or {}).items():
+ try:
+ dst[f"AG_{k}"] = float(v)
+ except Exception:
+ dst[f"AG_{k}"] = v
+ if "Train" in raw_metrics and "Train" in ag_by_split:
+ _inject_ag(ag_by_split["Train"], raw_metrics["Train"])
+ if "Validation" in raw_metrics and "Validation" in ag_by_split:
+ _inject_ag(ag_by_split["Validation"], raw_metrics["Validation"])
+ if "Test" in raw_metrics and "Test" in ag_by_split:
+ _inject_ag(ag_by_split["Test"], raw_metrics["Test"])
+
+ # JSON
+ with open(args.output_json, "w") as f:
+ json.dump(
+ {
+ "train": raw_metrics.get("Train", {}),
+ "val": raw_metrics.get("Validation", {}),
+ "test": raw_metrics.get("Test", {}),
+ "test_external": raw_metrics.get("Test (external)", {}),
+ "ag_eval": ag_by_split,
+ "ag_eval_std": ag_by_split_std,
+ "fit_summary": fit_summary_obj,
+ "problem_type": problem_type,
+ "predictor_path": getattr(predictor, "path", None),
+ "threshold": args.threshold,
+ "threshold_test": args.threshold,
+ "preset": args.preset,
+ "eval_metric": args.eval_metric,
+ "folds": {
+ "raw_folds": raw_folds,
+ "ag_folds": ag_folds,
+ "summary_mean": raw_metrics if raw_folds else None,
+ "summary_std": raw_metrics_std,
+ "ag_summary_mean": ag_by_split,
+ "ag_summary_std": ag_by_split_std,
+ },
+ },
+ f,
+ indent=2,
+ default=str,
+ )
+ logger.info(f"Wrote full JSON → {args.output_json}")
+
+ # HTML report assembly
+ label_col = args.target_column
+
+ class_balance_block_html = build_class_balance_html(
+ df_train=df_train,
+ label_col=label_col,
+ df_val=df_val,
+ df_test=df_test,
+ )
+ summary_perf_table_html = build_model_performance_summary_table(
+ train_scores=raw_metrics.get("Train", {}),
+ val_scores=raw_metrics.get("Validation", {}),
+ test_scores=raw_metrics.get("Test", {}),
+ include_test=True,
+ title=None,
+ show_title=False,
+ )
+
+ cfg_yaml = _load_config_yaml(args, predictor)
+ config_rows = _summarize_config(cfg_yaml, args)
+ threshold_rows = []
+ if problem_type == "binary" and args.threshold is not None:
+ threshold_rows.append(("Decision threshold (Test)", f"{float(args.threshold):.3f}"))
+ extra_run_rows = [
+ ("Target column", label_col),
+ ("Model evaluation metric", args.eval_metric or "AutoGluon default"),
+ ("Experiment quality", args.preset or "AutoGluon default"),
+ ] + threshold_rows + config_rows
+
+ summary_html = build_summary_html(
+ predictor=predictor,
+ df_train=df_train_full,
+ df_val=df_val,
+ df_test=df_test,
+ label_column=label_col,
+ extra_run_rows=extra_run_rows,
+ class_balance_html=class_balance_block_html,
+ perf_table_html=summary_perf_table_html,
+ )
+
+ train_tab_perf_html = build_model_performance_summary_table(
+ train_scores=raw_metrics.get("Train", {}),
+ val_scores=raw_metrics.get("Validation", {}),
+ test_scores=raw_metrics.get("Test", {}),
+ include_test=False,
+ title=None,
+ show_title=False,
+ )
+
+ train_html = build_train_html_and_plots(
+ predictor=predictor,
+ problem_type=problem_type,
+ df_train=df_train,
+ df_val=df_val,
+ label_column=label_col,
+ tmpdir=tempfile.mkdtemp(),
+ seed=int(args.random_seed),
+ perf_table_html=train_tab_perf_html,
+ threshold=args.threshold,
+ )
+
+ test_html_template, plots = build_test_html_and_plots(
+ predictor,
+ problem_type,
+ df_test,
+ label_col,
+ tempfile.mkdtemp(),
+ threshold=args.threshold,
+ )
+
+ def _fmt_val(v):
+ if isinstance(v, (int, np.integer)):
+ return f"{int(v)}"
+ if isinstance(v, (float, np.floating)):
+ return f"{v:.6f}"
+ return str(v)
+
+ test_scores = raw_metrics.get("Test", {})
+ # Drop AutoGluon-injected ROC AUC line from the Test Performance Summary
+ filtered_test_scores = {k: v for k, v in test_scores.items() if k != "AG_roc_auc"}
+ metric_rows = "".join(
+ f"
"
+
+
+def build_ignored_features_html(predictor, df_any: pd.DataFrame) -> str:
+ # MultiModalPredictor does not always expose .features(); guard accordingly.
+ used = set()
+ try:
+ used = set(predictor.features())
+ except Exception:
+ # If we can't determine, don't emit a misleading section
+ return ""
+ raw_cols = [c for c in df_any.columns if c != getattr(predictor, "label", None)]
+ ignored = [c for c in raw_cols if c not in used]
+ if not ignored:
+ return ""
+ items = "".join(f"
{html.escape(c)}
" for c in ignored)
+ return f"""
+
Ignored / Unused Features
+
The following columns were not used by the trained predictor at inference time:
+
{items}
+ """
+
+
+def build_presets_hparams_html(predictor) -> str:
+ # MultiModalPredictor path
+ mm_hp = {}
+ for attr in ("_config", "config", "_fit_args"):
+ if hasattr(predictor, attr):
+ try:
+ val = getattr(predictor, attr)
+ # make it JSON-ish
+ mm_hp[attr] = str(val)
+ except Exception:
+ continue
+ hp_html = f"
{html.escape(json.dumps(mm_hp, indent=2))}
" if mm_hp else "Unavailable"
+ return f"
Training Presets & Hyperparameters
Show hyperparameters{hp_html}"
+
+
+def build_warnings_html(warnings_list: List[str], notes_list: List[str]) -> str:
+ if not warnings_list and not notes_list:
+ return ""
+ w_html = "".join(f"
{_escape(w)}
" for w in warnings_list)
+ n_html = "".join(f"
{_escape(n)}
" for n in notes_list)
+ return f"""
+
Warnings & Notices
+ {'
Warnings
'+w_html+'
' if warnings_list else ''}
+ {'
Notices
'+n_html+'
' if notes_list else ''}
+ """
+
+
+def build_reproducibility_html(args, ctx: Dict[str, Any], model_path: Optional[str]) -> str:
+ cmd = " ".join(_escape(x) for x in sys.argv)
+ load_snippet = ""
+ if model_path:
+ load_snippet = f"""
+ {load_snippet or 'Model path not available'}
+ """
+
+
+def build_modalities_html(predictor, df_any: pd.DataFrame, label_col: str, image_col: Optional[str]) -> str:
+ """Summarize which inputs/modalities are used for MultiModalPredictor."""
+ cols = [c for c in df_any.columns]
+ # exclude label from feature list
+ feat_cols = [c for c in cols if c != label_col]
+ # identify image vs tabular columns from args / presence
+ img_present = (image_col in df_any.columns) if image_col else False
+ tab_cols = [c for c in feat_cols if c != image_col]
+
+ # brief lists (avoid dumping all, unless small)
+ def list_or_count(arr, max_show=20):
+ if len(arr) <= max_show:
+ items = "".join(f"