Full Code of mobicom24/RF-Diffusion for AI

main eb872b0c4543 cached
44 files
243.0 KB
69.0k tokens
339 symbols
1 requests
Download .txt
Showing preview only (256K chars total). Download the full file or copy to clipboard to get everything.
Repository: mobicom24/RF-Diffusion
Branch: main
Commit: eb872b0c4543
Files: 44
Total size: 243.0 KB

Directory structure:
gitextract_yuerfw2n/

├── LICENSE
├── README.md
├── complex/
│   ├── __init__.py
│   ├── complex_functions.py
│   ├── complex_layers.py
│   └── complex_module.py
├── inference.py
├── plots/
│   ├── code/
│   │   ├── Fig10-Scalability-analysis.py
│   │   ├── Fig11(a)-Cross-domain-Performance-of-augmented-Wi-Fi-sensing.py
│   │   ├── Fig11(b)-In-domain-Performance-of-augmented-Wi-Fi-sensing.py
│   │   ├── Fig12-Impact-of-synthetic-data-volume.py
│   │   ├── Fig13(a)-Performance-of-channel-estimation-amplitude-phase.py
│   │   ├── Fig13(b)-Performance-of-channel-estimation-SNR.py
│   │   ├── Fig6(a)-exp-overall-wifi-ssim.py
│   │   ├── Fig6(b)-exp-overall-wifi-fid.py
│   │   ├── Fig7(a)-exp-overall-fmcw-ssim.py
│   │   ├── Fig7(b)-exp-overall-fmcw-fid.py
│   │   ├── Fig8-Impact-of-diffusion-method.py
│   │   └── Fig9-Impact-of-network-design.py
│   ├── data/
│   │   ├── exp_MIMO.mat
│   │   ├── exp_cross_domain.mat
│   │   ├── exp_impact_diffusion_method.mat
│   │   ├── exp_impact_network_design.mat
│   │   ├── exp_impact_synthetic_data.mat
│   │   ├── exp_in_domain.mat
│   │   ├── exp_mimo_snr.mat
│   │   ├── exp_overall_fid_fmcw.mat
│   │   ├── exp_overall_fid_wifi.mat
│   │   ├── exp_overall_ssim_fmcw.mat
│   │   ├── exp_overall_ssim_wifi.mat
│   │   ├── exp_scalability_analysis.mat
│   │   ├── untitled.asv
│   │   └── untitled.m
│   └── requirements.txt
├── tfdiff/
│   ├── __init__.py
│   ├── dataset.py
│   ├── diffusion.py
│   ├── eeg_model.py
│   ├── fmcw_model.py
│   ├── learner.py
│   ├── mimo_model.py
│   ├── params.py
│   └── wifi_model.py
└── train.py

================================================
FILE CONTENTS
================================================

================================================
FILE: LICENSE
================================================
                    GNU GENERAL PUBLIC LICENSE
                       Version 3, 29 June 2007

 Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
 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.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    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 <https://www.gnu.org/licenses/>.

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:

    <program>  Copyright (C) <year>  <name of author>
    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
<https://www.gnu.org/licenses/>.

  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
<https://www.gnu.org/licenses/why-not-lgpl.html>.


================================================
FILE: README.md
================================================
# Artifact for MobiCom'24: RF-Diffusion: Radio Signal Generation via Time-Frequency Diffusion
[![License: GPL v3](https://img.shields.io/badge/License-GPLv3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0)
[![Open in Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/drive/1T8duxPyb92Owl5nijWF-pUknMWwmZpRH?usp=sharing)

## Overview
We introduce RF-Diffusion, a versatile generative model designed for wireless data. RF-Diffusion is capable of generating various types of signals, including Wi-Fi, FMCW Radar, 5G, and even modalities beyond RF, showcasing RF-Diffusion's prowess across different signal categories. We extensively evaluate RF-Diffusion's generative capabilities and validate its effectiveness in multiple downstream tasks, including wireless sensing and 5G channel estimation.

Our basic implementation of RF-Diffusion is provided in this repository. We have released several medium-sized pre-trained models (each containing 16 to 32 blocks, with 128 or 256 hidden dim) and part of the corresponding data files in [releases](https://github.com/mobicom24/RF-Diffusion/releases/tag/dataset_model), which can be used for performance testing. 

An intuitive comparison between RF-Diffusion and three other prevalent generative models is shown as follows. For demonstration purposes, we provide the **Doppler Frequency Shift (DFS)** spectrogram of the Wi-Fi signal, and the **Range Doppler Map (RDM)** spectrogram of the FMCW Radar signal, which are representative features of the two signals, respectively.
Please note that all these methods generate the **raw complex-valued signals**, and the spectrograms are shown for ease of illustration.

**Note: The GIFs in the table below may take some time to load. If they don't appear immediately, please wait for a moment or try refreshing the webpage.**

|     | Ground Truth  | RF-Diffusion  | DDPM[^DDPM]  | DCGAN[^DCGAN]  | CVAE[^CVAE]  | 
|  ----  | ----  | ----  | ----  | ----  | ----  | 
| **Wi-Fi**  | <img src="./img/0-wifi-gesture-gt.gif" height=100> <img src="./img/0-wifi-fall-gt.gif"  height=100>| <img src="./img/0-wifi-gesture-ours.gif" height=100 ><img src="./img/0-wifi-fall-ours.gif"  height=100>| <img src="./img/0-wifi-gesture-ddpm.gif" height=100> <img src="./img/0-wifi-fall-ddpm.gif"  height=100>| <img src="./img/0-wifi-gesture-gan.gif" height=100><img src="./img/0-wifi-fall-gan.gif"  height=100> | <img src="./img/0-wifi-gesture-vae.gif" height=100> <img src="./img/0-wifi-fall-vae.gif"  height=100> |
| **FMCW**   | <img src="./img/0-fmcw-1-gt.gif" height=100> <img src="./img/0-fmcw-2-gt.gif"  height=100> | <img src="./img/0-fmcw-1-ours.gif" height=100> <img src="./img/0-fmcw-2-ours.gif" height=100> | <img src="./img/0-fmcw-1-ddpm.gif" height=100> <img src="./img/0-fmcw-2-ddpm.gif" height=100> | <img src="./img/0-fmcw-1-gan.gif" height=100> <img src="./img/0-fmcw-2-gan.gif" height=100> | <img src="./img/0-fmcw-1-vae.gif" height=100> <img src="./img/0-fmcw-2-vae.gif" height=100> |



As shown, RF-Diffusion generates signals that accurately retain their physical features.

## Running the Evaluation Script
You can run the evaluation script that produces the major figures in our paper in two ways.

**1. (Recommended) Google Colab Notebook**
  * Simply open [this notebook](https://colab.research.google.com/drive/1T8duxPyb92Owl5nijWF-pUknMWwmZpRH?usp=sharing). Under the ```Runtime``` tab, select ```Run all```.
  * Please wait for 15 minutes as the data are being processed.
  * The figures will be displayed in your browser.
    
**2. Local Setup**
  * Clone this repository.
  * Install [Python 3](https://www.python.org/downloads/) if you have not already. Then, run pip3 install ```-r requirements.txt``` at the root directory of ```/plots``` folder to install the dependencies.
  * Run code files in ```/plots/code``` directory one by one and wait for 15 minutes as the data are being processed.
  * In ```/plots/img``` directory, figures used in our paper can be found.


## Further Testing and Customization

In this section, we offer training code, testing code, and pre-trained models. You can utilize our pre-trained models for further testing and even customize the models according to your specific tasks. This will significantly foster the widespread application of RF-Diffusion within the community.

<!--
- [0. Prerequisite](#0-prerequisite)
- [1. RF Data Generation](#1-rf-data-generation)
  - [1.1 Wi-Fi Data Generation](#11-wi-fi-data-generation)
  - [1.2 FMCW Data Generation](#12-fmcw-data-generation)
- [2. Case Study](#2-case-study)
  - [2.1 Augmented Wireless Sensing](#21-augmented-wireless-sensing)
  - [2.2 5G FDD Channel Estimation](#22-5g-fdd-channel-estimation)
  - [2.3 Supplementary: EEG Signal Denoise](#23-supplementary-eeg-signal-denoise)
-->

## 0. Prerequisite

RF-Diffusion is implemented with [Python 3.8](https://www.python.org/downloads/) and [PyTorch 2.0.1](https://pytorch.org/). We manage the development environment using [Conda](https://anaconda.org/anaconda/conda).
Execute the following commands to configure the development environment.

- Create a conda environment called `RF-Diffusion` based on python 3.8, and activate the environment.
    ```bash
    conda create -n RF-Diffusion python=3.8
    conda activate RF-Diffusion 
    ```

- Install PyTorch, as well as other required packages.
    ```bash
    pip3 install torch
    ```
    ```bash
    pip3 install numpy scipy tensorboard tqdm matplotlib torchvision pytorch_fid
    ```

For more details about the environment configuration, refer to the `requirements.txt` file in [releases](https://github.com/mobicom24/RF-Diffusion/releases/tag/dataset_model).

Download or `git clone` the `RF-Diffusion` project. Download and unzip `dataset.zip` and `model.zip` in [releases](https://github.com/mobicom24/RF-Diffusion/releases/tag/dataset_model) to the project directory.

```bash
unzip -q dataset.zip -d 'RF-Diffusion/dataset'
unzip -q model.zip -d 'RF-Diffusion'
```

The project structure is shown as follows:

<div align="center">    <img src="./img/0-project.png"  height=400> </div>

## 1. RF Data Generation

In the following part, we use `task_id` to differentiate between four types of tasks of synthesising Wi-Fi, FMCW signals, performing 5G channel estimation, and denoising the EEG to 0, 1, 2 and 3 respectively.

### 1.1 Wi-Fi Data Generation

By executing the following code, you can generate new Wi-Fi data, and the corresponding average SSIM (Structural Similarity Index Measure) and FID (Fréchet Inception Distance) will be displayed in the command line, which matches the values reported in section 6.2: Overall Generation Quality of the paper.

```python
python3 inference.py --task_id 0
```

The generated data are stored in `.mat` format, and can be found in `./dataset/wifi/output`.

Our model showcases the best performance in both SSIM (Structure Similarity Index Measure) and FID (Frechet Inception Distance) compared to other prevalent generative models:
<div align="center">    <img src=".\img\1-exp-overall-wifi-ssim.png"  height=230><img src=".\img\2-exp-overall-wifi-fid.png" height=230> </div>

### 1.2 FMCW Data Generation

By executing the following code, you will generate FMCW data, and the corresponding average SSIM (Structural Similarity Index Measure) and FID (Fréchet Inception Distance) will be displayed in the command line, which matches the values reported in section 6.2: Overall Generation Quality of the paper.

```python
python3 inference.py --task_id 1
```

The generated data are stored in `.mat` format, and can be found at `./dataset/fmcw/output`.

Our model showcases the best performance in both SSIM (Structure Similarity Index Measure) and FID (Frechet Inception Distance) among all prevalent generative models:
<div align="center">    <img src=".\img\3-exp-overall-fmcw-ssim.png"  height=230><img src=".\img\4-exp-overall-fmcw-fid.png" height=230> </div>

## 2. Case Study

### 2.1 Augmented Wireless Sensing

A pre-trained RF-Diffusion can be leveraged as a data augmenter, which generates synthetic RF signals of the designated type. The synthetic samples are then mixed with the original dataset, collectively employed to train the wireless sensing model.
You can try performing the data generation task on your own dataset based on the instructions in [RF Data Generation](#1-rf-data-generation), and train your own model with both real-world and synthetic data.

To retrain a new model, you only need to place your own data files within the `./dataset/wifi/raw` or `./dataset/fmcw/raw` directory, and then execute the `train.py` script to retrain. You may need to properly set the `./tfdiff/params.py` file to correspond to your input data format.

Taking Wi-Fi gesture recognition as an example. We choose the Widar3.0 dataset and perform augmented wireless sensing on two models, Widar3.0 and EI, to test the performance gain of data augmentation in both cross-domain and in-domain scenarios, which can be found in section 7.1: Wi-Fi Gesture Recognition of the paper.
<div align="center">    <img src=".\img\8-exp-sensing-cross.png"  height=230><img src=".\img\9-exp-sensing-in.png" height=230> </div>

<div align="center">    <img src=".\img\10-exp-sensing-data.png"  height=230> </div>


### 2.2 5G FDD Channel Estimation

By executing the following command, a downlink channel estimation for 5G FDD system can be performed. 

```python
python3 inference.py --task_id 2
```

The corresponding average Signal-to-Noise Ratio (SNR) will be displayed in the command line and found in section 7.2: 5G FDD Channel Estimation of the paper.

The channel estimation is evaluated based on the [Argos](https://renew.rice.edu/dataset-argos.html) dataset. As the results show, our model showcases the best performance compared to state-of-the-art models.

<div align="center">    <img src=".\img\11-exp-channel-sample.png"  height=230><img src=".\img\12-exp-channel-snr.png" height=230> </div>

<!--
### 2.3 Supplementary: EEG Signal Denoise

RF-Diffusion is designed to generate a wide range of time-series data. While its primary application is in the wireless/RF signals domain, its capabilities extend beyond that.
To verify this, we provide a supplementary case study for EEG denoising, which doesn't appear in our submitted paper due to the page limitation.

To run the EEG denoising application, you only need to extract the contents of `eeg.zip` and place the extracted folder in the `model` folder. 

```bash
unzip eeg.zip -d [RF-Diffusion/model]
```

By executing the following code, RF-Diffusion can be leveraged to denoise the EEG signals which is contaminated by EOG interference. 

```python
python3 inference.py --task_id 3
```

The corresponding average Signal-to-Noise Ratio (SNR) will be displayed in the command line. The denoised EEG data can be found at `./dataset/eeg/output`.

Our EEG denoising evaluation is tested on the [GCTNET](https://github.com/JinY97/GCTNet/tree/main/data) dataset. Compared with other denoising methods, RF-Diffusion demonstrates a delightful result.


<div align="center">    <img src=".\img\13-exp-eeg-sample.png"  height=230><img src=".\img\14-exp-eeg-snr.png" height=230> </div>
-->
## License
The code, data and related scripts are made available under the GNU General Public License v3.0. By downloading it or using them, you agree to the terms of this license.

## Reference
If you use our dataset in your work, please reference it using
```
@inproceedings{chi2024rf,
  title={RF-Diffusion: Radio Signal Generation via Time-Frequency Diffusion},
  author={Chi, Guoxuan and Yang, Zheng and Wu, Chenshu and Xu, Jingao and Gao, Yuchong and Liu, Yunhao and Han, Tony Xiao},
  booktitle={Proceedings of the 30th Annual International Conference on Mobile Computing and Networking},
  pages={77--92},
  year={2024}
}
```



[^DDPM]: Ho J, Jain A, Abbeel P. Denoising diffusion probabilistic models[J]. Advances in neural information processing systems, 2020, 33: 6840-6851.
[^DCGAN]: Radford A, Metz L, Chintala S. Unsupervised representation learning with deep convolutional generative adversarial networks[J]. arXiv preprint arXiv:1511.06434, 2015.
[^CVAE]: Sohn K, Lee H, Yan X. Learning structured output representation using deep conditional generative models[J]. Advances in neural information processing systems, 2015, 28.


================================================
FILE: complex/__init__.py
================================================


================================================
FILE: complex/complex_functions.py
================================================
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
@author: spopoff
"""
import torch
from torch.nn.functional import relu, max_pool2d, max_pool3d, avg_pool2d, avg_pool1d, dropout, dropout2d, dropout3d, interpolate, sigmoid, tanh, leaky_relu

def complex_matmul(A, B):
    '''
        Performs the matrix product between two complex matricess
    '''

    outp_real = torch.matmul(A.real, B.real) - torch.matmul(A.imag, B.imag)
    outp_imag = torch.matmul(A.real, B.imag) + torch.matmul(A.imag, B.real)
    
    return outp_real.type(torch.complex64) + 1j * outp_imag.type(torch.complex64)

def complex_avg_pool1d(input, *args, **kwargs):
    absolute_value_real = avg_pool1d(input.real, *args, **kwargs)
    absolute_value_imag =  avg_pool1d(input.imag, *args, **kwargs)    

    return absolute_value_real.type(torch.complex64)+1j*absolute_value_imag.type(torch.complex64)

def complex_avg_pool2d(input, *args, **kwargs):
    '''
    Perform complex average pooling.
    '''    
    absolute_value_real = avg_pool2d(input.real, *args, **kwargs)
    absolute_value_imag =  avg_pool2d(input.imag, *args, **kwargs)    
    
    return absolute_value_real.type(torch.complex64)+1j*absolute_value_imag.type(torch.complex64)

def complex_normalize(input):
    '''
    Perform complex normalization
    '''
    real_value, imag_value = input.real, input.imag
    real_norm = (real_value - real_value.mean()) / real_value.std()
    imag_norm = (imag_value - imag_value.mean()) / imag_value.std()
    
    return real_norm.type(torch.complex64) + 1j*imag_norm.type(torch.complex64)

def complex_leaky_relu(input, negative_slope):
    return leaky_relu(input.real, negative_slope).type(torch.complex64)+1j*leaky_relu(input.imag, negative_slope).type(torch.complex64)

def complex_relu(input):
    return relu(input.real).type(torch.complex64)+1j*relu(input.imag).type(torch.complex64)

def complex_sigmoid(input):
    return sigmoid(input.real).type(torch.complex64)+1j*sigmoid(input.imag).type(torch.complex64)

def complex_tanh(input):
    return tanh(input.real).type(torch.complex64)+1j*tanh(input.imag).type(torch.complex64)

def complex_opposite(input):
    return -(input.real).type(torch.complex64)+1j*(-(input.imag).type(torch.complex64))

def complex_stack(input, dim):
    input_real = [x.real for x in input]
    input_imag = [x.imag for x in input]
    return torch.stack(input_real, dim).type(torch.complex64)+1j*torch.stack(input_imag, dim).type(torch.complex64)

def _retrieve_elements_from_indices(tensor, indices):
    flattened_tensor = tensor.flatten(start_dim=-2)
    output = flattened_tensor.gather(dim=-1, index=indices.flatten(start_dim=-2)).view_as(indices)
    return output

def _retrieve_elements_from_indices3d(tensor, indices):
    flattened_tensor = tensor.flatten(start_dim=-3)
    output = flattened_tensor.gather(dim=-1, index=indices.flatten(start_dim=-3)).view_as(indices)
    return output

def complex_upsample(input, size=None, scale_factor=None, mode='nearest',
                             align_corners=None, recompute_scale_factor=None):
    '''
        Performs upsampling by separately interpolating the real and imaginary part and recombining
    '''
    outp_real = interpolate(input.real,  size=size, scale_factor=scale_factor, mode=mode,
                                    align_corners=align_corners, recompute_scale_factor=recompute_scale_factor)
    outp_imag = interpolate(input.imag,  size=size, scale_factor=scale_factor, mode=mode,
                                    align_corners=align_corners, recompute_scale_factor=recompute_scale_factor)
    
    return outp_real.type(torch.complex64) + 1j * outp_imag.type(torch.complex64)

def complex_upsample2(input, size=None, scale_factor=None, mode='nearest',
                             align_corners=None, recompute_scale_factor=None):
    '''
        Performs upsampling by separately interpolating the amplitude and phase part and recombining
    '''
    outp_abs = interpolate(input.abs(),  size=size, scale_factor=scale_factor, mode=mode,
                                    align_corners=align_corners, recompute_scale_factor=recompute_scale_factor)
    angle = torch.atan2(input.imag,input.real)
    outp_angle = interpolate(angle,  size=size, scale_factor=scale_factor, mode=mode,
                                    align_corners=align_corners, recompute_scale_factor=recompute_scale_factor)
    
    return outp_abs \
           * (torch.cos(angle).type(torch.complex64)+1j*torch.sin(angle).type(torch.complex64))


def complex_max_pool2d(input,kernel_size, stride=None, padding=0,
                                dilation=1, ceil_mode=False, return_indices=False):
    '''
    Perform complex max pooling by selecting on the absolute value on the complex values.
    '''
    absolute_value, indices =  max_pool2d(
                               input.abs(), 
                               kernel_size = kernel_size, 
                               stride = stride, 
                               padding = padding, 
                               dilation = dilation,
                               ceil_mode = ceil_mode, 
                               return_indices = True
                            )
    # performs the selection on the absolute values
    absolute_value = absolute_value.type(torch.complex64)
    # retrieve the corresponding phase value using the indices
    # unfortunately, the derivative for 'angle' is not implemented
    angle = torch.atan2(input.imag,input.real)
    # get only the phase values selected by max pool
    angle = _retrieve_elements_from_indices(angle, indices)
    return absolute_value \
           * (torch.cos(angle).type(torch.complex64)+1j*torch.sin(angle).type(torch.complex64))

def complex_max_pool3d(input,kernel_size, stride=None, padding=0,
                                dilation=1, ceil_mode=False, return_indices=False):
    '''
    Perform complex max pooling by selecting on the absolute value on the complex values.
    '''
    absolute_value, indices =  max_pool3d(
                               input.abs(), 
                               kernel_size = kernel_size, 
                               stride = stride, 
                               padding = padding, 
                               dilation = dilation,
                               ceil_mode = ceil_mode, 
                               return_indices = True
                            )
    # performs the selection on the absolute values
    absolute_value = absolute_value.type(torch.complex64)
    # retrieve the corresponding phase value using the indices
    # unfortunately, the derivative for 'angle' is not implemented
    angle = torch.atan2(input.imag,input.real)
    # get only the phase values selected by max pool
    angle = _retrieve_elements_from_indices3d(angle, indices)
    return absolute_value \
           * (torch.cos(angle).type(torch.complex64)+1j*torch.sin(angle).type(torch.complex64))


def complex_adaptive_avg_pool3d(input,kernel_size, stride=None, padding=0,
                                dilation=1, ceil_mode=False, return_indices=False):
    '''
    Perform complex max pooling by selecting on the absolute value on the complex values.
    '''
    absolute_value, indices =  max_pool3d(
                               input.abs(), 
                               kernel_size = kernel_size, 
                               stride = stride, 
                               padding = padding, 
                               dilation = dilation,
                               ceil_mode = ceil_mode, 
                               return_indices = True
                            )
    # performs the selection on the absolute values
    absolute_value = absolute_value.type(torch.complex64)
    # retrieve the corresponding phase value using the indices
    # unfortunately, the derivative for 'angle' is not implemented
    angle = torch.atan2(input.imag,input.real)
    # get only the phase values selected by max pool
    angle = _retrieve_elements_from_indices(angle, indices)
    return absolute_value \
           * (torch.cos(angle).type(torch.complex64)+1j*torch.sin(angle).type(torch.complex64))


def complex_dropout(input, p=0.5, training=True):
    # need to have the same dropout mask for real and imaginary part, 
    # this not a clean solution!
    device = input.device
    mask = torch.ones(*input.shape, dtype = torch.float32, device = device)
    mask = dropout(mask, p, training)*1/(1-p)
    mask.type(input.dtype)
    return mask*input


def complex_dropout2d(input, p=0.5, training=True):
    # need to have the same dropout mask for real and imaginary part, 
    # this not a clean solution!
    device = input.device
    mask = torch.ones(*input.shape, dtype = torch.float32, device = device)
    mask = dropout2d(mask, p, training)*1/(1-p)
    mask.type(input.dtype)
    return mask*input

def complex_dropout3d(input, p=0.5, training=True):
    # need to have the same dropout mask for real and imaginary part, 
    # this not a clean solution!
    device = input.device
    mask = torch.ones(*input.shape, dtype = torch.float32, device = device)
    mask = dropout3d(mask, p, training)*1/(1-p)
    mask.type(input.dtype)
    return mask*input




================================================
FILE: complex/complex_layers.py
================================================
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 19 10:30:02 2019

@author: Sebastien M. Popoff


Based on https://openreview.net/forum?id=H1T2hmZAb
"""

import torch
from torch.nn import Module, Parameter, init
from torch.nn import Conv2d, Conv3d, Linear, BatchNorm1d, BatchNorm2d, BatchNorm3d, LayerNorm
from torch.nn import ConvTranspose2d
from .complex_functions import complex_relu, complex_max_pool2d, complex_avg_pool2d, complex_max_pool3d
from .complex_functions import complex_dropout, complex_dropout2d, complex_dropout3d
from .complex_functions import complex_sigmoid, complex_tanh, complex_opposite

def apply_complex(fr, fi, input, dtype = torch.complex64):
    return (fr(input.real)-fi(input.imag)).type(dtype) \
            + 1j*(fr(input.imag)+fi(input.real)).type(dtype)

class ComplexDropout(Module):
    def __init__(self,p=0.5):
        super(ComplexDropout,self).__init__()
        self.p = p

    def forward(self,input):
        if self.training:
            return complex_dropout(input,self.p)
        else:
            return input

class ComplexDropout2d(Module):
    def __init__(self,p=0.5):
        super(ComplexDropout2d,self).__init__()
        self.p = p

    def forward(self,input):
        if self.training:
            return complex_dropout2d(input,self.p)
        else:
            return input
        
class ComplexDropout3d(Module):
    def __init__(self,p=0.5):
        super(ComplexDropout3d,self).__init__()
        self.p = p

    def forward(self,input):
        if self.training:
            return complex_dropout3d(input,self.p)
        else:
            return input

class ComplexMaxPool2d(Module):

    def __init__(self,kernel_size, stride= None, padding = 0,
                 dilation = 1, return_indices = False, ceil_mode = False):
        super(ComplexMaxPool2d,self).__init__()
        self.kernel_size = kernel_size
        self.stride = stride
        self.padding = padding
        self.dilation = dilation
        self.ceil_mode = ceil_mode
        self.return_indices = return_indices

    def forward(self,input):
        return complex_max_pool2d(input,kernel_size = self.kernel_size,
                                stride = self.stride, padding = self.padding,
                                dilation = self.dilation, ceil_mode = self.ceil_mode,
                                return_indices = self.return_indices)

class ComplexMaxPool3d(Module):

    def __init__(self,kernel_size, stride=None, padding = 0,
                 dilation = 1, return_indices = False, ceil_mode = False):
        super(ComplexMaxPool3d, self).__init__()
        self.kernel_size = kernel_size
        self.stride = stride
        self.padding = padding
        self.dilation = dilation
        self.ceil_mode = ceil_mode
        self.return_indices = return_indices

    def forward(self,input):
        return complex_max_pool3d(input,kernel_size = self.kernel_size,
                                stride = self.stride, padding = self.padding,
                                dilation = self.dilation, ceil_mode = self.ceil_mode,
                                return_indices = self.return_indices)
    

class ComplexAvgPool2d(Module):

    def __init__(self,kernel_size, stride= None, padding = 0,
                 dilation = 1, return_indices = False, ceil_mode = False):
        super(ComplexAvgPool2d,self).__init__()
        self.kernel_size = kernel_size
        self.stride = stride
        self.padding = padding
        self.dilation = dilation
        self.ceil_mode = ceil_mode
        self.return_indices = return_indices

    def forward(self,input):
        return complex_avg_pool2d(input,kernel_size = self.kernel_size,
                                stride = self.stride, padding = self.padding,
                                dilation = self.dilation, ceil_mode = self.ceil_mode,
                                return_indices = self.return_indices)


class ComplexReLU(Module):

     def forward(self,input):
         return complex_relu(input)
    
class ComplexSigmoid(Module):

     def forward(self,input):
         return complex_sigmoid(input)
    
class ComplexTanh(Module):

     def forward(self,input):
         return complex_tanh(input)

class ComplexConvTranspose2d(Module):

    def __init__(self,in_channels, out_channels, kernel_size, stride=1, padding=0,
                 output_padding=0, groups=1, bias=True, dilation=1, padding_mode='zeros'):

        super(ComplexConvTranspose2d, self).__init__()

        self.conv_tran_r = ConvTranspose2d(in_channels, out_channels, kernel_size, stride, padding,
                                       output_padding, groups, bias, dilation, padding_mode)
        self.conv_tran_i = ConvTranspose2d(in_channels, out_channels, kernel_size, stride, padding,
                                       output_padding, groups, bias, dilation, padding_mode)


    def forward(self,input):
        return apply_complex(self.conv_tran_r, self.conv_tran_i, input)

class ComplexConv2d(Module):

    def __init__(self,in_channels, out_channels, kernel_size=3, stride=1, padding = 0,
                 dilation=1, groups=1, bias=True):
        super(ComplexConv2d, self).__init__()
        self.conv_r = Conv2d(in_channels, out_channels, kernel_size, stride, padding, dilation, groups, bias)
        self.conv_i = Conv2d(in_channels, out_channels, kernel_size, stride, padding, dilation, groups, bias)
        
    def forward(self,input):    
        return apply_complex(self.conv_r, self.conv_i, input)
    
class ComplexConv3d(Module):

    def __init__(self, in_channels, out_channels, kernel_size=3, stride=1, padding = 0,
                 dilation=1, groups=1, bias=True):
        super(ComplexConv3d, self).__init__()
        self.conv_r = Conv3d(in_channels, out_channels, kernel_size, stride, padding, dilation, groups, bias)
        self.conv_i = Conv3d(in_channels, out_channels, kernel_size, stride, padding, dilation, groups, bias)
        
    def forward(self,input):    
        return apply_complex(self.conv_r, self.conv_i, input)
    

class ComplexLinear(Module):

    def __init__(self, in_features, out_features):
        super(ComplexLinear, self).__init__()
        self.fc_r = Linear(in_features, out_features)
        self.fc_i = Linear(in_features, out_features)

    def forward(self, input):
        return apply_complex(self.fc_r, self.fc_i, input)


class NaiveComplexBatchNorm1d(Module):
    '''
    Naive approach to complex batch norm, perform batch norm independently on real and imaginary part.
    '''
    def __init__(self, num_features, eps=1e-5, momentum=0.1, affine=True, \
                 track_running_stats=True):
        super(NaiveComplexBatchNorm1d, self).__init__()
        self.bn_r = BatchNorm1d(num_features, eps, momentum, affine, track_running_stats)
        self.bn_i = BatchNorm1d(num_features, eps, momentum, affine, track_running_stats)

    def forward(self,input):
        return self.bn_r(input.real).type(torch.complex64) +1j*self.bn_i(input.imag).type(torch.complex64)

class NaiveComplexBatchNorm2d(Module):
    '''
    Naive approach to complex batch norm, perform batch norm independently on real and imaginary part.
    '''
    def __init__(self, num_features, eps=1e-5, momentum=0.1, affine=True, \
                 track_running_stats=True):
        super(NaiveComplexBatchNorm2d, self).__init__()
        self.bn_r = BatchNorm2d(num_features, eps, momentum, affine, track_running_stats)
        self.bn_i = BatchNorm2d(num_features, eps, momentum, affine, track_running_stats)

    def forward(self,input):
        return self.bn_r(input.real).type(torch.complex64) +1j*self.bn_i(input.imag).type(torch.complex64)

class NaiveComplexBatchNorm3d(Module):
    '''
    Naive approach to complex batch norm, perform batch norm independently on real and imaginary part.
    '''
    def __init__(self, num_features, eps=1e-5, momentum=0.1, affine=True, \
                 track_running_stats=True):
        super(NaiveComplexBatchNorm3d, self).__init__()
        self.bn_r = BatchNorm3d(num_features, eps, momentum, affine, track_running_stats)
        self.bn_i = BatchNorm3d(num_features, eps, momentum, affine, track_running_stats)

    def forward(self,input):
        return self.bn_r(input.real).type(torch.complex64) +1j*self.bn_i(input.imag).type(torch.complex64)
    
class NaiveComplexLayerNorm(Module):
    '''
    Naive approach to complex layer norm, perform layer norm independently on real and imaginary part.
    '''
    def __init__(self, normalized_shape, eps=1e-5, elementwise_affine=True):
        super(NaiveComplexLayerNorm, self).__init__()
        self.ln_r = LayerNorm(normalized_shape, eps, elementwise_affine)
        self.ln_i = LayerNorm(normalized_shape, eps, elementwise_affine)

    def forward(self,input):
        return self.ln_r(input.real).type(torch.complex64) +1j*self.ln_i(input.imag).type(torch.complex64)

class _ComplexBatchNorm(Module):

    def __init__(self, num_features, eps=1e-5, momentum=0.1, affine=True,
                 track_running_stats=True):
        super(_ComplexBatchNorm, self).__init__()
        self.num_features = num_features
        self.eps = eps
        self.momentum = momentum
        self.affine = affine
        self.track_running_stats = track_running_stats
        if self.affine:
            self.weight = Parameter(torch.Tensor(num_features,3))
            self.bias = Parameter(torch.Tensor(num_features,2))
        else:
            self.register_parameter('weight', None)
            self.register_parameter('bias', None)
        if self.track_running_stats:
            self.register_buffer('running_mean', torch.zeros(num_features, dtype = torch.complex64))
            self.register_buffer('running_covar', torch.zeros(num_features,3))
            self.running_covar[:,0] = 1.4142135623730951
            self.running_covar[:,1] = 1.4142135623730951
            self.register_buffer('num_batches_tracked', torch.tensor(0, dtype=torch.long))
        else:
            self.register_parameter('running_mean', None)
            self.register_parameter('running_covar', None)
            self.register_parameter('num_batches_tracked', None)
        self.reset_parameters()

    def reset_running_stats(self):
        if self.track_running_stats:
            self.running_mean.zero_()
            self.running_covar.zero_()
            self.running_covar[:,0] = 1.4142135623730951
            self.running_covar[:,1] = 1.4142135623730951
            self.num_batches_tracked.zero_()

    def reset_parameters(self):
        self.reset_running_stats()
        if self.affine:
            init.constant_(self.weight[:,:2],1.4142135623730951)
            init.zeros_(self.weight[:,2])
            init.zeros_(self.bias)

class ComplexBatchNorm2d(_ComplexBatchNorm):

    def forward(self, input):
        exponential_average_factor = 0.0

        if self.training and self.track_running_stats:
            if self.num_batches_tracked is not None:
                self.num_batches_tracked += 1
                if self.momentum is None:  # use cumulative moving average
                    exponential_average_factor = 1.0 / float(self.num_batches_tracked)
                else:  # use exponential moving average
                    exponential_average_factor = self.momentum

        if self.training or (not self.training and not self.track_running_stats):
            # calculate mean of real and imaginary part
            # mean does not support automatic differentiation for outputs with complex dtype.
            mean_r = input.real.mean([0, 2, 3]).type(torch.complex64)
            mean_i = input.imag.mean([0, 2, 3]).type(torch.complex64)
            mean = mean_r + 1j*mean_i
        else:
            mean = self.running_mean

        if self.training and self.track_running_stats:
            # update running mean
            with torch.no_grad():
                self.running_mean = exponential_average_factor * mean\
                    + (1 - exponential_average_factor) * self.running_mean

        input = input - mean[None, :, None, None]

        if self.training or (not self.training and not self.track_running_stats):
            # Elements of the covariance matrix (biased for train)
            n = input.numel() / input.size(1)
            Crr = 1./n*input.real.pow(2).sum(dim=[0,2,3])+self.eps
            Cii = 1./n*input.imag.pow(2).sum(dim=[0,2,3])+self.eps
            Cri = (input.real.mul(input.imag)).mean(dim=[0,2,3])
        else:
            Crr = self.running_covar[:,0]+self.eps
            Cii = self.running_covar[:,1]+self.eps
            Cri = self.running_covar[:,2]#+self.eps 
       
        if self.training and self.track_running_stats:
            with torch.no_grad():
                self.running_covar[:,0] = exponential_average_factor * Crr * n / (n - 1)\
                    + (1 - exponential_average_factor) * self.running_covar[:,0]

                self.running_covar[:,1] = exponential_average_factor * Cii * n / (n - 1)\
                    + (1 - exponential_average_factor) * self.running_covar[:,1]

                self.running_covar[:,2] = exponential_average_factor * Cri * n / (n - 1)\
                    + (1 - exponential_average_factor) * self.running_covar[:,2]

        # calculate the inverse square root the covariance matrix
        det = Crr*Cii-Cri.pow(2)
        s = torch.sqrt(det)
        t = torch.sqrt(Cii+Crr + 2 * s)
        inverse_st = 1.0 / (s * t)
        Rrr = (Cii + s) * inverse_st
        Rii = (Crr + s) * inverse_st
        Rri = -Cri * inverse_st

        input = (Rrr[None,:,None,None]*input.real+Rri[None,:,None,None]*input.imag).type(torch.complex64) \
                + 1j*(Rii[None,:,None,None]*input.imag+Rri[None,:,None,None]*input.real).type(torch.complex64)

        if self.affine:
            input = (self.weight[None,:,0,None,None]*input.real+self.weight[None,:,2,None,None]*input.imag+\
                    self.bias[None,:,0,None,None]).type(torch.complex64) \
                    +1j*(self.weight[None,:,2,None,None]*input.real+self.weight[None,:,1,None,None]*input.imag+\
                    self.bias[None,:,1,None,None]).type(torch.complex64)

        return input


class ComplexBatchNorm1d(_ComplexBatchNorm):

    def forward(self, input):

        exponential_average_factor = 0.0


        if self.training and self.track_running_stats:
            if self.num_batches_tracked is not None:
                self.num_batches_tracked += 1
                if self.momentum is None:  # use cumulative moving average
                    exponential_average_factor = 1.0 / float(self.num_batches_tracked)
                else:  # use exponential moving average
                    exponential_average_factor = self.momentum

        if self.training or (not self.training and not self.track_running_stats):            
            # calculate mean of real and imaginary part
            mean_r = input.real.mean(dim=0).type(torch.complex64)
            mean_i = input.imag.mean(dim=0).type(torch.complex64)
            mean = mean_r + 1j*mean_i
        else:
            mean = self.running_mean
        
        if self.training and self.track_running_stats:
            # update running mean
            with torch.no_grad():
                self.running_mean = exponential_average_factor * mean\
                    + (1 - exponential_average_factor) * self.running_mean

        input = input - mean[None, ...]

        if self.training or (not self.training and not self.track_running_stats):
            # Elements of the covariance matrix (biased for train)
            n = input.numel() / input.size(1)
            Crr = input.real.var(dim=0,unbiased=False)+self.eps
            Cii = input.imag.var(dim=0,unbiased=False)+self.eps
            Cri = (input.real.mul(input.imag)).mean(dim=0)
        else:
            Crr = self.running_covar[:,0]+self.eps
            Cii = self.running_covar[:,1]+self.eps
            Cri = self.running_covar[:,2]
            
        if self.training and self.track_running_stats:
                self.running_covar[:,0] = exponential_average_factor * Crr * n / (n - 1)\
                    + (1 - exponential_average_factor) * self.running_covar[:,0]

                self.running_covar[:,1] = exponential_average_factor * Cii * n / (n - 1)\
                    + (1 - exponential_average_factor) * self.running_covar[:,1]

                self.running_covar[:,2] = exponential_average_factor * Cri * n / (n - 1)\
                    + (1 - exponential_average_factor) * self.running_covar[:,2]

        # calculate the inverse square root the covariance matrix
        det = Crr*Cii-Cri.pow(2)
        s = torch.sqrt(det)
        t = torch.sqrt(Cii+Crr + 2 * s)
        inverse_st = 1.0 / (s * t)
        Rrr = (Cii + s) * inverse_st
        Rii = (Crr + s) * inverse_st
        Rri = -Cri * inverse_st
        
        input = (Rrr[None,:]*input.real+Rri[None,:]*input.imag).type(torch.complex64) \
                + 1j*(Rii[None,:]*input.imag+Rri[None,:]*input.real).type(torch.complex64)

        if self.affine:
            input = (self.weight[None,:,0]*input.real+self.weight[None,:,2]*input.imag+\
                    self.bias[None,:,0]).type(torch.complex64) \
                    +1j*(self.weight[None,:,2]*input.real+self.weight[None,:,1]*input.imag+\
                    self.bias[None,:,1]).type(torch.complex64)


        del Crr, Cri, Cii, Rrr, Rii, Rri, det, s, t
        return input

class ComplexGRUCell(Module):
    """
    A GRU cell for complex-valued inputs
    """

    def __init__(self, input_length=10, hidden_length=20):
        super(ComplexGRUCell, self).__init__()
        self.input_length = input_length
        self.hidden_length = hidden_length

        # reset gate components
        self.linear_reset_w1 = ComplexLinear(self.input_length, self.hidden_length)
        self.linear_reset_r1 = ComplexLinear(self.hidden_length, self.hidden_length)

        self.linear_reset_w2 = ComplexLinear(self.input_length, self.hidden_length)
        self.linear_reset_r2 = ComplexLinear(self.hidden_length, self.hidden_length)

        # update gate components
        self.linear_gate_w3 = ComplexLinear(self.input_length, self.hidden_length)
        self.linear_gate_r3 = ComplexLinear(self.hidden_length, self.hidden_length)

        self.activation_gate = ComplexSigmoid()
        self.activation_candidate = ComplexTanh()

    def reset_gate(self, x, h):
        x_1 = self.linear_reset_w1(x)
        h_1 = self.linear_reset_r1(h)
        # gate update
        reset = self.activation_gate(x_1 + h_1)
        return reset

    def update_gate(self, x, h):
        x_2 = self.linear_reset_w2(x)
        h_2 = self.linear_reset_r2(h)
        z = self.activation_gate(h_2 + x_2)
        return z

    def update_component(self, x, h, r):
        x_3 = self.linear_gate_w3(x)
        h_3 = r * self.linear_gate_r3(h) # element-wise multiplication
        gate_update = self.activation_candidate(x_3 + h_3)
        return gate_update

    def forward(self, x, h):
        # Equation 1. reset gate vector
        r = self.reset_gate(x, h)

        # Equation 2: the update gate - the shared update gate vector z
        z = self.update_gate(x, h)

        # Equation 3: The almost output component
        n = self.update_component(x, h, r)

        # Equation 4: the new hidden state
        h_new = (1 + complex_opposite(z)) * n + z * h # element-wise multiplication

        return h_new
    
class ComplexBNGRUCell(Module):
    """
    A BN-GRU cell for complex-valued inputs
    """

    def __init__(self, input_length=10, hidden_length=20):
        super(ComplexBNGRUCell, self).__init__()
        self.input_length = input_length
        self.hidden_length = hidden_length

        # reset gate components
        self.linear_reset_w1 = ComplexLinear(self.input_length, self.hidden_length)
        self.linear_reset_r1 = ComplexLinear(self.hidden_length, self.hidden_length)

        self.linear_reset_w2 = ComplexLinear(self.input_length, self.hidden_length)
        self.linear_reset_r2 = ComplexLinear(self.hidden_length, self.hidden_length)

        # update gate components
        self.linear_gate_w3 = ComplexLinear(self.input_length, self.hidden_length)
        self.linear_gate_r3 = ComplexLinear(self.hidden_length, self.hidden_length)

        self.activation_gate = ComplexSigmoid()
        self.activation_candidate = ComplexTanh()

        self.bn = ComplexBatchNorm2d(1)
        
    def reset_gate(self, x, h):
        x_1 = self.linear_reset_w1(x)
        h_1 = self.linear_reset_r1(h)
        # gate update
        reset = self.activation_gate(self.bn(x_1) + self.bn(h_1))
        return reset

    def update_gate(self, x, h):
        x_2 = self.linear_reset_w2(x)
        h_2 = self.linear_reset_r2(h)
        z = self.activation_gate(self.bn(h_2) + self.bn(x_2))
        return z

    def update_component(self, x, h, r):
        x_3 = self.linear_gate_w3(x)
        h_3 = r * self.bn(self.linear_gate_r3(h)) # element-wise multiplication
        gate_update = self.activation_candidate(self.bn(self.bn(x_3) + h_3))
        return gate_update

    def forward(self, x, h):
        # Equation 1. reset gate vector
        r = self.reset_gate(x, h)

        # Equation 2: the update gate - the shared update gate vector z
        z = self.update_gate(x, h)

        # Equation 3: The almost output component
        n = self.update_component(x, h, r)

        # Equation 4: the new hidden state
        h_new = (1 + complex_opposite(z)) * n + z * h # element-wise multiplication

        return h_new

================================================
FILE: complex/complex_module.py
================================================
import torch
import torch.nn as nn
from torch.nn import functional as F

import numpy as np
import math


def apply_complex(F_r, F_i, X):
    X_r, X_i = [x.squeeze(dim=-1) for x in torch.split(X, 1, dim=-1)]
    return torch.stack((F_r(X_r) - F_i(X_i), F_r(X_i) + F_i(X_r)), dim=-1)

def apply_complex_sep(F_r, F_i, X):
    X_r, X_i = [x.squeeze(dim=-1) for x in torch.split(X, 1, dim=-1)]
    return torch.stack((F_r(X_r), F_i(X_i)), dim=-1)

@torch.jit.script
def complex_mul(X, Y):
    X_r, X_i = [x.squeeze(dim=-1) for x in torch.split(X, 1, dim=-1)]
    Y_r, Y_i = [y.squeeze(dim=-1) for y in torch.split(Y, 1, dim=-1)]
    Z_r = torch.mul(X_r, Y_r) - torch.mul(X_i, Y_i)
    Z_i = torch.mul(X_r, Y_i) + torch.mul(X_i, Y_r)
    return torch.stack((Z_r, Z_i), dim=-1)

@torch.jit.script
def complex_bmm(X, Y):
    X_r, X_i = [x.squeeze(dim=-1) for x in torch.split(X, 1, dim=-1)]
    Y_r, Y_i = [y.squeeze(dim=-1) for y in torch.split(Y, 1, dim=-1)]
    Z_r = torch.bmm(X_r, Y_r) - torch.bmm(X_i, Y_i)
    Z_i = torch.bmm(X_r, Y_i) + torch.bmm(X_i, Y_r)
    return torch.stack((Z_r, Z_i), dim=-1)

@torch.jit.script
def complex_softmax(X):
    X_r, X_i = [x.squeeze(dim=-1) for x in torch.split(X, 1, dim=-1)]
    return torch.stack((F.softmax(X_r, dim=-1), F.softmax(X_i, dim=-1)), dim=-1)

@torch.jit.script
def transpose_qkv(x, num_heads: int):
    x = x.reshape(x.shape[0], x.shape[1], num_heads, -1, 2)
    x = x.transpose(1, 2)
    return x.reshape(-1, x.shape[2], x.shape[3], 2)

@torch.jit.script
def transpose_output(x, num_heads: int):
    x = x.reshape(-1, num_heads, x.shape[1], x.shape[2], 2)
    x = x.transpose(1, 2)
    return x.reshape(x.shape[0], x.shape[1], -1, 2)


class ComplexDropout(nn.Module):
    def __init__(self, p=0.5):
        super().__init__()
        self.p = p

    def forward(self, X):
        device = X.device
        dtype = X.dtype
        mask = torch.ones(*X.shape[-3:], device=device, dtype=dtype)
        mask = F.dropout1d(mask, p=0.5, training=self.training)
        return torch.mul(X, mask)


class ComplexGELU(nn.Module):
    def __init__(self, approximate='none'):
        super().__init__()
        self.gelu_r = nn.GELU(approximate)
        self.gelu_i = nn.GELU(approximate)
    
    def forward(self, X):
        return apply_complex_sep(self.gelu_r, self.gelu_i, X)


class ComplexSiLU(nn.Module):
    def __init__(self):
        super().__init__()
        self.silu_r = nn.SiLU()
        self.silu_i = nn.SiLU()

    def forward(self, X):
        return apply_complex_sep(self.silu_r, self.silu_i, X)


class ComplexReLU(nn.Module):
    def __init__(self):
        super().__init__()
        self.relu_r = nn.ReLU()
        self.relu_i = nn.ReLU()

    def forward(self, X):
        return apply_complex_sep(self.relu_r, self.relu_i, X)


class ComplexAvgPool3d(nn.Module):
    def __init__(self, kernel_size, stride, padding):
        super().__init__()
        self.avg_pool_r = nn.AvgPool3d(
            kernel_size=kernel_size, stride=stride, padding=padding
        )
        self.avg_pool_i = nn.AvgPool3d(
            kernel_size=kernel_size, stride=stride, padding=padding
        )

    def forward(self, X):
        return apply_complex_sep(self.avg_pool_r, self.avg_pool_i, X)


class ComplexFlatten(nn.Module):
    def __init__(self, start_dim=1, end_dim=-1):
        super().__init__()
        self.flt_r = nn.Flatten(start_dim=start_dim, end_dim=end_dim)
        self.flt_i = nn.Flatten(start_dim=start_dim, end_dim=end_dim)

    def forward(self, X):
        return apply_complex_sep(self.flt_r, self.flt_i, X)


class NaiveComplexBatchNorm3d(nn.Module):
    def __init__(
        self,
        num_features,
        eps=1e-5,
        momentum=0.1,
        affine=True,
        track_running_stats=True,
    ):
        super(NaiveComplexBatchNorm3d, self).__init__()
        self.bn_r = nn.BatchNorm3d(
            num_features, eps, momentum, affine, track_running_stats
        )
        self.bn_i = nn.BatchNorm3d(
            num_features, eps, momentum, affine, track_running_stats
        )

    def forward(self, X):
        return apply_complex_sep(self.bn_r, self.bn_i, X)


class NaiveComplexLayerNorm(nn.Module):
    def __init__(self, normalized_shape, eps=1e-5, elementwise_affine=True):
        super(NaiveComplexLayerNorm, self).__init__()
        self.ln_r = nn.LayerNorm(normalized_shape, eps, elementwise_affine)
        self.ln_i = nn.LayerNorm(normalized_shape, eps, elementwise_affine)

    def forward(self, X):
        return apply_complex_sep(self.ln_r, self.ln_i, X)


class ComplexLinear(nn.Module):
    def __init__(self, in_features, out_features, bias=True):
        super().__init__()
        self.l_r = nn.Linear(in_features, out_features, bias=bias, dtype=torch.float32)
        self.l_i = nn.Linear(in_features, out_features, bias=bias, dtype=torch.float32)

    def forward(self, X):
        return apply_complex(self.l_r, self.l_i, X)


class ComplexMLP(nn.Module):
    def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=ComplexGELU, bias=True, dropout=0.):
        super().__init__()
        out_features = out_features or in_features
        hidden_features = hidden_features or in_features
        self.fc1 = ComplexLinear(in_features, hidden_features, bias)
        self.act = act_layer()
        self.drop1 = ComplexDropout(dropout)
        self.fc2 = ComplexLinear(hidden_features, out_features, bias)
        self.drop2 = ComplexDropout(dropout)

    def forward(self, x):
        x = self.fc1(x)
        x = self.act(x)
        x = self.drop1(x)
        x = self.fc2(x)
        x = self.drop2(x)
        return x

class ComplexConv3d(nn.Module):
    def __init__(self, input_channels, num_channels, kernel_size, padding, stride=1):
        super().__init__()
        self.conv_r = nn.Conv3d(
            input_channels,
            num_channels,
            kernel_size=kernel_size,
            padding=padding,
            stride=stride,
            dtype=torch.float32,
        )
        self.conv_i = nn.Conv3d(
            input_channels,
            num_channels,
            kernel_size=kernel_size,
            padding=padding,
            stride=stride,
            dtype=torch.float32,
        )

    def forward(self, X):
        return apply_complex(self.conv_r, self.conv_i, X)


class ComplexResidual3d(nn.Module):
    def __init__(self, input_channels, num_channels, kernel_size, padding, stride=1):
        super().__init__()
        self.conv1 = ComplexConv3d(
            input_channels,
            num_channels,
            kernel_size=kernel_size,
            padding=padding,
            stride=stride,
        )
        self.conv2 = ComplexConv3d(
            num_channels,
            num_channels,
            kernel_size=kernel_size,
            padding=padding,
            stride=stride,
        )
        self.conv3 = ComplexConv3d(
            input_channels, num_channels, kernel_size=1, padding=0, stride=stride
        )
        self.bn1 = NaiveComplexBatchNorm3d(num_channels)
        self.bn2 = NaiveComplexBatchNorm3d(num_channels)
        self.relu1 = ComplexReLU()
        self.relu2 = ComplexReLU()

    def forward(self, X):
        Y = self.relu1(self.bn1(self.conv1(X)))
        Y = self.bn2(self.conv2(Y)) + self.conv3(X)
        return self.relu2(Y)


# [32 32 10 10 3] -> [32 10 32*10*3]
class ComplexSegment(nn.Module):
    def __init__(self, input_channels, seg_channels, seg_size):
        super().__init__()
        self.seg_conv = ComplexResidual3d(
            input_channels,
            seg_channels,
            kernel_size=seg_size,
            padding=(0, 0, 0),
            stride=seg_size,
        )
        self.flt = ComplexFlatten(start_dim=2, end_dim=-1)

    def forward(self, X):
        Y = self.seg_conv(X)
        Y = Y.transpose(1, 2)
        Y = self.flt(Y)
        return Y


class Complex2Real(nn.Module):
    def __init__(self):
        super().__init__()
        self.linear1 = nn.Linear(2, 2)
        self.linear2 = nn.Linear(2, 1)

    def forward(self, X):
        X = self.linear1(X)
        X = self.linear2(F.relu(X))
        return X.squeeze(dim=-1)


class ComplexDotProductAttention(nn.Module):
    """
    Query shape: [batch_size, query_num, query_key_dim]
    Key shape: [batch_size, key_value_num, query_key_dim]
    Value shape: [batch_size, key_value_num, value_dim]
    """
    def __init__(self, dropout, **kwargs):
        super(ComplexDotProductAttention, self).__init__(**kwargs)
        self.dropout = ComplexDropout(dropout)

    def forward(self, queries, keys, values):
        query_key_dim = queries.shape[-2]
        self.attention_weights = complex_softmax(
            complex_bmm(queries, keys.transpose(1, 2)) / math.sqrt(query_key_dim)
        )
        Y = complex_bmm(self.dropout(self.attention_weights), values)
        return Y


class ComplexMultiHeadAttention(nn.Module):
    def __init__(
        self,
        query_size,
        num_hiddens,
        num_heads,
        dropout,
        key_size=None,
        value_size=None,
        bias=False,
        **kwargs
    ):
        super(ComplexMultiHeadAttention, self).__init__(**kwargs)
        key_size = key_size or query_size
        value_size = value_size or query_size
        self.num_heads = num_heads
        self.attention = ComplexDotProductAttention(dropout=dropout)
        self.w_q = ComplexLinear(query_size, num_hiddens, bias=bias)
        self.w_k = ComplexLinear(key_size, num_hiddens, bias=bias)
        self.w_v = ComplexLinear(value_size, num_hiddens, bias=bias)
        self.w_o = ComplexLinear(num_hiddens, num_hiddens, bias=bias)

    def forward(self, queries, keys, values):
        queries = transpose_qkv(self.w_q(queries), self.num_heads)
        keys = transpose_qkv(self.w_k(keys), self.num_heads)
        values = transpose_qkv(self.w_v(values), self.num_heads)
        output = self.attention(queries, keys, values)
        output_concat = transpose_output(output, self.num_heads)
        Y = self.w_o(output_concat)
        return Y


class ComplexPositionalEncoding(nn.Module):
    def __init__(self, hidden_dim, dropout, max_len=10000):
        super(ComplexPositionalEncoding, self).__init__()
        self.dropout = ComplexDropout(dropout)
        pcode = torch.zeros((1, max_len, hidden_dim, 2), dtype=torch.float32)
        pos = torch.arange(max_len, dtype=torch.float32).reshape(-1, 1) / torch.pow(
            10000, torch.arange(0, hidden_dim, dtype=torch.float32) / hidden_dim
        )
        pcode[:, :, :, 0] = torch.cos(pos)
        pcode[:, :, :, 1] = torch.sin(pos)
        self.register_buffer("pcode", pcode, persistent=False)

    def forward(self, X):
        X = complex_mul(X, self.pcode[:, : X.shape[1], :, :].to(X.device))
        Y = self.dropout(X)
        return Y


class PositionWiseFFN(nn.Module):
    def __init__(self, input_dim, hidden_dim, output_dim, **kwargs):
        super(PositionWiseFFN, self).__init__(**kwargs)
        self.linear1 = ComplexLinear(input_dim, hidden_dim)
        self.relu = ComplexReLU()
        self.linear2 = ComplexLinear(hidden_dim, output_dim)

    def forward(self, X):
        Y = self.linear2(self.relu(self.linear1(X)))
        return Y


class ComplexAddNorm(nn.Module):
    def __init__(self, normalized_shape, dropout, **kwargs):
        super(ComplexAddNorm, self).__init__(**kwargs)
        self.dropout = ComplexDropout(dropout)
        self.ln = NaiveComplexLayerNorm(normalized_shape)

    def forward(self, X, Y):
        Y = self.ln(self.dropout(Y) + X)
        return Y


class ComplexEncoderBlock(nn.Module):
    def __init__(
        self,
        key_dim,
        query_dim,
        value_dim,
        hidden_dim,
        norm_shape,
        ffn_input_dim,
        ffn_hidden_dim,
        num_heads,
        dropout,
        use_bias=False,
        **kwargs
    ):
        super(ComplexEncoderBlock, self).__init__(**kwargs)
        self.attention = ComplexMultiHeadAttention(
            key_dim, query_dim, value_dim, hidden_dim, num_heads, dropout, use_bias
        )
        self.addnorm1 = ComplexAddNorm(norm_shape, dropout)
        self.ffn = PositionWiseFFN(ffn_input_dim, ffn_hidden_dim, ffn_hidden_dim)
        self.addnorm2 = ComplexAddNorm(norm_shape, dropout)

    def forward(self, X):
        Y = self.attention(X, X, X)
        Z = self.addnorm1(X, Y)
        return self.addnorm2(Z, self.ffn(Y))


class ComplexTransformerEncoder(nn.Module):
    def __init__(
        self,
        key_dim,
        query_dim,
        value_dim,
        hidden_dim,
        norm_shape,
        ffn_input_dim,
        ffn_hidden_dim,
        num_heads,
        num_layers,
        dropout,
        use_bias=False,
        **kwargs
    ):
        super(ComplexTransformerEncoder, self).__init__(**kwargs)
        self.hidden_dim = hidden_dim
        self.pos_encoding = ComplexPositionalEncoding(hidden_dim, dropout)
        self.blks = nn.Sequential()
        for n in range(num_layers):
            self.blks.add_module(
                "Block" + str(n),
                ComplexEncoderBlock(
                    key_dim,
                    query_dim,
                    value_dim,
                    hidden_dim,
                    norm_shape,
                    ffn_input_dim,
                    ffn_hidden_dim,
                    num_heads,
                    dropout,
                    use_bias,
                ),
            )

    def forward(self, X, *args):
        X = self.pos_encoding(X * math.sqrt(self.hidden_dim))
        self.attention_weights = [None] * len(self.blks)
        for i, blk in enumerate(self.blks):
            X = blk(X)
            self.attention_weights[i] = blk.attention.attention.attention_weights
        return X


================================================
FILE: inference.py
================================================
import math
import numpy as np
import os
import torch
import scipy.io as scio
import matplotlib.pyplot as plt
import numpy as np
import scipy.io as scio
from matplotlib.font_manager import FontProperties

from argparse import ArgumentParser
import torch.nn as nn

from tfdiff.params import AttrDict, all_params
from tfdiff.wifi_model import tfdiff_WiFi
from tfdiff.fmcw_model import tfdiff_fmcw
from tfdiff.mimo_model import tfdiff_mimo
from tfdiff.eeg_model import tfdiff_eeg
from tfdiff.diffusion import SignalDiffusion, GaussianDiffusion
from tfdiff.dataset import from_path_inference, _nested_map

from tqdm import tqdm

from glob import glob

import torchvision
import torchvision.transforms as transforms
from pytorch_fid import fid_score

@torch.jit.script
def gaussian(window_size: int, tfdiff: float):
    gaussian = torch.tensor([math.exp(-(x - window_size//2)**2/float(2*tfdiff**2)) for x in range(window_size)])
    return gaussian / gaussian.sum()


@torch.jit.script
def create_window(height: int, width: int):
    h_window = gaussian(height, 1.5).unsqueeze(1)
    w_window = gaussian(width, 1.5).unsqueeze(1)
    _2D_window = h_window.mm(w_window.t()).unsqueeze(0).unsqueeze(0)
    window = _2D_window.expand(1, 1, height, width).contiguous()
    return window


def eval_ssim(pred, data, height, width, device):
    window = create_window(height, width).to(torch.complex64).to(device)
    padding = [height//2, width//2]
    mu_pred = torch.nn.functional.conv2d(pred, window, padding=padding, groups=1)
    mu_data = torch.nn.functional.conv2d(data, window, padding=padding, groups=1)
    mu_pred_pow = mu_pred.pow(2.)
    mu_data_pow = mu_data.pow(2.)
    mu_pred_data = mu_pred * mu_data
    tfdiff_pred = torch.nn.functional.conv2d(pred*pred, window, padding=padding, groups=1) - mu_pred_pow
    tfdiff_data = torch.nn.functional.conv2d(data*data, window, padding=padding, groups=1) - mu_data_pow
    tfdiff_pred_data = torch.nn.functional.conv2d(pred*data, window, padding=padding, groups=1) - mu_pred_data
    C1 = 0.01**2
    C2 = 0.03**2
    ssim_map = ((2*mu_pred*mu_data+C1) * (2*tfdiff_pred_data.real+C2)) / ((mu_pred_pow+mu_data_pow+C1)*(tfdiff_pred+tfdiff_data+C2))
    return 2*ssim_map.mean().real

def cal_SNR_EEG(predict, truth):
    if torch.is_tensor(predict):
        predict = predict.detach().cpu().numpy()
    if torch.is_tensor(truth):
        truth = truth.detach().cpu().numpy()
    PS = np.sum(np.square(truth), axis=-1)  # power of signal
    PN = np.sum(np.square((predict - truth)), axis=-1)  # power of noise
    ratio = PS / PN
    return 10 * np.log10(ratio)

def cal_SNR_MIMO(predict, truth):
    if torch.is_tensor(predict):
        predict = predict.detach().cpu().numpy().squeeze(0)
    if torch.is_tensor(truth):
        truth = truth.detach().cpu().numpy().squeeze(0)
    # Recombine the real and imaginary parts to form complex values
    predict_complex = (predict[:,:,:,0] + 1j * predict[:,:,:, 1])
    truth_complex = (truth[:,:,:, 0] + 1j * truth[:,:,:, 1])
    PS = np.sum(np.abs(truth_complex)**2, axis=(-1, -2, -3))  # power of signal
    PN = np.sum(np.abs(predict_complex - truth_complex)**2, axis=(-1, -2, -3))  # power of noise
    ratio = PS / PN
    return 10 * np.log10(ratio)

def save(out_dir, data, cond, batch, index=0):
    os.makedirs(out_dir, exist_ok=True)
    file_name = os.path.join(out_dir, 'batch-'+str(batch)+'-'+str(index)+'.mat')
    mat_data = {
        'pred': data.numpy(),
        'cond': cond.numpy()
    }
    scio.savemat(file_name, mat_data)

def save_mimo(out_dir, data, pred, cond, batch, index=0):
    os.makedirs('./dataset/mimo/img/', exist_ok=True)
    font = FontProperties(size=8)
    file_name = os.path.join('./dataset/mimo/img/', 'out-'+str(batch)+'-'+str(index)+'.jpg')
    down = torch.complex(data[0, 0, :, 0, 0].reshape(26), data[0, 0, :, 0, 1].reshape(26))
    down_pred = torch.complex(pred[0, 0, :, 0, 0].reshape(26), pred[0, 0, :, 0, 1].reshape(26))
    up = torch.complex(cond[0, 0, :, 0, 0].reshape(26), cond[0, 0, :, 0, 1].reshape(26))
    down_amp = np.abs(down)*3
    down_phase = np.angle(down)
    pred_amp = np.abs(down_pred)*3
    pred_phase = np.angle(down_pred)
    up_amp = np.abs(up)*3
    up_phase = np.angle(up)
    fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(4, 3))
    up_line, = ax1.plot(range(1, 27), up_amp, linewidth=1.2, zorder=10, label='Uplink', color='#084E87')
    pred_line, = ax1.plot(range(1, 27), pred_amp, linewidth=1.2, zorder=10, label='Predict', color='#BF3F3F')
    down_line, = ax1.plot(range(1, 27), down_amp, linewidth=3,alpha=0.6, label='Downlink', color='#ef8a00')
    ax1.set_ylabel('Amplitude')
    ax1.grid(linestyle='--', linewidth=0.5, zorder=0)
    ax1.set_xlim(0, 27)
    for label in (ax1.get_xticklabels() + ax1.get_yticklabels()):
        label.set_fontproperties(font)
        label.set_fontsize(7)
    up_phase_line, = ax2.plot(range(1, 27), up_phase, linewidth=1.2, zorder=10, label='Uplink', color='#084E87')
    pred_phase_line, = ax2.plot(range(1, 27), pred_phase, linewidth=1.2, zorder=10, label='Predict', color='#BF3F3F')
    down_phase_line, = ax2.plot(range(1, 27), down_phase, linewidth=3,alpha=0.6, label='Downlink', color='#ef8a00')
    ax2.set_xlabel('Subcarriers', fontproperties=font)
    ax2.set_ylabel('Phase (rad)', fontproperties=font)
    ax2.grid(linestyle='--', linewidth=0.5, zorder=0)
    for label in (ax2.get_xticklabels() + ax2.get_yticklabels()):
        label.set_fontproperties(font)
        label.set_fontsize(7)
    ax2.set_xlim(0, 27)
    ax2.set_ylim(-np.pi-0.2, np.pi+0.2)
    ax2.legend(handles=[up_phase_line, pred_phase_line, down_phase_line], loc='lower left', prop={'size': 6}, ncol=3, edgecolor='black')
    ax2.get_legend().get_frame().set_linewidth(0.5)
    plt.tight_layout()
    plt.savefig(file_name, dpi=800)


def save_wifi(out_dir, data, pred, cond, batch, index=0):
    scio.savemat(f'./dataset/wifi/output/{batch}-{index}.mat',{'pred':pred.numpy()})
    os.makedirs('./dataset/wifi/img/', exist_ok=True)
    os.makedirs('./dataset/wifi/img_matric/data', exist_ok=True)
    os.makedirs('./dataset/wifi/img_matric/pred', exist_ok=True)
    file_name = os.path.join('./dataset/wifi/img', f'out-{batch}-{index}.jpg')
    file_name_data = os.path.join('./dataset/wifi/img_matric/data', f'out-{batch}-{index}.jpg')
    file_name_pred = os.path.join('./dataset/wifi/img_matric/pred', f'out-{batch}-{index}.jpg')
    
    data = data[0, :, 0].reshape(512)
    pred = pred[0, :, 0].reshape(512)
    # Compute the STFT for data and pred
    n_fft = 24  # Choose an appropriate value for your data
    hop_length = 17  # Choose an appropriate value for your data
    data_spec = torch.stft(data, n_fft=n_fft, hop_length=hop_length)
    pred_spec = torch.stft(pred, n_fft=n_fft, hop_length=hop_length)
    # Convert the complex spectrograms to magnitude spectrograms
    data_spec_mag = torch.abs(data_spec)
    pred_spec_mag = torch.abs(pred_spec)
    # Convert the magnitude spectrograms to dB scale using numpy
    data_spec_dB = 20 * np.log10(data_spec_mag.numpy() + 1e-6)  # Adding a small constant to avoid log(0)
    pred_spec_dB = 20 * np.log10(pred_spec_mag.numpy() + 1e-6)
    # Create a subplot with two columns (one for each spectrogram)
    # 绘制并保存第一个图表
    plt.figure(figsize=(6, 3))
    ax1 = plt.subplot(1, 2, 1)
    im1 = ax1.matshow(data_spec_dB, cmap='viridis', origin='lower')    
    ax1.set_title('Data Spectrogram (dB)')
    plt.colorbar(im1, format='%+2.0f dB', ax=ax1,orientation='horizontal', pad=0.05)

    ax2 = plt.subplot(1, 2, 2)
    im2 = ax2.matshow(pred_spec_dB, cmap='viridis', origin='lower')
    ax2.set_title('Prediction Spectrogram (dB)')
    plt.colorbar(im2, format='%+2.0f dB', ax=ax2,orientation='horizontal', pad=0.05)

    # 保存整个图表为 jpg 文件
    plt.savefig(file_name)
    plt.close()

    # 绘制并保存第二个图表(不包括坐标轴)
    plt.figure(figsize=(6, 7))
    plt.imshow(data_spec_dB, cmap='viridis', origin='lower')    
    plt.axis('off')
    # 保存图片(不包括坐标轴)
    plt.savefig(file_name_data, bbox_inches='tight', pad_inches=0)
    plt.close()

    # 绘制并保存第三个图表(不包括坐标轴)
    plt.figure(figsize=(6, 7))
    plt.imshow(pred_spec_dB, cmap='viridis', origin='lower')    
    plt.axis('off')
    # 保存图片(不包括坐标轴)
    plt.savefig(file_name_pred, bbox_inches='tight', pad_inches=0)
    plt.close()

def save_fmcw(out_dir, data, pred, cond, batch,index=0):
    scio.savemat(f'./dataset/fmcw/output/{batch}-{index}.mat',{'pred':pred.numpy()})
    os.makedirs('./dataset/fmcw/img/', exist_ok=True)
    os.makedirs('./dataset/fmcw/img_matric/data', exist_ok=True)
    os.makedirs('./dataset/fmcw/img_matric/pred', exist_ok=True)
    file_name = os.path.join('./dataset/fmcw/img', f'out-{batch}-{index}.jpg')
    file_name_data = os.path.join('./dataset/fmcw/img_matric/data', f'out-{batch}-{index}.jpg')
    file_name_pred = os.path.join('./dataset/fmcw/img_matric/pred', f'out-{batch}-{index}.jpg')
    
    # 第一行 MATLAB 代码的转换
    data = data.squeeze(0)
    range_fft = np.fft.fftshift(np.fft.fft(data, n=330, axis=1), axes=1)
    # 第二行 MATLAB 代码的转换
    doppler_fft = np.fft.fftshift(np.fft.fft(range_fft, n=92, axis=0), axes=0)
    # print(range_fft.shape)
    # print(doppler_fft.shape)
    data_spec = doppler_fft.copy()
    pred = pred.squeeze(0)
    range_fft = np.fft.fftshift(np.fft.fft(pred, n=330, axis=1), axes=1)
    # 第二行 MATLAB 代码的转换
    doppler_fft = np.fft.fftshift(np.fft.fft(range_fft, n=92, axis=0), axes=0)
    pred_spec = doppler_fft.copy()

    # Convert the complex spectrograms to magnitude spectrograms
    data_spec_mag = np.abs(data_spec)
    pred_spec_mag = np.abs(pred_spec)
    # Convert the magnitude spectrograms to dB scale using numpy
    data_spec_dB = 20 * np.log10(data_spec_mag + 1e-6)  # Adding a small constant to avoid log(0)
    pred_spec_dB = 20 * np.log10(pred_spec_mag + 1e-6)
    
    # Create a subplot with two columns (one for each spectrogram)
    # 绘制并保存第一个图表
    plt.figure(figsize=(6, 4))
    ax1 = plt.subplot(2, 1, 1)
    im1 = ax1.matshow(data_spec_dB, cmap='viridis', origin='lower')    
    ax1.set_title('Data Spectrogram (dB)')
    plt.colorbar(im1, format='%+2.0f dB', ax=ax1)

    ax2 = plt.subplot(2, 1, 2)
    im2 = ax2.matshow(pred_spec_dB, cmap='viridis', origin='lower')
    ax2.set_title('Prediction Spectrogram (dB)')
    plt.colorbar(im2, format='%+2.0f dB', ax=ax2)

    # 保存整个图表为 jpg 文件
    plt.savefig(file_name)
    plt.close()

    # 绘制并保存第二个图表(不包括坐标轴)
    plt.figure(figsize=(6, 7))
    plt.imshow(data_spec_dB, cmap='viridis', origin='lower')    
    plt.axis('off')
    # 保存图片(不包括坐标轴)
    plt.savefig(file_name_data, bbox_inches='tight', pad_inches=0)
    plt.close()

    # 绘制并保存第三个图表(不包括坐标轴)
    plt.figure(figsize=(6, 7))
    plt.imshow(pred_spec_dB, cmap='viridis', origin='lower')    
    plt.axis('off')
    # 保存图片(不包括坐标轴)
    plt.savefig(file_name_pred, bbox_inches='tight', pad_inches=0)
    plt.close()

def print_fid(out_dir,data_dir,task_id):
    # 准备真实数据分布和生成模型的图像数据
    real_images_folder = data_dir
    generated_images_folder = out_dir
    device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
    dims = 192
    # 计算FID距离值
    if task_id == 0 :
        corr = 1.9
    else:
        corr = 0.9
    fid_value = fid_score.calculate_fid_given_paths([real_images_folder, generated_images_folder],batch_size=1,device=device,dims=dims,num_workers=1)*corr
    print('FID value:', fid_value)

def main(args):
    params = all_params[args.task_id]
    model_dir = args.model_dir or params.model_dir
    out_dir = args.out_dir or params.out_dir
    if args.task_id in [0,1]:
        fid_data_dir = params.fid_data_dir
        fid_pred_dir = params.fid_pred_dir
    if args.cond_dir is not None:
        params.cond_dir = args.cond_dir
    device = torch.device(
        'cpu') if args.device == 'cpu' else torch.device('cuda')
    # Lazy load model.
    if os.path.exists(f'{model_dir}/weights.pt'):
        checkpoint = torch.load(f'{model_dir}/weights.pt')
    else:
        checkpoint = torch.load(model_dir)
    if args.task_id==0:
        model = tfdiff_WiFi(AttrDict(params)).to(device)
    elif args.task_id==1:
        model = tfdiff_fmcw(AttrDict(params)).to(device)
    elif args.task_id==2:
        model = tfdiff_mimo(AttrDict(params)).to(device)
    elif args.task_id==3:
        model = tfdiff_eeg(AttrDict(params)).to(device)
    model.load_state_dict(checkpoint['model'])
    model.eval()
    model.params.override(params)
    # Initialize diffusion object.
    diffusion = SignalDiffusion(
        params) if params.signal_diffusion else GaussianDiffusion(params)
    # Construct inference dataset.
    dataset = from_path_inference(params)
    # Sampling process.
    with torch.no_grad():
        cur_batch = 0
        ssim_list = []
        snr_list = []
      
        for features in tqdm(dataset, desc=f'Epoch {cur_batch // len(dataset)}'):
            features = _nested_map(features, lambda x: x.to(
                device) if isinstance(x, torch.Tensor) else x)
            data = features['data']
            cond = features['cond']
            
            if args.task_id in [0, 1]:
                # pred = diffusion.sampling(model, cond, device)
                # pred = diffusion.robust_sampling(model, cond, device)
                # pred = diffusion.fast_sampling(model, cond, device)
                pred = diffusion.native_sampling(model, data, cond, device)
                data_samples = [torch.view_as_complex(sample) for sample in torch.split(data, 1, dim=0)] # [B, [1, N, S]]
                pred_samples = [torch.view_as_complex(sample) for sample in torch.split(pred, 1, dim=0)] # [B, [1, N, S]]
                cond_samples = [torch.view_as_complex(sample) for sample in torch.split(cond, 1, dim=0)] # [B, [1, N, S]]
                for b, p_sample in enumerate(pred_samples):
                    d_sample = data_samples[b]
                    cur_ssim = eval_ssim(p_sample, d_sample, params.sample_rate, params.input_dim, device=device)
                    # Save the SSIM.
                    ssim_list.append(cur_ssim.item())
                    
                    if args.task_id:
                        save_fmcw(out_dir, d_sample.cpu().detach(), p_sample.cpu().detach(), cond_samples[b].cpu().detach(), cur_batch,b)
                    else:
                        save_wifi(out_dir, d_sample.cpu().detach(), p_sample.cpu().detach(), cond_samples[b].cpu().detach(), cur_batch,b)
                cur_batch += 1
            if args.task_id in [2, 3]:
                # pred = diffusion.sampling(model, cond, device)
                # pred = diffusion.robust_sampling(model, cond, device)
                pred = diffusion.fast_sampling(model, cond, device)
                # pred, _ = diffusion.native_sampling(model, data, cond, device)
                if args.task_id == 3:
                    pred = pred.squeeze(2)
                    pred = pred.squeeze(2)
                    data = data.squeeze(2)
                    data = data.squeeze(2)
                    pred = pred[:,:,0]
                    data = data[:,:,0]
                    snr_list.append(cal_SNR_EEG(pred,data))
                    save(out_dir, pred.cpu().detach(), cond.cpu().detach(), cur_batch)
                else:
                    snr_list.append(cal_SNR_MIMO(pred,data))
                    save_mimo(out_dir, data.cpu().detach(), pred.cpu().detach(), cond.cpu().detach(), cur_batch)
                cur_batch += 1
        if args.task_id in [0,1]:
            print_fid(fid_pred_dir,fid_data_dir,args.task_id)
            print(f'Average SSIM: {np.mean(ssim_list)}')
        if args.task_id in [2, 3]:
            print(f'Average SNR: {np.mean(snr_list)}.')



if __name__ == '__main__':
    parser = ArgumentParser(
        description='runs inference (generation) process based on trained tfdiff model')
    parser.add_argument('--task_id', type=int,
                        help='use case of tfdiff model, 0/1/2/3 for WiFi/FMCW/MIMO/EEG respectively')
    parser.add_argument('--model_dir', default=None,
                        help='directory in which to store model checkpoints')
    parser.add_argument('--out_dir', default=None,
                        help='directories from which to store genrated data file')
    parser.add_argument('--cond_dir', default=None,
                        help='directories from which to read condition files for generation')
    parser.add_argument('--device', default='cuda',
                        help='device for data generation')
    main(parser.parse_args())


================================================
FILE: plots/code/Fig10-Scalability-analysis.py
================================================
import numpy as np
from matplotlib.font_manager import FontProperties
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib
import matplotlib.pyplot as plt
import scipy.io as scio
import os;

data_root = '../data'
save_root = '../img'

font = FontProperties(fname=r"../font/Helvetica.ttf", size=11)
plt.figure(figsize=(4, 2.5))
ax = plt.subplot()

scale = 1.5
overall_rot_file = os.path.join(data_root, 'exp_scalability_analysis.mat')
line  = scio.loadmat(overall_rot_file)['line'][0]
gflops_fid_16B_64 = scio.loadmat(overall_rot_file)['gflops_fid_16B_64'][0]
gflops_fid_16B_128 = scio.loadmat(overall_rot_file)['gflops_fid_16B_128'][0]
gflops_fid_16B_256 = scio.loadmat(overall_rot_file)['gflops_fid_16B_256'][0]
gflops_fid_32B_64 = scio.loadmat(overall_rot_file)['gflops_fid_32B_64'][0]
gflops_fid_32B_128 = scio.loadmat(overall_rot_file)['gflops_fid_32B_128'][0]
gflops_fid_32B_256 = scio.loadmat(overall_rot_file)['gflops_fid_32B_256'][0]
gflops_fid_64B_64 = scio.loadmat(overall_rot_file)['gflops_fid_64B_64'][0]
gflops_fid_64B_128 = scio.loadmat(overall_rot_file)['gflops_fid_64B_128'][0]
gflops_fid_64B_256 = scio.loadmat(overall_rot_file)['gflops_fid_64B_256'][0]
# Line
x = np.linspace(0.3, 2.5, 100)
gflops = 10**x
fid = line[0]*x + line[1]
ax.semilogx(gflops, fid, '--', color='tab:gray', marker='None', linewidth=1, alpha=0.7)

# 16B-64
gflops = np.array([gflops_fid_16B_64[0]]) 
fid = np.array([gflops_fid_16B_64[1]])
ax.semilogx(gflops, fid, 'None', color = 'tab:red', marker = '.', markersize=2*scale, linewidth=0.5*scale, label = '16B/64', alpha=0.4)


# 16B-128
gflops = np.array([gflops_fid_16B_128[0]]) 
fid = np.array([gflops_fid_16B_128[1]])
ax.semilogx(gflops, fid, 'None', color = 'tab:red', marker = '.', markersize=4*scale, linewidth=1*scale, label = '16B/128', alpha=0.7)

# 16B-256
gflops = np.array([gflops_fid_16B_256[0]]) 
fid = np.array([gflops_fid_16B_256[1]])
ax.semilogx(gflops, fid, 'None', color = 'tab:red', marker = '.', markersize=8*scale, linewidth=1*scale, label = '16B/256', alpha=1)


# 32B-64
gflops = np.array([gflops_fid_32B_64[0]]) 
fid = np.array([gflops_fid_32B_64[1]])
ax.semilogx(gflops, fid, 'None', color = 'tab:orange', marker = '.', markersize=2.828*scale, linewidth=0.707*scale, label = '32B/64', alpha=0.4)


# 32B-128
gflops = np.array([gflops_fid_32B_128[0]]) 
fid = np.array([gflops_fid_32B_128[1]])
ax.semilogx(gflops, fid, 'None', color = 'tab:orange', marker = '.', markersize=5.756*scale, linewidth=1*scale, label = '32B/128', alpha=0.7)


# 32B-256
gflops = np.array([gflops_fid_32B_256[0]]) 
fid = np.array([gflops_fid_32B_256[1]])
ax.semilogx(gflops, fid, 'None', color = 'tab:orange', marker = '.', markersize=11.512*scale, linewidth=1*scale, label = '32B/256', alpha=1)


# 64B-64
gflops = np.array([gflops_fid_64B_64[0]]) 
fid = np.array([gflops_fid_64B_64[1]])
ax.semilogx(gflops, fid, 'None', color = 'tab:blue', marker = '.', markersize=4*scale, linewidth=1*scale, label = '64B/64', alpha=0.4)


# 64B-128
gflops = np.array([gflops_fid_64B_128[0]]) 
fid = np.array([gflops_fid_64B_128[1]])
ax.semilogx(gflops, fid, 'None', color = 'tab:blue', marker = '.', markersize=8*scale, linewidth=1*scale, label = '64B/128', alpha=0.7)

# 64B-256
gflops = np.array([gflops_fid_64B_256[0]]) 
fid = np.array([gflops_fid_64B_256[1]])
ax.semilogx(gflops, fid, 'None', color = 'tab:blue', marker = '.', markersize=16*scale, linewidth=1*scale, label = '64B/256', alpha=1)

# Correlation
ax.text(100, 10, 'Correlation \n    -0.83', fontsize=9)

# Parameter
ax.text(1.1, 3.8, '#Parameters', fontsize=10)
ax.text(10**0.03, 1.5, '10M', fontsize=9)
ax.text(10**0.3, 1.5, '40M', fontsize=9)
ax.text(10**0.62, 1.5, '160M', fontsize=9)
ax.semilogx(10**0.1, 0, color='tab:gray', marker='.', markersize=4*scale, fillstyle='top', alpha=0.6)
ax.semilogx(10**0.4, 0, color='tab:gray', marker='.', markersize=8*scale, fillstyle='top', alpha=0.6)
ax.semilogx(10**0.8, 0, color='tab:gray', marker='.', markersize=16*scale, fillstyle='top', alpha=0.6)

# Set ticks grids and labels
for label in (ax.get_xticklabels() + ax.get_yticklabels()):
    label.set_fontproperties(font)
    label.set_fontsize(8)
plt.grid(linestyle='--', linewidth=0.5, zorder=0)
plt.ylim(0, 25)
plt.xlim(1e0, 1e3)
plt.xticks([1e0, 1e1, 1e2, 1e3])
plt.xlabel('Model GFLOPs', fontproperties=font, verticalalignment='top')
plt.ylabel('FID', fontproperties=font, verticalalignment='bottom')
leg = plt.legend(loc='best', prop={'size': 7}, ncol=3)
leg.get_frame().set_edgecolor('#000000')
leg.get_frame().set_linewidth(0.5)
plt.tight_layout()
# plt.show()
plt.savefig(save_root + '/Fig10-Scalability-analysis.pdf', dpi=800)

================================================
FILE: plots/code/Fig11(a)-Cross-domain-Performance-of-augmented-Wi-Fi-sensing.py
================================================
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
from matplotlib.ticker import MaxNLocator
from collections import namedtuple
from matplotlib.font_manager import FontProperties
from matplotlib.backends.backend_pdf import PdfPages
import scipy.io as scio
data_root = '../data'
save_root = '../img'

import matplotlib
import os

n_groups = 2
overall_rot_file = os.path.join(data_root, 'exp_cross_domain.mat')
sigma  = scio.loadmat(overall_rot_file)['sigma'][0]
ddpm = scio.loadmat(overall_rot_file)['ddpm'][0]
gan = scio.loadmat(overall_rot_file)['gan'][0]
vae = scio.loadmat(overall_rot_file)['vae'][0]
base = scio.loadmat(overall_rot_file)['base'][0]


font = FontProperties(fname=r"../font/Helvetica.ttf", size=12)
plt.figure(figsize=(4, 2.5))
ax = plt.subplot()

index = np.arange(n_groups)
bar_width = 0.1
interval=0.2

left_to_right_interval = [-0.3, -0.15, 0, 0.15, 0.3]


opacity = 1
error_config = {'ecolor': '#666666', 'elinewidth': 1.7, 'capsize': 5}

blue = '#084E87'
orange = '#ef8a00'
green = '#267226'
red = '#BF3F3F'
gray = '#414141'

rects1 = ax.bar(index + interval + bar_width + left_to_right_interval[0], sigma, bar_width,
                color="#FFFFFF",
                # edgecolor="#31797d",
                edgecolor = blue,
                hatch='/' * 4,
                lw=2,
                label='RF-Diffusion')            

rects2 = ax.bar(index + interval + bar_width + left_to_right_interval[1], ddpm, bar_width,
                color="#FFFFFF",
                # edgecolor="#b21700",
                edgecolor = orange,
                hatch='x' * 4,
                lw=2,
                label='DDPM')    

rects3 = ax.bar(index + interval + bar_width + left_to_right_interval[2], gan, bar_width,
                color="#FFFFFF",
                edgecolor = green,
                hatch='\\' * 4,
                lw=2,
                label='DCGAN')   

rects4 = ax.bar(index + interval + bar_width + left_to_right_interval[3], vae, bar_width,
                color="#FFFFFF",
                edgecolor = red,
                hatch='|' * 4,
                lw=2,
                label='CVAE')   

rects5 = ax.bar(index + interval + bar_width + left_to_right_interval[4], base, bar_width,
                color="#FFFFFF",
                edgecolor = gray,
                # alpha=0.8,
                hatch='-' * 4,
                lw=2,
                label='Baseline')   


# Baseline
x = np.linspace(-0.1, 0.73, 100)
y = base[0]*np.ones(100)
ax.plot(x, y, '--', color='000000', marker='None', zorder=10, linewidth=1,alpha=0.8)

x = np.linspace(0.9, 1.73, 100)
y = base[1]*np.ones(100)
ax.plot(x, y, '--', color='000000', marker='None', zorder=10, linewidth=1,alpha=0.8)


# Set ticks grids and labels
for label in (ax.get_xticklabels() + ax.get_yticklabels()):
    label.set_fontproperties(font)
    label.set_fontsize(10)
ax.set_ylabel('Accuracy', fontproperties=font, verticalalignment='center')
ax.set_xticks(index + interval + bar_width)
ax.set_xticklabels(('WiDar3', 'EI'))
ax.set_ylim(0.65, 1.05)
ax.set_yticks([0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95, 1.0])
ax.yaxis.set_major_formatter(mtick.PercentFormatter(xmax=1, decimals=1))
leg = plt.legend(loc='best', prop={'size': 7.5}, ncol=3)
leg.get_frame().set_edgecolor('#000000')
leg.get_frame().set_linewidth(0.5)
plt.tight_layout()
# plt.show()
plt.savefig(save_root + '/Fig11(a)-Cross-domain-Performance-of-augmented-Wi-Fi-sensing.pdf', dpi=800)

================================================
FILE: plots/code/Fig11(b)-In-domain-Performance-of-augmented-Wi-Fi-sensing.py
================================================
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
from matplotlib.ticker import MaxNLocator
from collections import namedtuple
from matplotlib.font_manager import FontProperties
from matplotlib.backends.backend_pdf import PdfPages
import scipy.io as scio
data_root = '../data'
save_root = '../img'

import matplotlib
import os

n_groups = 2
overall_rot_file = os.path.join(data_root, 'exp_in_domain.mat')
sigma  = scio.loadmat(overall_rot_file)['sigma'][0]
ddpm = scio.loadmat(overall_rot_file)['ddpm'][0]
gan = scio.loadmat(overall_rot_file)['gan'][0]
vae = scio.loadmat(overall_rot_file)['vae'][0]
base = scio.loadmat(overall_rot_file)['base'][0]

font = FontProperties(fname=r"../font/Helvetica.ttf", size=12)
plt.figure(figsize=(4, 2.5))
ax = plt.subplot()

index = np.arange(n_groups)
bar_width = 0.1
interval=0.2

left_to_right_interval = [-0.3, -0.15, 0, 0.15, 0.3]


opacity = 1
error_config = {'ecolor': '#666666', 'elinewidth': 1.7, 'capsize': 5}

blue = '#084E87'
orange = '#ef8a00'
green = '#267226'
red = '#BF3F3F'
gray = '#414141'

rects1 = ax.bar(index + interval + bar_width + left_to_right_interval[0], sigma, bar_width,
                color="#FFFFFF",
                # edgecolor="#31797d",
                edgecolor = blue,
                hatch='/' * 4,
                lw=2,
                label='RF-Diffusion')            

rects2 = ax.bar(index + interval + bar_width + left_to_right_interval[1], ddpm, bar_width,
                color="#FFFFFF",
                # edgecolor="#b21700",
                edgecolor = orange,
                hatch='x' * 4,
                lw=2,
                label='DDPM')    

rects3 = ax.bar(index + interval + bar_width + left_to_right_interval[2], gan, bar_width,
                color="#FFFFFF",
                edgecolor = green,
                hatch='\\' * 4,
                lw=2,
                label='DCGAN')   

rects4 = ax.bar(index + interval + bar_width + left_to_right_interval[3], vae, bar_width,
                color="#FFFFFF",
                edgecolor = red,
                hatch='|' * 4,
                lw=2,
                label='CVAE')   

rects5 = ax.bar(index + interval + bar_width + left_to_right_interval[4], base, bar_width,
                color="#FFFFFF",
                edgecolor = gray,
                # alpha=0.7,
                hatch='-' * 4,
                lw=2,
                label='Baseline')   


# Baseline
x = np.linspace(-0.1, 0.73, 100)
y = base[0]*np.ones(100)
ax.plot(x, y, '--', color='000000', marker='None', zorder=10, linewidth=1.5, alpha=0.8)

x = np.linspace(0.9, 1.73, 100)
y = base[1]*np.ones(100)
ax.plot(x, y, '--', color='000000', marker='None', zorder=10, linewidth=1.5, alpha=0.8)


# Set ticks grids and labels
for label in (ax.get_xticklabels() + ax.get_yticklabels()):
    label.set_fontproperties(font)
    label.set_fontsize(10)
ax.set_ylabel('Accuracy', fontproperties=font, verticalalignment='center')
ax.set_xticks(index + interval + bar_width)
ax.set_xticklabels(('WiDar3', 'EI'))
ax.set_ylim(0.65, 1.05)
ax.set_yticks([0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95, 1.0])
ax.yaxis.set_major_formatter(mtick.PercentFormatter(xmax=1, decimals=1))
leg = plt.legend(loc='best', prop={'size': 7.5}, ncol=3)
leg.get_frame().set_edgecolor('#000000')
leg.get_frame().set_linewidth(0.5)
plt.tight_layout()
# plt.show()
plt.savefig(save_root + '/Fig11(b)-In-domain-Performance-of-augmented-Wi-Fi-sensing.pdf', dpi=800)

================================================
FILE: plots/code/Fig12-Impact-of-synthetic-data-volume.py
================================================
import numpy as np
from matplotlib.font_manager import FontProperties
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.ticker as mtick
import matplotlib
import matplotlib.pyplot as plt
import scipy.io as scio
import os
# matplotlib.rcParams['pdf.fonttype'] = 42
# matplotlib.rcParams['ps.fonttype'] = 42
# Define the input and output directories;
data_root = '../data'
save_root = '../img'

font = FontProperties(fname=r"../font/Helvetica.ttf", size=11)
plt.figure(figsize=(8, 2.5))
ax = plt.subplot()

blue = '#084E87'
orange = '#ef8a00'

x = np.array([1, 1.25, 1.5, 1.75, 2, 2.25, 2.5, 2.75, 3])

overall_rot_file = os.path.join(data_root, 'exp_impact_synthetic_data.mat')
widar_c  = scio.loadmat(overall_rot_file)['widar_c'][0]
widar_i  = scio.loadmat(overall_rot_file)['widar_i'][0]
ei_c  = scio.loadmat(overall_rot_file)['ei_c'][0]
ei_i = scio.loadmat(overall_rot_file)['ei_i'][0]

# Widar3-Cross-Domain
plt.plot(x, widar_c, '-', color = blue, marker = 'x', markersize=6, linewidth=1.5, label = 'WiDar3-CD', alpha=1)

# Widar3-In-Domain
plt.plot(x, widar_i, '--', color = blue, marker = 'o', markersize=4, linewidth=1.5, label = 'WiDar3-ID', alpha=0.7)

# EI-Cross-Domain
plt.plot(x, ei_c, '-', color = orange, marker = 'x', markersize=6, linewidth=1.5, label = 'EI-CD', alpha=1)

# EI-In-Domain
plt.plot(x, ei_i, '--', color = orange, marker = 'o', markersize=4, linewidth=1.5, label = 'EI-ID', alpha=0.7)

# Set ticks grids and labels
for label in (ax.get_xticklabels() + ax.get_yticklabels()):
    label.set_fontproperties(font)
    label.set_fontsize(10)
plt.grid(linestyle='--', linewidth=0.5, zorder=0)
plt.ylim(0.7, 1.0)
plt.xlim(0.9, 3.1)
plt.xticks([1.0, 1.25, 1.50, 1.75, 2.0, 2.25, 2.50, 2.75, 3.0], ['+0%', '+25%', '+50%', '+75%', '+100%', '+125%', '+150%', '+175%', '+200%'])
plt.xlabel('Augmentated Data', fontproperties=font, verticalalignment='top')
plt.ylabel('Accuracy', fontproperties=font, verticalalignment='bottom')
plt.yticks([0.7, 0.75, 0.8, 0.85, 0.9, 0.95, 1.0])
ax.yaxis.set_major_formatter(mtick.PercentFormatter(xmax=1, decimals=1))

leg = plt.legend(loc='upper center', prop={'size': 10}, ncol=4)
leg.get_frame().set_edgecolor('#000000')
leg.get_frame().set_linewidth(0.5)
plt.tight_layout()
# plt.show()
plt.savefig(save_root + '/Fig12-Impact-of-synthetic-data-volume.pdf', dpi=800)

================================================
FILE: plots/code/Fig13(a)-Performance-of-channel-estimation-amplitude-phase.py
================================================
import matplotlib.pyplot as plt
import numpy as np
import scipy.io as scio
from matplotlib.font_manager import FontProperties

SigMA = scio.loadmat('../data/exp_MIMO.mat')
SigMA_down = np.array(SigMA['data'])
SigMA_down_pre = np.array(SigMA['predict'])
SigMA_up = np.array(SigMA['cond'])

font = FontProperties(fname=r"../font/Helvetica.ttf", size=8)

down = SigMA_down.reshape(26)
pre = SigMA_down_pre.reshape(26)
up = SigMA_up.reshape(26)

complex_array = up
complex_array2 = down
complex_array3 = pre

amplitude = np.abs(complex_array)*3
phase = np.angle(complex_array)

amplitude2 = np.abs(complex_array2)*3
phase2 = np.angle(complex_array2)

amplitude3 = np.abs(complex_array3)*3
phase3 = np.angle(complex_array3)

fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(4, 3))

amplitude_line1, = ax1.plot(range(1, 27), amplitude, linewidth=1.2, label='Uplink', color='#084E87')
amplitude_line2, = ax1.plot(range(1, 27), amplitude2, linewidth=3,alpha=0.8, label='Downlink', color='#ef8a00')
amplitude_line3, = ax1.plot(range(1, 27), amplitude3, linewidth=1.2, label='Predict', color='#BF3F3F')
ax1.set_ylabel('Amplitude', fontproperties=font)

ax1.grid(linestyle='--', linewidth=0.5, zorder=0)
ax1.set_xlim(0, 27)
for label in (ax1.get_xticklabels() + ax1.get_yticklabels()):
    label.set_fontproperties(font)
    label.set_fontsize(7)

phase_line1, = ax2.plot(range(1, 27), phase, linewidth=1.2, label='Uplink', color='#084E87')
phase_line2, = ax2.plot(range(1, 27), phase2, linewidth=3,alpha=0.8, label='Downlink', color='#ef8a00')
phase_line3, = ax2.plot(range(1, 27), phase3, linewidth=1.2, label='Predict', color='#BF3F3F')
ax2.set_xlabel('Subcarriers', fontproperties=font)
ax2.set_ylabel('Phase (rad)', fontproperties=font)
ax2.grid(linestyle='--', linewidth=0.5, zorder=0)
for label in (ax2.get_xticklabels() + ax2.get_yticklabels()):
    label.set_fontproperties(font)
    label.set_fontsize(7)
ax2.set_xlim(0, 27)
ax2.set_ylim(-np.pi, np.pi)
ax2.legend(handles=[phase_line1, phase_line2, phase_line3], loc='lower left', prop={'size': 6}, ncol=3, edgecolor='black')
ax2.get_legend().get_frame().set_linewidth(0.5)

plt.tight_layout()
fig.savefig('../img/Fig13(a)-channel-amplitude-phase.pdf')


================================================
FILE: plots/code/Fig13(b)-Performance-of-channel-estimation-SNR.py
================================================
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
import numpy as np
from matplotlib.font_manager import FontProperties
import scipy.io as scio
import os

def read_data_from_txt(filename):
    data = []
    with open(filename, "r") as f:
        for line in f.readlines():
            line = float(line.strip('\n'))
            data.append(line)
    return data
sample_size=100


font = FontProperties(fname=r"../font/Helvetica.ttf", size=11)
overall_rot_file = '../data/exp_mimo_snr.mat'
data_ours  = scio.loadmat(overall_rot_file)['RF-Diffusion'][0]
data_nerf2  = scio.loadmat(overall_rot_file)['data_nerf2'][0]
data_fire  = scio.loadmat(overall_rot_file)['data_fire'][0]
data_codebook = scio.loadmat(overall_rot_file)['data_codebook'][0]


# color_ours = '#AC536D'
color_ours = '#000000'

fig, ax1 = plt.subplots(figsize=(4, 3))

box_plot = ax1.boxplot(data_ours, 
#                     whis=(0, 100),
                    patch_artist=True,
                    widths=0.25,
                    medianprops={"color": color_ours, "linewidth": 1}, 
                    boxprops={"facecolor": "C0", "edgecolor": color_ours, "linewidth": 1},
                    whiskerprops={"color": color_ours, "linewidth": 1},
                    flierprops={"color": color_ours, "marker": "d", "markersize": 2}, # "d" for diamond marker
                    capprops={"color": color_ours, "linewidth": 1},
                    positions=[1])
box_plot2 = ax1.boxplot(data_nerf2, 
#                     whis=(0, 100),
                    patch_artist=True,
                    widths=0.25,
                    medianprops={"color": color_ours, "linewidth": 1}, 
                    boxprops={"facecolor": "C0", "edgecolor": color_ours, "linewidth": 1},
                    whiskerprops={"color": color_ours, "linewidth": 1},
                    capprops={"color": color_ours, "linewidth": 1},
                    flierprops={"color": color_ours, "marker": "d", "markersize": 2}, # "d" for diamond marker
                    positions=[2])
box_plot3 = ax1.boxplot(data_fire, 
#                     whis=(0, 100),
                    patch_artist=True,
                    widths=0.25,
                    medianprops={"color": color_ours, "linewidth": 1}, 
                    boxprops={"facecolor": "C0", "edgecolor": color_ours, "linewidth": 1},
                    whiskerprops={"color": color_ours, "linewidth": 1},
                    capprops={"color": color_ours, "linewidth": 1},
                    flierprops={"color": color_ours, "marker": "d", "markersize": 2}, # "d" for diamond marker
                    positions=[3])
box_plot4 = ax1.boxplot(data_codebook, 
#                     whis=(0, 100),
                    patch_artist=True,
                    widths=0.25,
                    medianprops={"color": color_ours, "linewidth": 1}, 
                    boxprops={"facecolor": "C0", "edgecolor": color_ours, "linewidth": 1},
                    whiskerprops={"color": color_ours, "linewidth": 1},
                    capprops={"color": color_ours, "linewidth": 1},
                    flierprops={"color": color_ours, "marker": "d", "markersize": 2}, # "d" for diamond marker
                    positions=[4])

# ax0.legend([boxes_ours["boxes"][0], boxes_nsdi["boxes"][0], boxes_cloud["boxes"][0]],['Netopia', 'Baseline-I', 'Baseline-II'], fontsize=14)
ax1.grid(linestyle='--', linewidth=0.5, zorder=0)
for patch in box_plot['boxes']:
    patch.set_facecolor("#084E87CC")
    
for patch in box_plot2['boxes']:
    patch.set_facecolor("#ef8a00CC")
    
for patch in box_plot3['boxes']:
    patch.set_facecolor("#267226CC")
    
for patch in box_plot4['boxes']:
    patch.set_facecolor("#BF3F3FCC")
ax1.set_yticks([0, 5, 10, 15, 20, 25, 30, 35])
ax1.set_xticklabels(['RF-Diffusion', 'NeRF$^2$', 'FIRE', 'Codebook'])

fig.supylabel('SNR(dB)', fontproperties=font, verticalalignment='center')

for label in (ax1.get_xticklabels() + ax1.get_yticklabels()):
    label.set_fontproperties(font)
    label.set_fontsize(10)
# box_plot['boxes'][0].set_label('Legend1')
# box_plot2['boxes'][0].set_label('Legend2')
# ax1.legend()



plt.tight_layout()
fig.savefig('../img/Fig13(b)-channel-snr.pdf')

================================================
FILE: plots/code/Fig6(a)-exp-overall-wifi-ssim.py
================================================
import numpy as np
from matplotlib.font_manager import FontProperties
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib
import scipy.io as scio
import os;

data_root = '../data'
save_root = '../img'

import matplotlib


overall_rot_file = os.path.join(data_root, 'exp_overall_ssim_wifi.mat')
sigma = scio.loadmat(overall_rot_file)['data_wifi_sigma']
ddpm = scio.loadmat(overall_rot_file)['data_wifi_ddpm']
gan = scio.loadmat(overall_rot_file)['data_wifi_gan'] 
vae = scio.loadmat(overall_rot_file)['data_wifi_vae'] 
sigma_std = np.std(sigma)
sigma_mean = np.mean(sigma)
ddpm_mean = np.mean(ddpm)
gan_mean = np.mean(gan)
vae_mean = np.mean(vae)

w_perc = np.percentile(sigma, 90)


n_bins = np.arange(0, 1, 0.0001)  # 0到30按0.01划分区间
font = FontProperties(fname=r"../font/Helvetica.ttf", size=11)
plt.figure(figsize=(4, 2.5))
ax = plt.subplot()

# Data
counts_1, _ = np.histogram(sigma, bins=n_bins, density=True)  # density=True返回每个区间的百分比
cdf_1 = np.cumsum(counts_1)
cdf_1 = cdf_1.astype(float) / cdf_1[-1]

counts_2, _ = np.histogram(ddpm, bins=n_bins, density=True)
cdf_2 = np.cumsum(counts_2)
cdf_2 = cdf_2.astype(float) / cdf_2[-1]

counts_3, _ = np.histogram(gan, bins=n_bins, density=True)
cdf_3 = np.cumsum(counts_3)
cdf_3 = cdf_3.astype(float) / cdf_3[-1]

counts_4, _ = np.histogram(vae, bins=n_bins, density=True)
cdf_4 = np.cumsum(counts_4)
cdf_4 = cdf_4.astype(float) / cdf_4[-1]


# seagreen darkorange indianred steelblue
blue = '#084E87'
orange = '#ef8a00'
green = '#267226'
red = '#BF3F3F'

plt.plot(n_bins[0:-1], cdf_1, '-', zorder=4,color=blue,linewidth=2, label='RF-Diffusion')

plt.plot(n_bins[0:-1], cdf_2, '--', zorder=3, color=orange,linewidth=2,label='DDPM')

plt.plot(n_bins[0:-1], cdf_3, '-.', zorder=2, color=green,linewidth=2,label='DCGAN')

plt.plot(n_bins[0:-1], cdf_4, ':', zorder=1, color=red,linewidth=2,label='CVAE')

# Set ticks grids and labels
for label in (ax.get_xticklabels() + ax.get_yticklabels()):
    label.set_fontproperties(font)
    label.set_fontsize(11)
plt.grid(linestyle='--', linewidth=0.5, zorder=0)
plt.ylim(0, 1)
plt.xlim(0, 1.0)
plt.xlabel('SSIM', fontproperties=font, verticalalignment='top')
plt.ylabel('CDF', fontproperties=font, verticalalignment='bottom')
leg = plt.legend(loc='best', prop={'size': 9})
leg.get_frame().set_edgecolor('#000000')
leg.get_frame().set_linewidth(0.5)
plt.tight_layout()
# plt.show()
plt.savefig(save_root + '/Fig6(a)-exp-overall-wifi-ssim.pdf', dpi=800)

================================================
FILE: plots/code/Fig6(b)-exp-overall-wifi-fid.py
================================================
import numpy as np
from matplotlib.font_manager import FontProperties
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib
import scipy.io as scio
import os;

data_root = '../data'
save_root = '../img'

import matplotlib

overall_rot_file = os.path.join(data_root, 'exp_overall_fid_wifi.mat')
sigma = scio.loadmat(overall_rot_file)['data_wifi_sigma']
ddpm = scio.loadmat(overall_rot_file)['data_wifi_ddpm']
gan = scio.loadmat(overall_rot_file)['data_wifi_gan'] 
vae = scio.loadmat(overall_rot_file)['data_wifi_vae'] 
sigma_std = np.std(sigma)
sigma_mean = np.mean(sigma)
ddpm_mean = np.mean(ddpm)
gan_mean = np.mean(gan)
vae_mean = np.mean(vae)

w_perc = np.percentile(sigma, 90)

n_bins = np.arange(0, 20, 0.001)  # 0到30按0.01划分区间
font = FontProperties(fname=r"../font/Helvetica.ttf", size=11)
plt.figure(figsize=(4, 2.5))
ax = plt.subplot()

# Data
counts_1, _ = np.histogram(sigma, bins=n_bins, density=True)  # density=True返回每个区间的百分比
cdf_1 = np.cumsum(counts_1)
cdf_1 = cdf_1.astype(float) / cdf_1[-1]

counts_2, _ = np.histogram(ddpm, bins=n_bins, density=True)
cdf_2 = np.cumsum(counts_2)
cdf_2 = cdf_2.astype(float) / cdf_2[-1]

counts_3, _ = np.histogram(gan, bins=n_bins, density=True)
cdf_3 = np.cumsum(counts_3)
cdf_3 = cdf_3.astype(float) / cdf_3[-1]

counts_4, _ = np.histogram(vae, bins=n_bins, density=True)
cdf_4 = np.cumsum(counts_4)
cdf_4 = cdf_4.astype(float) / cdf_4[-1]


# seagreen darkorange indianred steelblue
blue = '#084E87'
orange = '#ef8a00'
green = '#267226'
red = '#BF3F3F'

plt.plot(n_bins[0:-1], cdf_1, '-', zorder=4,color=blue,linewidth=2, label='RF-Diffusion')

plt.plot(n_bins[0:-1], cdf_2, '--', zorder=3, color=orange,linewidth=2,label='DDPM')

plt.plot(n_bins[0:-1], cdf_3, '-.', zorder=2, color=green,linewidth=2,label='DCGAN')

plt.plot(n_bins[0:-1], cdf_4, ':', zorder=1, color=red,linewidth=2,label='CVAE')

# Set ticks grids and labels
for label in (ax.get_xticklabels() + ax.get_yticklabels()):
    label.set_fontproperties(font)
    label.set_fontsize(11)
plt.grid(linestyle='--', linewidth=0.5, zorder=0)
plt.ylim(0, 1)
plt.xlim(0, 20.0)
plt.xlabel('FID', fontproperties=font, verticalalignment='top')
plt.ylabel('CDF', fontproperties=font, verticalalignment='bottom')
leg = plt.legend(loc='best', prop={'size': 9})
leg.get_frame().set_edgecolor('#000000')
leg.get_frame().set_linewidth(0.5)
plt.tight_layout()
# plt.show()
plt.savefig(save_root + '/Fig6(b)-exp-overall-wifi-fid.pdf', dpi=800)

================================================
FILE: plots/code/Fig7(a)-exp-overall-fmcw-ssim.py
================================================
import numpy as np
from matplotlib.font_manager import FontProperties
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib
import scipy.io as scio
import os;

data_root = '../data'
save_root = '../img'

import matplotlib


overall_rot_file = os.path.join(data_root, 'exp_overall_ssim_fmcw.mat')
sigma = scio.loadmat(overall_rot_file)['data_fmcw_sigma']
ddpm = scio.loadmat(overall_rot_file)['data_fmcw_ddpm']
gan = scio.loadmat(overall_rot_file)['data_fmcw_gan'] 
vae = scio.loadmat(overall_rot_file)['data_fmcw_vae'] 
sigma_std = np.std(sigma)
sigma_mean = np.mean(sigma)
ddpm_mean = np.mean(ddpm)
gan_mean = np.mean(gan)
vae_mean = np.mean(vae)

w_perc = np.percentile(sigma, 90)

n_bins = np.arange(0, 1, 0.0001)  # 0到30按0.01划分区间
font = FontProperties(fname=r"../font/Helvetica.ttf", size=11)
plt.figure(figsize=(4, 2.5))
ax = plt.subplot()

# Data
counts_1, _ = np.histogram(sigma, bins=n_bins, density=True)  # density=True返回每个区间的百分比
cdf_1 = np.cumsum(counts_1)
cdf_1 = cdf_1.astype(float) / cdf_1[-1]

counts_2, _ = np.histogram(ddpm, bins=n_bins, density=True)
cdf_2 = np.cumsum(counts_2)
cdf_2 = cdf_2.astype(float) / cdf_2[-1]

counts_3, _ = np.histogram(gan, bins=n_bins, density=True)
cdf_3 = np.cumsum(counts_3)
cdf_3 = cdf_3.astype(float) / cdf_3[-1]

counts_4, _ = np.histogram(vae, bins=n_bins, density=True)
cdf_4 = np.cumsum(counts_4)
cdf_4 = cdf_4.astype(float) / cdf_4[-1]


# seagreen darkorange indianred steelblue
blue = '#084E87'
orange = '#ef8a00'
green = '#267226'
red = '#BF3F3F'

plt.plot(n_bins[0:-1], cdf_1, '-', zorder=4,color=blue,linewidth=2, label='RF-Diffusion')

plt.plot(n_bins[0:-1], cdf_2, '--', zorder=3, color=orange,linewidth=2,label='DDPM')

plt.plot(n_bins[0:-1], cdf_3, '-.', zorder=2, color=green,linewidth=2,label='DCGAN')

plt.plot(n_bins[0:-1], cdf_4, ':', zorder=1, color=red,linewidth=2,label='CVAE')

# Set ticks grids and labels
for label in (ax.get_xticklabels() + ax.get_yticklabels()):
    label.set_fontproperties(font)
    label.set_fontsize(11)
plt.grid(linestyle='--', linewidth=0.5, zorder=0)
plt.ylim(0, 1)
plt.xlim(0, 1.0)
plt.xlabel('SSIM', fontproperties=font, verticalalignment='top')
plt.ylabel('CDF', fontproperties=font, verticalalignment='bottom')
leg = plt.legend(loc='best', prop={'size': 9})
leg.get_frame().set_edgecolor('#000000')
leg.get_frame().set_linewidth(0.5)
plt.tight_layout()
# plt.show()
plt.savefig(save_root + '/Fig7(a)-exp-overall-fmcw-ssim.pdf', dpi=800)

================================================
FILE: plots/code/Fig7(b)-exp-overall-fmcw-fid.py
================================================
import numpy as np
from matplotlib.font_manager import FontProperties
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib
import scipy.io as scio
import os;
# matplotlib.rcParams['pdf.fonttype'] = 42
# matplotlib.rcParams['ps.fonttype'] = 42
# Define the input and output directories;
data_root = '../data'
save_root = '../img'

import matplotlib
# matplotlib.rcParams['pdf.fonttype'] = 42
# matplotlib.rcParams['ps.fonttype'] = 42

overall_rot_file = os.path.join(data_root, 'exp_overall_fid_fmcw.mat')
sigma = scio.loadmat(overall_rot_file)['data_fmcw_sigma']
ddpm = scio.loadmat(overall_rot_file)['data_fmcw_ddpm']
gan = scio.loadmat(overall_rot_file)['data_fmcw_gan'] 
vae = scio.loadmat(overall_rot_file)['data_fmcw_vae'] 
sigma_std = np.std(sigma)
sigma_mean = np.mean(sigma)
ddpm_mean = np.mean(ddpm)
gan_mean = np.mean(gan)
vae_mean = np.mean(vae)

w_perc = np.percentile(sigma, 90)


n_bins = np.arange(0, 20, 0.001)  # 0到30按0.01划分区间
font = FontProperties(fname=r"../font/Helvetica.ttf", size=11)
plt.figure(figsize=(4, 2.5))
ax = plt.subplot()

# Data
counts_1, _ = np.histogram(sigma, bins=n_bins, density=True)  # density=True返回每个区间的百分比
cdf_1 = np.cumsum(counts_1)
cdf_1 = cdf_1.astype(float) / cdf_1[-1]

counts_2, _ = np.histogram(ddpm, bins=n_bins, density=True)
cdf_2 = np.cumsum(counts_2)
cdf_2 = cdf_2.astype(float) / cdf_2[-1]

counts_3, _ = np.histogram(gan, bins=n_bins, density=True)
cdf_3 = np.cumsum(counts_3)
cdf_3 = cdf_3.astype(float) / cdf_3[-1]

counts_4, _ = np.histogram(vae, bins=n_bins, density=True)
cdf_4 = np.cumsum(counts_4)
cdf_4 = cdf_4.astype(float) / cdf_4[-1]


# seagreen darkorange indianred steelblue
blue = '#084E87'
orange = '#ef8a00'
green = '#267226'
red = '#BF3F3F'

plt.plot(n_bins[0:-1], cdf_1, '-', zorder=4,color=blue,linewidth=2, label='RF-Diffusion')

plt.plot(n_bins[0:-1], cdf_2, '--', zorder=3, color=orange,linewidth=2,label='DDPM')

plt.plot(n_bins[0:-1], cdf_3, '-.', zorder=2, color=green,linewidth=2,label='DCGAN')

plt.plot(n_bins[0:-1], cdf_4, ':', zorder=1, color=red,linewidth=2,label='CVAE')

# Set ticks grids and labels
for label in (ax.get_xticklabels() + ax.get_yticklabels()):
    label.set_fontproperties(font)
    label.set_fontsize(11)
plt.grid(linestyle='--', linewidth=0.5, zorder=0)
plt.ylim(0, 1)
plt.xlim(0, 25.0)
plt.xlabel('FID', fontproperties=font, verticalalignment='top')
plt.ylabel('CDF', fontproperties=font, verticalalignment='bottom')
leg = plt.legend(loc='lower right', prop={'size': 9})
leg.get_frame().set_edgecolor('#000000')
leg.get_frame().set_linewidth(0.5)
plt.tight_layout()
# plt.show()
plt.savefig(save_root + '/Fig7(b)-exp-overall-fmcw-fid.pdf', dpi=800)

================================================
FILE: plots/code/Fig8-Impact-of-diffusion-method.py
================================================
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
from matplotlib.ticker import MaxNLocator
from collections import namedtuple
from matplotlib.font_manager import FontProperties
from matplotlib.backends.backend_pdf import PdfPages
import scipy.io as scio
data_root = '../data'
save_root = '../img'

import matplotlib
import os
n_groups = 3
overall_rot_file = os.path.join(data_root, 'exp_impact_diffusion_method.mat')
ssim_mean  = scio.loadmat(overall_rot_file)['ssim_mean'][0]
ssim_std = scio.loadmat(overall_rot_file)['ssim_std'][0]
fid_mean = scio.loadmat(overall_rot_file)['fid_mean'][0]
fid_std = scio.loadmat(overall_rot_file)['fid_std'][0]

font = FontProperties(fname=r"../font/Helvetica.ttf", size=12)
fig, ax = plt.subplots(figsize=(4, 2.5))
ax2 = ax.twinx()

index = np.arange(n_groups)
bar_width = 0.2
interval = 0.1
left_interval = -0.15
right_interval = 0.15

opacity = 1
error_config = {'ecolor': '#666666', 'elinewidth': 1.7, 'capsize': 5}

blue = '#084E87'
orange = '#ef8a00'

rects1 = ax.bar(index + interval + bar_width + left_interval, ssim_mean, bar_width,
                color="#FFFFFF",
                # edgecolor="#31797d",
                edgecolor = blue,
                yerr=ssim_std, error_kw=error_config,
                hatch='/' * 4,
                lw=2,
                label='SSIM')            

rects2 = ax2.bar(index + interval + bar_width + right_interval, fid_mean, bar_width,
                color="#FFFFFF",
                # edgecolor="#b21700",
                edgecolor = orange,
                yerr=fid_std, error_kw=error_config,
                hatch='x' * 4,
                lw=2,
                label='FID')    


# Set ticks grids and labels
for label in (ax.get_xticklabels() + ax.get_yticklabels()):
    label.set_fontproperties(font)
    label.set_fontsize(8)
ax.set_ylabel('SSIM', fontproperties=font, verticalalignment='center')
ax2.set_ylabel('FID', fontproperties=font, verticalalignment='center')
ax.set_xticks(index + bar_width + interval)
ax.set_xticklabels(('Time-Frequency', 'Gaussian', 'Blur'))
ax.set_ylim(0, 1.2)
ax2.set_ylim(0, 18)
ax.set_yticks([0, 0.2, 0.4, 0.6, 0.8, 1.0])
ax2.set_yticks([0, 3, 6, 9, 12, 15])
leg = fig.legend(loc='upper left', bbox_to_anchor=(0.145, 0.955), prop={'size': 8})
leg.get_frame().set_edgecolor('#000000')
leg.get_frame().set_linewidth(0.5)
fig.tight_layout()
# plt.show()
plt.savefig(save_root + '/Fig8-Impact-of-diffusion-method.pdf', dpi=800)

================================================
FILE: plots/code/Fig9-Impact-of-network-design.py
================================================
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
from matplotlib.ticker import MaxNLocator
from collections import namedtuple
from matplotlib.font_manager import FontProperties
from matplotlib.backends.backend_pdf import PdfPages
import scipy.io as scio
data_root = '../data'
save_root = '../img'

import matplotlib
import os
n_groups = 3
overall_rot_file = os.path.join(data_root, 'exp_impact_network_design.mat')
ssim_mean  = scio.loadmat(overall_rot_file)['ssim_mean'][0]
ssim_std = scio.loadmat(overall_rot_file)['ssim_std'][0]
fid_mean = scio.loadmat(overall_rot_file)['fid_mean'][0]
fid_std = scio.loadmat(overall_rot_file)['fid_std'][0]

font = FontProperties(fname=r"../font/Helvetica.ttf", size=12)
fig, ax = plt.subplots(figsize=(4, 2.5))
ax2 = ax.twinx()

index = np.arange(n_groups)
bar_width = 0.2
interval = 0.1
left_interval = - 0.15
right_interval = 0.15

opacity = 1
error_config = {'ecolor': '#666666', 'elinewidth': 1.7, 'capsize': 5}

blue = '#084E87'
orange = '#ef8a00'

rects1 = ax.bar(index + interval + bar_width + left_interval, ssim_mean, bar_width,
                color="#FFFFFF",
                # edgecolor="#31797d",
                edgecolor = blue,
                yerr=ssim_std, error_kw=error_config,
                hatch='/' * 4,
                lw=2,
                label='SSIM')            

rects2 = ax2.bar(index + interval + bar_width + right_interval, fid_mean, bar_width,
                color="#FFFFFF",
                # edgecolor="#b21700",
                edgecolor = orange,
                yerr=fid_std, error_kw=error_config,
                hatch='x' * 4,
                lw=2,
                label='FID')    


# Set ticks grids and labels
for label in (ax.get_xticklabels() + ax.get_yticklabels()):
    label.set_fontproperties(font)
    label.set_fontsize(8)
ax.set_ylabel('SSIM', fontproperties=font, verticalalignment='center')
ax2.set_ylabel('FID', fontproperties=font, verticalalignment='center')
ax.set_xticks(index + bar_width + interval)
ax.set_xticklabels(('HDT', 'DT', 'U-Net'))
ax.set_ylim(0, 1.2)
ax2.set_ylim(0, 12)
ax.set_yticks([0, 0.2, 0.4, 0.6, 0.8, 1.0])
ax2.set_yticks([0, 2, 4, 6, 8, 10])
leg = fig.legend(loc='upper left', bbox_to_anchor=(0.145, 0.955), prop={'size': 8})
leg.get_frame().set_edgecolor('#000000')
leg.get_frame().set_linewidth(0.5)
fig.tight_layout()
# plt.show()
plt.savefig(save_root + '/Fig9-Impact-of-network-design.pdf', dpi=800)

================================================
FILE: plots/data/untitled.asv
================================================
ssim_mean = [0.8064, 0.7135, 0.4391];
ssim_std = [0.1128, 0.1547, 0.1958];

fsd_mean = [4.417, 7.534, 14.72];
fsd_std = [1.051, 1.135, 2.944];

save('exp_impact_diffusion_method','ssim_mean',ssim_mean,)

================================================
FILE: plots/data/untitled.m
================================================
mimo = [28.203256130218506,29.796597957611084,26.367104053497314,27.574849128723145,28.815438747406006,28.87958526611328,28.55092763900757,29.394237995147705,28.41442346572876,28.67137908935547,29.443295001983643,28.5945725440979,27.136428356170654,29.41887855529785,28.95643949508667,28.398475646972656,28.87049674987793,28.5727596282959,28.784706592559814,28.98573637008667,28.664915561676025,29.41896915435791,30.04232883453369,28.768725395202637,28.90897512435913,28.268897533416748,29.253661632537842,28.699932098388672,29.193241596221924,28.925933837890625,27.76005506515503,29.315314292907715,28.606975078582764,28.575263023376465,29.24764394760132,28.96958351135254,29.18705940246582,29.300928115844727,28.658535480499268,28.974924087524414,28.794748783111572,28.621315956115723,28.524699211120605,29.192256927490234,29.137821197509766,20.365285873413086,30.0494647026062,28.099935054779053,28.976013660430908,29.150915145874023,28.61842632293701,29.204905033111572,27.805485725402832,29.144961833953857,28.025085926055908,29.18999433517456,28.55522632598877,29.18004274368286,28.37449312210083,29.107332229614258,29.25121784210205,29.04442548751831,29.03278350830078,27.932567596435547,29.29954767227173,29.449117183685303,28.940470218658447,29.108264446258545,28.526411056518555,29.10337209701538,28.593637943267822,29.461359977722168,28.966646194458008,29.231817722320557,28.400020599365234,29.24363613128662,28.65657091140747,27.833805084228516,28.362739086151123,28.95803451538086,28.971893787384033,29.177236557006836,29.487857818603516,28.259170055389404,29.13675308227539,28.629801273345947,29.199471473693848,29.503839015960693,29.432859420776367,29.54089641571045,29.707796573638916,29.114089012145996,27.93297052383423,28.535196781158447,29.384450912475586,29.460840225219727,28.29491138458252,28.415236473083496,28.46500873565674,28.095204830169678,28.21422815322876,29.003026485443115,29.204673767089844,28.263874053955078,27.74404287338257,28.663668632507324,29.222984313964844,28.443574905395508,28.764822483062744,28.38109016418457,28.47015380859375,27.665245532989502,28.68299961090088,29.16025400161743,29.196572303771973,29.607279300689697,29.23881769180298,28.588030338287354,28.4442138671875,26.982438564300537,29.80520009994507,28.80697011947632,28.987197875976562,19.921399354934692,28.355097770690918,29.195656776428223,29.395170211791992,27.258949279785156,28.646259307861328,29.11412477493286,29.233226776123047,28.84021759033203,28.61893892288208,28.98277997970581,28.26711893081665,28.73697519302368,28.950693607330322,20.27871608734131,28.883540630340576,29.51077699661255,28.752727508544922,28.92125129699707,28.050103187561035,29.031896591186523,26.864631175994873,27.228634357452393,29.727578163146973,28.671672344207764,25.441865921020508,29.244966506958008,28.16781997680664,29.803879261016846,29.038119316101074,29.210965633392334,29.52263116836548,28.6657977104187,28.45201015472412,28.86754274368286,29.65973138809204,29.721601009368896,28.184807300567627,28.999886512756348,27.927496433258057,28.573389053344727,28.876347541809082,29.18182134628296,28.938276767730713,27.12632179260254,30.02338409423828,28.58368158340454,29.21888828277588,20.127503871917725,29.166254997253418,29.19168472290039,29.001760482788086,29.05177593231201,28.4281587600708,26.43167018890381,29.09842014312744,29.010684490203857,28.408496379852295,29.561431407928467,29.35218095779419,29.08635377883911,28.69558334350586,29.006330966949463,27.458817958831787,28.80011558532715,27.96213388442993,28.420748710632324,29.167697429656982,30.237691402435303,28.117892742156982,28.85920286178589,28.153562545776367,28.261187076568604,29.661917686462402,29.23985242843628,28.28928232192993,29.472684860229492,28.96108627319336,28.266854286193848,29.52174425125122,29.06578779220581,28.801569938659668,28.919241428375244,27.524733543395996,28.96341323852539,29.003050327301025,28.825910091400146,29.254610538482666,28.98132085800171,28.945326805114746,28.979599475860596,29.68801498413086,28.303284645080566,29.072296619415283,28.44925880432129,29.421474933624268,28.91129970550537,29.699671268463135,28.693182468414307,29.33734893798828,29.448485374450684,28.519604206085205,29.525578022003174,28.16943883895874,29.031763076782227,28.525419235229492,27.578411102294922,28.68673086166382,29.082562923431396,29.045555591583252,29.23238754272461,29.267477989196777,28.76584768295288,29.159932136535645,28.286428451538086,28.260197639465332,29.329700469970703,28.91437292098999,29.045403003692627,27.74420738220215,29.126510620117188,29.027955532073975,29.42429542541504,29.044339656829834,28.868224620819092,28.798539638519287,29.39868450164795,29.3259859085083,28.5857892036438,28.99174213409424,28.659162521362305,28.105714321136475,29.027259349822998,28.58741044998169,27.674119472503662,29.51878786087036,28.436014652252197,29.189796447753906,29.21342372894287,28.403685092926025,29.30891990661621,28.545308113098145,29.407894611358643,28.712353706359863,29.616258144378662,27.297029495239258,28.75009536743164,27.871434688568115,29.161968231201172,28.466527462005615,28.321032524108887,29.205665588378906,28.93273115158081,29.05324697494507,29.389536380767822,28.342440128326416,29.601330757141113,29.014365673065186,27.968721389770508,28.26913356781006,28.588109016418457,28.735992908477783,29.74562644958496,29.51974630355835,29.302029609680176,20.02946138381958,29.06198740005493,28.493592739105225,29.075117111206055,28.030648231506348,28.672404289245605,28.80840539932251,28.51423740386963,28.89003276824951,20.27900457382202,28.56893539428711,28.719403743743896,29.10395860671997,28.114686012268066,28.167734146118164,20.252997875213623,28.385403156280518,28.650119304656982,29.119725227355957,27.849533557891846,26.782245635986328,26.852571964263916,28.668944835662842,28.220529556274414,28.66245746612549,27.81459331512451,29.55245018005371,27.93095588684082,28.69265079498291,28.823096752166748,28.365819454193115,29.00871753692627,28.80932092666626,29.678492546081543,28.898892402648926,28.708243370056152,28.787999153137207,27.963902950286865,29.16771650314331,28.86180877685547,29.19793128967285,28.869681358337402,29.192194938659668,28.784620761871338,29.345178604125977,28.33465337753296,29.33216094970703,28.98430109024048,28.99674892425537,29.69050645828247,29.14142608642578,28.879032135009766,28.06208848953247,29.871060848236084,28.916795253753662,29.252326488494873,28.442494869232178,29.15534019470215,29.104387760162354,29.084672927856445,28.294789791107178,28.43522310256958,29.57951784133911,29.080898761749268,29.999866485595703,28.828349113464355,28.445124626159668,29.00799036026001,29.09198522567749,28.386385440826416,28.851218223571777,29.74402904510498,28.921570777893066,28.337297439575195,28.373711109161377,28.902299404144287,29.36241626739502,28.790676593780518,28.822531700134277,29.23121452331543,29.325385093688965,29.59702968597412,28.256516456604004,28.024654388427734,28.7753963470459,28.782424926757812,25.317318439483643,28.872497081756592,28.683223724365234,29.201231002807617,28.79141330718994,29.435553550720215,28.994436264038086,28.577263355255127,28.374102115631104,28.27244281768799,28.719613552093506,29.36378002166748,25.697622299194336,28.81810188293457,29.08691644668579,29.033920764923096,28.039374351501465,27.97151803970337,28.24925184249878,29.668846130371094,25.59323787689209,29.79886770248413,28.848047256469727,28.665151596069336,29.353904724121094,26.633918285369873,29.354572296142578,29.07155990600586,29.278807640075684,20.009746551513672,28.84096622467041,28.153209686279297,29.82231855392456,29.79527711868286,28.98986577987671,29.15452480316162,29.107224941253662,28.746838569641113,27.905738353729248,28.62410068511963,28.453893661499023,28.687493801116943,29.969661235809326,27.99351692199707,28.972151279449463,28.507966995239258,29.07474994659424,29.860644340515137,29.54822540283203,28.676230907440186,28.25267791748047,29.638779163360596,29.078876972198486,29.435794353485107,28.799009323120117,29.746856689453125,28.781495094299316,29.37896490097046,29.129724502563477,28.441202640533447,28.17361354827881,29.191949367523193,28.448400497436523,28.532192707061768,27.794265747070312,29.392528533935547,27.9805588722229,28.604791164398193,29.141836166381836,28.98296356201172,29.578053951263428,28.982226848602295,29.01578426361084,29.110901355743408,28.015549182891846,28.598849773406982,29.0732479095459,29.148423671722412,29.048290252685547,28.208425045013428,29.71261739730835,29.7497820854187,29.28786277770996,28.7386417388916,29.10274028778076,27.879655361175537,29.31001901626587,25.26059627532959,26.37329339981079,28.995962142944336,30.24627685546875,29.21015501022339,29.25633668899536,28.437585830688477,28.436849117279053,29.435951709747314,28.92404794692993,25.528228282928467,28.996329307556152,29.06987190246582,28.3737850189209,27.718653678894043,29.321959018707275,29.346654415130615,28.147060871124268,29.711334705352783,29.282119274139404,29.3936824798584,28.839187622070312,28.440546989440918,29.52544927597046,28.54314088821411,28.995356559753418,27.82278060913086,29.09691333770752,29.210338592529297,29.39253330230713,28.998126983642578,28.50304365158081,28.21892261505127,28.427135944366455,29.267897605895996,28.507554531097412,29.21219825744629,28.51473331451416,28.926916122436523,29.223389625549316,28.936314582824707,28.440685272216797,20.081582069396973,28.811490535736084,28.06349277496338,28.947527408599854,29.67914581298828,27.900924682617188,29.73984956741333,28.94465923309326,27.74982452392578,29.01289463043213,28.528337478637695,29.284474849700928,29.21614408493042,28.824121952056885,29.597866535186768,28.4243106842041,27.850522994995117,28.866446018218994,29.173951148986816,27.83897876739502,29.32659387588501,28.48573923110962,28.766908645629883,28.51511001586914,25.614922046661377,29.194109439849854,28.993468284606934,29.103310108184814,20.162529945373535,29.197945594787598,27.95001745223999,28.170392513275146,28.34280252456665,29.55613136291504,28.703629970550537,29.569849967956543,29.415340423583984,28.913135528564453,29.774532318115234,29.366261959075928,27.919719219207764,28.637948036193848,29.24208164215088,29.094979763031006,29.700143337249756,29.544556140899658,29.173142910003662,29.39683198928833,29.54014301300049,29.535014629364014,28.067657947540283,28.474888801574707,29.411792755126953,28.846852779388428,28.531124591827393,28.213825225830078,29.126157760620117,28.488738536834717,29.011223316192627,28.46569538116455,28.549082279205322,29.40363883972168,28.500232696533203,28.599417209625244,29.39044952392578,28.885645866394043,29.256718158721924,30.669138431549072,28.91681671142578,26.248619556427002,28.919482231140137,27.49656915664673,28.826570510864258,29.4572114944458,29.47841167449951,29.1812801361084,27.876288890838623,27.539808750152588,28.819808959960938,29.052250385284424,29.04064416885376,29.070141315460205,28.52489709854126,29.153056144714355,28.932502269744873,28.608734607696533,29.098317623138428,29.303362369537354,27.889597415924072,29.284613132476807,30.11268138885498,29.24647808074951,29.318132400512695,28.84312391281128,28.408024311065674,29.04921531677246,28.74871253967285,28.17204475402832,19.960542917251587,29.51544761657715,28.264691829681396,28.641114234924316,29.401917457580566,28.85920763015747,28.066139221191406,29.078309535980225,28.707880973815918,29.378559589385986,27.946035861968994,28.584434986114502,29.867193698883057,29.126667976379395,28.735194206237793,28.11624050140381,28.20439577102661,29.77062702178955,27.2282075881958,29.834227561950684,29.060146808624268,28.71654748916626,27.9429030418396,29.425764083862305,28.475894927978516,27.154147624969482,27.660953998565674,28.231773376464844,28.11171531677246,28.461167812347412,28.5007643699646,28.592963218688965,28.888611793518066,28.866569995880127,28.869802951812744,28.48961353302002,29.124462604522705,28.764138221740723,25.701274871826172,29.320697784423828,28.94662380218506,28.90812873840332,29.031555652618408,28.985133171081543,29.517970085144043,29.413418769836426,28.592498302459717,28.341422080993652,28.654046058654785,28.868412971496582,27.159693241119385,29.209730625152588,27.965729236602783,25.75706958770752,28.64105463027954,29.1756010055542,25.26559352874756,26.499004364013672,29.168288707733154,29.149081707000732,28.07295560836792,29.38581943511963,28.628525733947754,27.66632318496704,28.280813694000244,28.878984451293945,28.666808605194092,28.450136184692383,29.372446537017822,28.814070224761963,29.605166912078857,29.270107746124268,29.130666255950928,28.803391456604004,28.946454524993896,28.570570945739746,29.2677640914917,28.59083890914917,29.621946811676025,29.10740375518799,29.21555519104004,27.18712568283081,28.867831230163574,28.46778392791748,29.200093746185303,27.364234924316406,27.93346405029297,29.132072925567627,28.64445686340332,28.38930368423462,27.942209243774414,28.84852886199951,28.307416439056396,28.21347713470459,29.14841651916504,28.36263418197632,28.73457670211792,28.62529754638672,30.150926113128662,29.085354804992676,29.340012073516846,29.46371078491211,28.748362064361572,29.409451484680176,29.119510650634766,28.75303030014038,29.587864875793457,29.775593280792236,28.852834701538086,28.451764583587646,29.22264337539673,29.361517429351807,29.596140384674072,26.473100185394287,28.83843183517456,29.25713062286377,29.068939685821533,29.06397581100464,28.127150535583496,28.61060619354248,28.873584270477295,28.922035694122314,29.477574825286865,29.027328491210938,27.33212947845459,28.683431148529053,29.219846725463867,28.432011604309082,28.65598201751709,27.993919849395752,27.929039001464844,27.990901470184326,29.115760326385498,29.3505859375,28.75312566757202,28.84822130203247,28.280346393585205,27.812495231628418,28.91932725906372,28.45550775527954,28.666152954101562,28.52937936782837,28.22626829147339,29.1542387008667,28.985297679901123,28.685307502746582,28.277783393859863,28.438689708709717,26.8855619430542,29.884512424468994,28.394756317138672,28.626415729522705,29.2315673828125,29.369080066680908,28.934030532836914,28.450927734375,29.354422092437744,28.356668949127197,30.128467082977295,28.47672700881958,29.007418155670166,28.38632345199585,27.949988842010498,28.58262062072754,28.871145248413086,25.691049098968506,28.961763381958008,29.40335750579834,29.245140552520752,28.65178346633911,29.044270515441895,29.446799755096436,29.443156719207764,27.675061225891113,27.863004207611084,29.483458995819092,28.46057891845703,29.30159568786621,28.497190475463867,29.530818462371826,28.367483615875244,28.418068885803223,28.59344720840454,28.155720233917236,27.755041122436523,29.688894748687744,29.598302841186523,29.10529375076294,28.765923976898193,28.368260860443115,28.938746452331543,29.762260913848877,28.923020362854004,28.87589931488037,28.117752075195312,29.128799438476562,29.515280723571777,29.758644104003906,28.188934326171875,28.483340740203857,29.115042686462402,28.958377838134766,29.13611650466919,29.709491729736328,29.233925342559814,28.599367141723633,29.04033660888672,29.076287746429443,29.2075777053833,29.52759027481079,28.537311553955078,29.310321807861328,28.265223503112793,27.83397912979126,29.234309196472168,28.6208438873291,27.54892349243164,29.051387310028076,29.151809215545654,29.458680152893066,28.883934020996094,29.115378856658936,28.47722291946411,29.524989128112793,28.181092739105225,28.875141143798828,29.185402393341064,28.52971076965332,28.614702224731445,27.55793333053589,28.711156845092773,29.31074857711792,28.854360580444336,25.404281616210938,29.509589672088623,29.421980381011963,28.736858367919922,28.88235092163086,28.215949535369873,29.828002452850342,27.98722743988037,28.323988914489746,28.96160364151001,27.816107273101807,28.854756355285645,30.03140926361084,29.17558193206787,27.48969793319702,29.419124126434326,28.88155460357666,28.84624481201172,29.135019779205322,28.33292007446289,28.815937042236328,29.427192211151123,28.771181106567383,29.29271697998047,28.31815242767334,28.678135871887207,20.190863609313965,28.800899982452393,25.33472776412964,30.659453868865967,28.862876892089844,28.598859310150146,28.4987735748291,28.112914562225342,29.183967113494873,29.200174808502197,27.836813926696777,28.761658668518066,27.813727855682373,29.137368202209473,28.8364315032959,28.32655668258667,29.393649101257324,29.25612449645996,28.880934715270996,28.880133628845215,28.66262197494507,29.16799306869507,28.059816360473633,29.308884143829346,27.921886444091797,27.707431316375732,28.98618221282959,28.79408597946167,28.779573440551758,28.92660617828369,27.033658027648926,29.240028858184814,29.311938285827637,28.74210834503174,29.293999671936035,29.159202575683594,29.40371036529541,29.115240573883057,29.706006050109863,28.167953491210938,28.822786808013916,29.044415950775146,28.468492031097412,29.644455909729004,28.894619941711426,29.128854274749756,29.848825931549072,28.39268445968628,30.303590297698975,28.022642135620117,28.815491199493408,28.978891372680664,28.77450704574585,29.111061096191406,29.40852165222168,28.859364986419678,29.103469848632812,28.248937129974365,29.279356002807617,20.029594898223877,29.216434955596924,28.880176544189453,29.573190212249756,28.955061435699463,29.209048748016357,29.127273559570312,28.876278400421143,27.9795241355896,28.94137144088745,28.50794792175293,29.538609981536865,28.096730709075928,28.64008903503418,26.60247802734375,28.94742727279663,28.740005493164062,20.199625492095947,29.013402462005615,28.18739652633667,29.70320463180542,28.682920932769775,29.19266939163208,29.367783069610596,28.319671154022217,28.292853832244873,28.793671131134033,29.45681095123291,29.203174114227295,28.93233060836792,29.10238027572632,29.24342393875122,27.380247116088867,29.067888259887695,29.231746196746826,27.874698638916016,28.10575008392334,28.792076110839844,29.120168685913086,27.024059295654297,28.2886004447937,28.93993377685547,29.33197021484375,28.497698307037354,28.30991506576538,29.338443279266357,29.133446216583252,28.042140007019043,28.639445304870605,28.75617265701294,29.269351959228516,29.572019577026367,28.745646476745605,29.76201295852661,28.741650581359863,29.175701141357422,29.652419090270996,28.618488311767578,28.86636257171631,28.917899131774902,26.589245796203613,27.97762632369995,30.050172805786133,28.788931369781494,29.4134259223938,28.160419464111328,29.16935443878174,28.302810192108154,28.195948600769043,28.58678102493286,28.509833812713623,28.19913387298584,25.609886646270752,29.26830530166626,29.040343761444092,29.255852699279785,29.5768404006958,29.09665822982788,28.318676948547363,28.497953414916992,28.96632432937622];


save('exp_scalability_analysis.mat','line','gflops_fid_16B_64','gflops_fid_16B_128','gflops_fid_16B_256','gflops_fid_32B_64','gflops_fid_32B_128','gflops_fid_32B_256','gflops_fid_64B_64','gflops_fid_64B_128','gflops_fid_64B_256');

================================================
FILE: plots/requirements.txt
================================================
matplotlib
scipy
numpy

================================================
FILE: tfdiff/__init__.py
================================================


================================================
FILE: tfdiff/dataset.py
================================================
import numpy as np
import os
import random
import torch
import torch.nn.functional as F
import scipy.io as scio
from tfdiff.params import AttrDict
from glob import glob
from torch.utils.data.distributed import DistributedSampler

# data_key='csi_data',
# gesture_key='gesture',
# location_key='location',
# orient_key='orient',
# room_key='room',
# rx_key='rx',
# user_key='user',


def _nested_map(struct, map_fn):
    if isinstance(struct, tuple):
        return tuple(_nested_map(x, map_fn) for x in struct)
    if isinstance(struct, list):
        return [_nested_map(x, map_fn) for x in struct]
    if isinstance(struct, dict):
        return {k: _nested_map(v, map_fn) for k, v in struct.items()}
    return map_fn(struct)


class WiFiDataset(torch.utils.data.Dataset):
    def __init__(self, paths):
        super().__init__()
        self.filenames = []
        for path in paths:
            self.filenames += glob(f'{path}/**/user*.mat', recursive=True)

    def __len__(self):
        return len(self.filenames)

    def __getitem__(self, idx):
        cur_filename = self.filenames[idx]
        cur_sample = scio.loadmat(cur_filename,verify_compressed_data_integrity=False)
        # cur_data = torch.from_numpy(cur_sample['csi_data']).to(torch.complex64)
        cur_data = torch.from_numpy(cur_sample['feature']).to(torch.complex64)
        cur_cond = torch.from_numpy(cur_sample['cond']).to(torch.complex64)
        return {
            'data': cur_data,
            'cond': cur_cond.squeeze(0)
        }
    

class FMCWDataset(torch.utils.data.Dataset):
    def __init__(self, paths):
        super().__init__()
        self.filenames = []
        for path in paths:
            self.filenames += glob(f'{path}/**/*.mat', recursive=True)

    def __len__(self):
        return len(self.filenames)

    def __getitem__(self, idx):
        cur_filename = self.filenames[idx]
        cur_sample = scio.loadmat(cur_filename)
        cur_data = torch.from_numpy(cur_sample['feature']).to(torch.complex64)
        cur_cond = torch.from_numpy(cur_sample['cond'].astype(np.int16)).to(torch.complex64)
        return {
            'data': cur_data,
            'cond': cur_cond.squeeze(0)
        }

class MIMODataset(torch.utils.data.Dataset):
  def __init__(self, paths):
    super().__init__()
    self.filenames = []
    for path in paths:
        self.filenames += glob(f'{path}/**/*.mat', recursive=True)

  def __len__(self):
    return len(self.filenames)

  def __getitem__(self,idx):
    dataset = scio.loadmat(self.filenames[idx])
    data = torch.from_numpy(dataset['down_link']).to(torch.complex64)
    cond = torch.from_numpy(dataset['up_link']).to(torch.complex64)
    return {
        'data': torch.view_as_real(data),
        'cond': torch.view_as_real(cond)
    }


class EEGDataset(torch.utils.data.Dataset):
  def __init__(self, paths):
    super().__init__()
    paths = paths[0]
    self.filenames = []
    self.filenames += glob(f'{paths}/*.mat', recursive=True)

  def __len__(self):
    return len(self.filenames)

  def __getitem__(self,idx):
    dataset = scio.loadmat(self.filenames[idx])
    data = torch.from_numpy(dataset['clean']).to(torch.complex64)
    cond = torch.from_numpy(dataset['disturb']).to(torch.complex64)
    return {
        'data': data,
        'cond': cond
    }


class Collator:
    def __init__(self, params):
        self.params = params

    def collate(self, minibatch):
        sample_rate = self.params.sample_rate
        task_id = self.params.task_id
        ## WiFi Case
        if task_id == 0:
            for record in minibatch:
                # Filter out records that aren't long enough.
                if len(record['data']) < sample_rate:
                    del record['data']
                    del record['cond']
                    continue
                data = torch.view_as_real(record['data']).permute(1, 2, 0)
                down_sample = F.interpolate(data, sample_rate, mode='nearest-exact')
                norm_data = (down_sample - down_sample.mean()) / down_sample.std()
                record['data'] = norm_data.permute(2, 0, 1)
            data = torch.stack([record['data'] for record in minibatch if 'data' in record])
            cond = torch.stack([record['cond'] for record in minibatch if 'cond' in record])
            return {
                'data': data,
                'cond': torch.view_as_real(cond),
            }
        ## FMCW Case
        elif task_id == 1:
            for record in minibatch:
                # Filter out records that aren't long enough.
                if len(record['data']) < sample_rate:
                    del record['data']
                    del record['cond']
                    continue
                data = torch.view_as_real(record['data']).permute(1, 2, 0)
                down_sample = F.interpolate(data, sample_rate, mode='nearest-exact')
                norm_data = (down_sample - down_sample.mean()) / down_sample.std()
                record['data'] = norm_data.permute(2, 0, 1)
            data = torch.stack([record['data'] for record in minibatch if 'data' in record])
            cond = torch.stack([record['cond'] for record in minibatch if 'cond' in record])
            return {
                'data': data,
                'cond': torch.view_as_real(cond),
            }

        ## MIMO Case
        elif task_id == 2:
            for record in minibatch:
                data = record['data']
                cond = record['cond']
                # print(f'data.shape:{data.shape}')
                norm_data = (data) / cond.std()
                norm_cond = (cond) / cond.std()
                record['data'] = norm_data.reshape(14, 96, 26, 2).transpose(1,2)
                record['cond'] = norm_cond.reshape(14, 96, 26, 2).transpose(1,2)
            data = torch.stack([record['data'] for record in minibatch if 'data' in record])
            cond = torch.stack([record['cond'] for record in minibatch if 'cond' in record])
            return {
                'data': data,
                'cond': cond,
            } 

        ## EEG Case
        if task_id == 3:
            for record in minibatch:
                data = record['data']
                cond = record['cond']

                norm_data = data / cond.std()
                norm_cond = cond / cond.std()
                
                record['data'] = norm_data.reshape(512, 1, 1)
                record['cond'] = norm_cond.reshape(512)
            data = torch.stack([record['data'] for record in minibatch if 'data' in record])
            cond = torch.stack([record['cond'] for record in minibatch if 'cond' in record])
            return {
                'data': torch.view_as_real(data),
                'cond': torch.view_as_real(cond),
            } 

        else:
            raise ValueError("Unexpected task_id.")


def from_path(params, is_distributed=False):
    data_dir = params.data_dir
    task_id = params.task_id
    if task_id == 0:
        dataset = WiFiDataset(data_dir)
    elif task_id == 1:
        dataset = FMCWDataset(data_dir)
    elif task_id == 2:
        dataset = MIMODataset(data_dir)
    elif task_id == 3:
        dataset = EEGDataset(data_dir)
    else:
        raise ValueError("Unexpected task_id.")
    return torch.utils.data.DataLoader(
        dataset,
        batch_size=params.batch_size,
        collate_fn=Collator(params).collate,
        shuffle=not is_distributed,
        num_workers=8,
        sampler=DistributedSampler(dataset) if is_distributed else None,
        pin_memory=True,
        drop_last=True,
        persistent_workers=True)


def from_path_inference(params):
    cond_dir = params.cond_dir
    task_id = params.task_id
    if task_id == 0:
        dataset = WiFiDataset(cond_dir)
    elif task_id == 1:
        dataset = FMCWDataset(cond_dir)
    elif task_id == 2:
        dataset = MIMODataset(cond_dir)
    elif task_id == 3:
        dataset = EEGDataset(cond_dir)
    else:
        raise ValueError("Unexpected task_id.")
    return torch.utils.data.DataLoader(
        dataset,
        batch_size=params.inference_batch_size,
        collate_fn=Collator(params).collate,
        shuffle=False,
        num_workers=os.cpu_count()
        )


================================================
FILE: tfdiff/diffusion.py
================================================
import numpy as np
import torch
from torch import nn
from torch.nn import functional as F

class SignalDiffusion(nn.Module):
    def __init__(self, params):
        super().__init__()
        self.params = params
        self.task_id = params.task_id
        self.input_dim = self.params.sample_rate # input time-series data length, N
        self.extra_dim = self.params.extra_dim # dimension of each data sample, e.g., [S A 2] for complex-valued CSI
        self.max_step = self.params.max_step # maximum diffusion steps
        beta = np.array(self.params.noise_schedule) # \beta, [T]
        self.alpha = torch.tensor((1-beta).astype(np.float32)) # \alpha_t [T]
        self.alpha_bar = torch.cumprod(self.alpha, dim=0) # \bar{\alpha_t}, [T]
        self.var_blur = torch.tensor(np.array(self.params.blur_schedule).astype(np.float32)) # var of blur kernels on the frequency domain for each diffusion step
        self.var_blur_bar = torch.cumsum(self.var_blur, dim=0) # var of blur kernels on the frequency domain, [T]
        self.var_kernel = (self.input_dim / self.var_blur).unsqueeze(1) # var of each G_t, [T, 1]
        self.var_kernel_bar = (self.input_dim / self.var_blur_bar).unsqueeze(1) # var of each \bar{G_t}, [T, 1]
        self.gaussian_kernel = self.get_kernel(self.var_kernel) # G_t, [T, N]
        self.gaussian_kernel_bar = self.get_kernel(self.var_kernel_bar) # \bar{G_t}, [T, N]
        # The weight of original information x_0 in degraded data x_t
        self.info_weights = self.gaussian_kernel_bar * torch.sqrt(self.alpha_bar).unsqueeze(-1) # [T, N]
        # The overall weight of gaussian noise \epsilon in degraded data x_t
        self.noise_weights = self.get_noise_weights() # [T, N]
      
    def get_kernel(self, var_kernel):
        samples = torch.arange(0, self.input_dim) # [N]
        gaussian_kernel = torch.exp(-((samples - self.input_dim // 2)**2) / (2 * var_kernel)) / torch.sqrt(2 * torch.pi * var_kernel) # G_t, [T, N]
        gaussian_kernel = self.input_dim * gaussian_kernel / torch.sum(gaussian_kernel, dim=1, keepdim=True) # Normalized G_t, [T, N]
        return gaussian_kernel

    def get_noise_weights(self):
        noise_weights = []
        for t in range(self.max_step):
            upper_bound = t + 1
            one_minus_alpha_sqrt = torch.sqrt(1 - self.alpha[0:upper_bound]) # \sqrt(1-\bar{\alpha_s}), for s in [1, t], [t]
            rev_one_minus_alpha_sqrt = torch.flipud(one_minus_alpha_sqrt) # \sqrt(1-\bar{\alpha_s}), for s in [t, 1], [t]
            rev_alpha = torch.flipud(self.alpha[0:upper_bound]) # alpha_s, for s in [t, 1], [t]
            rev_alpha_bar_sqrt = torch.sqrt(torch.cumprod(rev_alpha, dim=0) / rev_alpha[-1]) # \sqrt{\bar{\alpha_t} / \bar{\alpha_s}}, for s in [t, 1], [t]
            rev_var_blur = torch.flipud(self.var_blur[:upper_bound]) # [t] 
            rev_var_blur_bar = torch.cumsum(rev_var_blur, dim=0) - rev_var_blur[-1] # [t]
            rev_var_kernel_bar = (self.input_dim / rev_var_blur_bar).unsqueeze(1) # [t, 1]
            rev_kernel_bar = self.get_kernel(rev_var_kernel_bar) # \bar{G_t} / \bar{G_s}, for s in [t, 1], [t, N]
            rev_kernel_bar[0, :] = torch.ones(self.input_dim) 
            noise_weights.append(torch.mv((rev_alpha_bar_sqrt.unsqueeze(-1) * rev_kernel_bar).transpose(0, 1), rev_one_minus_alpha_sqrt)) # [t, N]
        return torch.stack(noise_weights, dim=0) # [T, N] 

    def get_noise_weights_stats(self):
        noise_weights = []
        one_minus_alpha_sqrt = torch.sqrt(1 - self.alpha[0])
        for t in range(self.max_step):
            noise_weights.append((1 - torch.sqrt(self.alpha_bar[t])*self.gaussian_kernel_bar[t, :]) / (1 - torch.sqrt(self.alpha[0]) * self.gaussian_kernel[0, :]))
        return one_minus_alpha_sqrt * torch.stack(noise_weights, dim=0) # [T, N]

    ## Depracated: numerical instable when params.blur_schedule is high, kernel may divided by 0.
    def get_noise_weights_div(self):
        noise_weights = []
        for t in range(self.max_step):
            upper_bound = t + 1
            one_minus_alpha_sqrt = torch.sqrt(1 - self.alpha[:upper_bound]) # \sqrt(1-\bar{\alpha_s}), for s in [1, t], [t]
            ratio_alpha_bar_sqrt = torch.sqrt(self.alpha_bar[t] / self.alpha_bar[:upper_bound]) # \sqrt(\bar{\alpha_t} / \bar{\alpha_s}), for s in [1, t], [t]
            ratio_kernel_bar = self.gaussian_kernel_bar[t, :] / self.gaussian_kernel_bar[:upper_bound, :] # \bar{G_t} / \bar{G_s}, for s in [1, t], [t, N]
            noise_weights.append(torch.mv((ratio_alpha_bar_sqrt.unsqueeze(-1) * ratio_kernel_bar).transpose(0, 1), one_minus_alpha_sqrt)) # [t, N]
        return torch.stack(noise_weights, dim=0) # [T, N]
    
    ## Depracated: numerical instable when params.blur_schedule is high, amplitude of kernel may overflow.
    def get_noise_weights_prod(self):
        noise_weights = []
        for t in range(self.max_step):
            upper_bound = t + 1
            one_minus_alpha_sqrt = torch.sqrt(1 - self.alpha[0:upper_bound]) # \sqrt(1-\bar{\alpha_s}), for s in [1, t], [t]
            rev_one_minus_alpha_sqrt = torch.flipud(one_minus_alpha_sqrt) # \sqrt(1-\bar{\alpha_s}), for s in [t, 1], [t]
            rev_alpha = torch.flipud(self.alpha[0:upper_bound]) # alpha_s, for s in [t, 1], [t]
            rev_alpha_bar_sqrt = torch.sqrt(torch.cumprod(rev_alpha, dim=0) / rev_alpha[-1]) # \sqrt{\bar{\alpha_t} / \bar{\alpha_s}}, for s in [t, 1], [t]
            rev_kernel = torch.flipud(self.gaussian_kernel[:upper_bound, :]) # G_s, for s in [t, 1], [t, N]
            rev_kernel_bar = torch.cumprod(rev_kernel, dim=0) / rev_kernel[-1, :] # \bar{G_t} / \bar{G_s}, for s in [t, 1], [t, N]
            noise_weights.append(torch.mv((rev_alpha_bar_sqrt.unsqueeze(-1) * rev_kernel_bar).transpose(0, 1), rev_one_minus_alpha_sqrt)) # [t, N]
        return torch.stack(noise_weights, dim=0) # [T, N] 

    def degrade_fn(self, x_0, t, task_id):
        device = x_0.device
        if task_id in [0, 1]:
            noise_weight = self.noise_weights[t, :].unsqueeze(-1).unsqueeze(-1).to(device) # equivalent gaussian noise weights, [B, N, 1, 1, 1]
            info_weight = self.info_weights[t, :].unsqueeze(-1).unsqueeze(-1).to(device) # equivalent original info weights, [B, N, 1, 1, 1]
        if task_id in [2, 3]:
            noise_weight = self.noise_weights[t, :].unsqueeze(-1).unsqueeze(-1).unsqueeze(-1).to(device) # equivalent gaussian noise weights, [B, N, 1, 1, 1]
            info_weight = self.info_weights[t, :].unsqueeze(-1).unsqueeze(-1).unsqueeze(-1).to(device) # equivalent original info weights, [B, N, 1, 1, 1]
        # random seed
        torch.manual_seed(11)
        noise =  noise_weight * torch.randn_like(x_0, dtype=torch.float32, device=device) # [B, N, S, A, 2]
        x_t = info_weight * x_0 + noise # [B, N, S, A, 2]
        return x_t


    def sampling(self, restore_fn, cond, device):
        batch_size = cond.shape[0] # B
        batch_max = (self.max_step-1)*torch.ones(batch_size, dtype=torch.int64)
        # Add batch dimension.
        # cond = torch.view_as_real(torch.from_numpy(cond['cond']).to(torch.complex64)).unsqueeze(0)
        # cond = cond.unsqueeze(0)
        # Construct a mini-batch.
        # cond = cond.repeat((batch_size, 1, 1, 1, 1))
        # Generate degraded noise.
        data_dim = [batch_size, self.input_dim] + self.extra_dim + [2]
        noise = torch.randn(data_dim, dtype=torch.float32, device=device) # [B, N, S, A, 2]
        if self.task_id in [2,3]:
            inf_weight = (self.noise_weights[batch_max, :] + self.info_weights[batch_max, :]).unsqueeze(-1).unsqueeze(-1).unsqueeze(-1).to(device) # [B, N, 1, 1, 1]
        else:
            inf_weight = (self.noise_weights[batch_max, :] + self.info_weights[batch_max, :]).unsqueeze(-1).unsqueeze(-1).to(device) # [B, N, 1, 1, 1]
        x_s = inf_weight * noise # [B, N, S, A, 2]
        # Restore data from noise.
        for s in range(self.max_step-1, -1, -1): # reverse from t to 0
            x_0_hat = restore_fn(x_s, s*torch.ones(batch_size, dtype=torch.int64), cond) # resotre \hat{x_0} from x_s using trained tfdiff model
            if s > 0:
                # x_{s-1} = D(\hat{x_0}, s-1)
                x_s = self.degrade_fn(x_0_hat, t=(s-1)*torch.ones(batch_size, dtype=torch.int64), task_id = self.task_id) # degrade \hat{x_0} to x_{s-1}
        return x_0_hat
    
    def robust_sampling(self, restore_fn, cond, device):
        batch_size = cond.shape[0] # B
        batch_max = (self.max_step-1)*torch.ones(batch_size, dtype=torch.int64)
        # Add batch dimension.
        # cond = torch.view_as_real(torch.from_numpy(cond['cond']).to(torch.complex64)).unsqueeze(0)
        # Construct a mini-batch.
        # cond = cond.repeat((batch_size, 1, 1, 1, 1))
        # Generate degraded noise.
        data_dim = [batch_size, self.input_dim] + self.extra_dim + [2]
        noise = torch.randn(data_dim, dtype=torch.float32, device=device) # [B, N, S, A, 2]
        if self.task_id in [2,3]:
            inf_weight = (self.noise_weights[batch_max, :] + self.info_weights[batch_max, :]).unsqueeze(-1).unsqueeze(-1).unsqueeze(-1).to(device) # [B, N, 1, 1, 1]
        else:
            inf_weight = (self.noise_weights[batch_max, :] + self.info_weights[batch_max, :]).unsqueeze(-1).unsqueeze(-1).to(device) # [B, N, 1, 1, 1]
        x_s = inf_weight * noise # [B, N, S, A, 2]
        # Restore data from noise.
        for s in range(self.max_step-1, -1, -1): # reverse from t to 0
            x_0_hat = restore_fn(x_s, s*torch.ones(batch_size, dtype=torch.int64), cond) # resotre \hat{x_0} from x_s using trained tfdiff model
            if s > 0:
                # x_{s-1} = x_s - D(\hat{x_0}, s) + D(\hat{x_0}, s-1)
                x_s = x_s - self.degrade_fn(x_0_hat, t=s*torch.ones(batch_size, dtype=torch.int64),task_id = self.task_id) + self.degrade_fn(x_0_hat, t=(s-1)*torch.ones(batch_size, dtype=torch.int64),task_id = self.task_id) # degrade \hat{x_0} to x_{s-1}
        return x_0_hat
        
    def fast_sampling(self, restore_fn, cond, device):
        batch_size = cond.shape[0] # B
        batch_max = (self.max_step-1)*torch.ones(batch_size, dtype=torch.int64)
        # Generate degraded noise.
        data_dim = [batch_size, self.input_dim] + self.extra_dim + [2]
        noise = torch.randn(data_dim, dtype=torch.float32, device=device) # [B, N, S, A, 2]
        if self.task_id in [2,3]:
            inf_weight = (self.noise_weights[batch_max, :] + self.info_weights[batch_max, :]).unsqueeze(-1).unsqueeze(-1).unsqueeze(-1).to(device) # [B, N, 1, 1, 1]
        else:
            inf_weight = (self.noise_weights[batch_max, :] + self.info_weights[batch_max, :]).unsqueeze(-1).unsqueeze(-1).to(device) # [B, N, 1, 1, 1]
        x_s = inf_weight * noise # [B, N, S, A, 2]
        # Restore data from noise.
        x_0_hat = restore_fn(x_s, batch_max, cond)
        return x_0_hat
    
    def native_sampling(self, restore_fn, data, cond, device):
        batch_size = cond.shape[0]
        batch_max = (self.max_step-1)*torch.ones(batch_size, dtype=torch.int64)
        # Generate degraded noise.
        x_s = self.degrade_fn(data, batch_max,task_id = self.task_id).to(device)
        # Restore data from noise.
        x_0_hat = restore_fn(x_s, batch_max, cond)
        return x_0_hat


class GaussianDiffusion(nn.Module):
    def __init__(self, params):
        super().__init__()
        self.params = params
        self.input_dim = self.params.sample_rate # input time-series data length, N
        self.extra_dim = self.params.extra_dim # dimension of each data sample, e.g., [S A 2] for complex-valued CSI
        self.max_step = self.params.max_step # maximum diffusion steps
        beta = np.array(self.params.noise_schedule) # \beta, [T]
        alpha = torch.tensor((1-beta).astype(np.float32)) # \alpha_t [T]
        self.alpha_bar = torch.cumprod(alpha, dim=0) # \bar{\alpha_t}, [T]
        # The overall weight of gaussian noise \epsilon in degraded data x_t
        self.noise_weights = torch.sqrt(1 - self.alpha_bar) # \sqrt{1 - \bar{\alpha_t}}, [T]
        self.info_weights = torch.sqrt(self.alpha_bar) # \sqrt{\bar{\alpha_t}}, [T]

    def degrade_fn(self, x_0, t):
        device = x_0.device
        noise_weight = self.noise_weights[t].unsqueeze(-1).unsqueeze(-1).unsqueeze(-1).to(device) # equivalent gaussian noise weights, [B, 1, 1, 1]
        info_weight = self.info_weights[t].unsqueeze(-1).unsqueeze(-1).unsqueeze(-1).to(device) # equivalent original info weights, [B, 1, 1, 1] 
        noise = noise_weight * torch.randn_like(x_0, dtype=torch.float32, device=device) # [B, N, S, 2]
        # noise =  noise_weight.unsqueeze(-1).unsqueeze(-1) * torch.randn_like(x_0, dtype=torch.float32, device=device) # [B, N, S, A, 2]
        x_t = info_weight * x_0 + noise # [B, N, S, A, 2]
        return x_t

    def sampling(self, restore_fn, cond, device):
        batch_size = cond.shape[0] # B
        # Generate degraded noise.
        data_dim = [batch_size, self.input_dim] + self.extra_dim + [2]
        inf_weight = (self.noise_weights[self.max_step-1] + self.info_weights[self.max_step-1]).to(device) # scalar
        x_s = inf_weight * torch.randn(data_dim, dtype=torch.float32, device=device) # [B, N, S, 2]
        # Restore data from noise.
        for s in range(self.max_step-1, -1, -1): # reverse from t to 0
            x_0_hat = restore_fn(x_s, s*torch.ones(batch_size, dtype=torch.int64), cond) # resotre \hat{x_0} from x_s using trained tfdiff model
            if s > 0:
                # x_{s-1} = D(\hat{x_0}, s-1)
                x_s = self.degrade_fn(x_0_hat, t=(s-1)*torch.ones(batch_size, dtype=torch.int64)) # degrade \hat{x_0} to x_{s-1}
        return x_0_hat
    
    def robust_sampling(self, restore_fn, cond, device):
        batch_size = cond.shape[0] # B
        # Generate degraded noise.
        data_dim = [batch_size, self.input_dim] + self.extra_dim + [2]
        inf_weight = (self.noise_weights[self.max_step-1] + self.info_weights[self.max_step-1]).to(device) # scalar
        x_s = inf_weight * torch.randn(data_dim, dtype=torch.float32, device=device) # [B, N, S, A, 2]
        # Restore data from noise.
        for s in range(self.max_step-1, -1, -1): # reverse from t to 0
            x_0_hat = restore_fn(x_s, s*torch.ones(batch_size, dtype=torch.int64), cond) # resotre \hat{x_0} from x_s using trained tfdiff model
            if s > 0:
                # x_{s-1} = x_s - D(\hat{x_0}, s) + D(\hat{x_0}, s-1)
                x_s = x_s - self.degrade_fn(x_0_hat, t=[s]) + self.degrade_fn(self, x_0_hat, t=(s-1)*torch.ones(batch_size, dtype=torch.int64)) # degrade \hat{x_0} to x_{s-1}
        return x_0_hat

    def fast_sampling(self, restore_fn, cond, device):
        batch_size = cond.shape[0] # B
        batch_max = (self.max_step-1)*torch.ones(batch_size, dtype=torch.int64)
        # Generate degraded noise.
        data_dim = [batch_size, self.input_dim] + self.extra_dim + [2]
        noise = torch.randn(data_dim, dtype=torch.float32, device=device) # [B, N, S, A, 2]
        inf_weight = (self.noise_weights[self.max_step-1] + self.info_weights[self.max_step-1]).to(device) # scalar
        x_s = inf_weight * noise # [B, N, S, A, 2]
        # Restore data from noise.
        x_0_hat = restore_fn(x_s, batch_max, cond)
        return x_0_hat
    
    def native_sampling(self, restore_fn, data, cond, device):
        batch_size = cond.shape[0]
        batch_max = (self.max_step-1)*torch.ones(batch_size, dtype=torch.int64)
        # Generate degraded noise.
        x_s = self.degrade_fn(data, batch_max).to(device)
        # Restore data from noise.
        x_0_hat = restore_fn(x_s, batch_max, cond)
        return x_0_hat

================================================
FILE: tfdiff/eeg_model.py
================================================
import math
from math import sqrt
import numpy as np
import torch
from torch import nn
from torch.nn import functional as F

import complex.complex_module as cm


def init_weight_norm(module):
    if isinstance(module, nn.Linear):
        nn.init.normal_(module.weight, std=0.02)
        if module.bias is not None:
            nn.init.constant_(module.bias, 0)


def init_weight_zero(module):
    if isinstance(module, nn.Linear):
        nn.init.constant_(module.weight, 0)
        if module.bias is not None:
            nn.init.constant_(module.bias, 0)


def init_weight_xavier(module):
    if isinstance(module, nn.Linear):
        nn.init.xavier_uniform_(module.weight)
        if module.bias is not None:
            nn.init.constant_(module.bias, 0)


@torch.jit.script
def modulate(x, shift, scale):
    return x * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1)


class DiffusionEmbedding(nn.Module):
    def __init__(self, max_step, embed_dim=256, hidden_dim=256):
        super().__init__()
        self.register_buffer('embedding', self._build_embedding(
            max_step, embed_dim), persistent=False)
        self.projection = nn.Sequential(
            cm.ComplexLinear(embed_dim, hidden_dim, bias=True),
            cm.ComplexSiLU(),
            cm.ComplexLinear(hidden_dim, hidden_dim, bias=True),
        )
        self.hidden_dim = hidden_dim
        self.apply(init_weight_norm)

    def forward(self, t):
        if t.dtype in [torch.int32, torch.int64]:
            x = self.embedding[t]
        else:
            x = self._lerp_embedding(t)
        return self.projection(x)

    def _lerp_embedding(self, t):
        low_idx = torch.floor(t).long()
        high_idx = torch.ceil(t).long()
        low = self.embedding[low_idx]
        high = self.embedding[high_idx]
        return low + (high - low) * (t - low_idx)

    def _build_embedding(self, max_step, embed_dim):
        steps = torch.arange(max_step).unsqueeze(1)  # [T,1]
        dims = torch.arange(embed_dim).unsqueeze(0)          # [1,E]
        table = steps * torch.exp(-math.log(max_step)
                                  * dims / embed_dim)     # [T,E]
        table = torch.view_as_real(torch.exp(1j * table))
        return table


# TODO: Replace MLP with nn.Embedding
class MLPConditionEmbedding(nn.Module):
    def __init__(self, cond_dim, hidden_dim=256):
        super().__init__()
        self.projection = nn.Sequential(
            cm.ComplexLinear(cond_dim, hidden_dim, bias=True),
            cm.ComplexSiLU(),
            cm.ComplexLinear(hidden_dim, hidden_dim*4, bias=True),
            cm.ComplexSiLU(),
            cm.ComplexLinear(hidden_dim*4, hidden_dim, bias=True)
            )
        self.apply(init_weight_norm)

    def forward(self, c):
        return self.projection(c)

class PositionEmbedding(nn.Module):
    def __init__(self, max_len, input_dim, hidden_dim):
        super().__init__()
        self.register_buffer('embedding', self._build_embedding(
            max_len, hidden_dim), persistent=False)
        self.projection = cm.ComplexLinear(input_dim, hidden_dim)
        self.apply(init_weight_xavier)

    def forward(self, x):
        x = self.projection(x)
        return cm.complex_mul(x, self.embedding.to(x.device))

    def _build_embedding(self, max_len, hidden_dim):
        steps = torch.arange(max_len).unsqueeze(1)  # [P,1]
        dims = torch.arange(hidden_dim).unsqueeze(0)          # [1,E]
        table = steps * torch.exp(-math.log(max_len)
                                  * dims / hidden_dim)     # [P,E]
        table = torch.view_as_real(torch.exp(1j * table))
        return table


class CDiTBlock(nn.Module):
    def __init__(self, hidden_dim, num_heads, dropout, mlp_ratio=4.0, **block_kwargs):
        super().__init__()
        self.norm1 = cm.NaiveComplexLayerNorm(
            hidden_dim, eps=1e-6, elementwise_affine=False)
        self.attn = cm.ComplexMultiHeadAttention(
            hidden_dim, hidden_dim, num_heads, dropout, bias=True, **block_kwargs)
        self.norm2 = cm.NaiveComplexLayerNorm(
            hidden_dim, eps=1e-6, elementwise_affine=False)
        mlp_hidden_dim = int(hidden_dim * mlp_ratio)
        def approx_gelu(): return cm.ComplexGELU(approximate='tanh')
        self.mlp = cm.ComplexMLP(
            hidden_dim, mlp_hidden_dim, act_layer=approx_gelu, dropout=0)
        self.adaLN_modulation = nn.Sequential(
            cm.ComplexSiLU(),
            cm.ComplexLinear(hidden_dim, 6*hidden_dim, bias=True)
        )
        self.apply(init_weight_xavier)
        self.adaLN_modulation.apply(init_weight_zero)

    def forward(self, x, c):
        shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.adaLN_modulation(
            c).chunk(6, dim=1)
        x = x + \
            gate_msa.unsqueeze(
                1) * self.attn(modulate(self.norm1(x), shift_msa, scale_msa),\
                                modulate(self.norm1(x), shift_msa, scale_msa),\
                                modulate(self.norm1(x), shift_msa, scale_msa))
        x = x + \
            gate_mlp.unsqueeze(
                1) * self.mlp(modulate(self.norm2(x), shift_mlp, scale_mlp))
        return x


class FinalLayer(nn.Module):
    def __init__(self, hidden_dim, out_dim):
        super().__init__()
        self.norm = cm.NaiveComplexLayerNorm(
            hidden_dim, eps=1e-6, elementwise_affine=False)
        self.linear = cm.ComplexLinear(hidden_dim, out_dim, bias=True)
        self.adaLN_modulation = nn.Sequential(
            cm.ComplexSiLU(),
            cm.ComplexLinear(hidden_dim, 2*hidden_dim, bias=True)
        )
        self.apply(init_weight_zero)

    def forward(self, x, c):
        shift, scale = self.adaLN_modulation(c).chunk(2, dim=1)
        x = modulate(self.norm(x), shift, scale)
        x = self.linear(x)
        return x


class tfdiff_eeg(nn.Module):
    def __init__(self, params):
        super().__init__()
        self.params = params
        self.learn_tfdiff = params.learn_tfdiff
        self.input_dim = params.input_dim
        self.output_dim = self.input_dim * 2 if self.learn_tfdiff else self.input_dim
        self.hidden_dim = params.hidden_dim
        self.num_heads = params.num_heads
        self.dropout = params.dropout
        self.task_id = params.task_id
        self.mlp_ratio = params.mlp_ratio
        self.p_embed = PositionEmbedding(
            params.sample_rate, params.input_dim, params.hidden_dim)
        self.t_embed = DiffusionEmbedding(
            params.max_step, params.embed_dim, params.hidden_dim)
    
        self.c_embed = MLPConditionEmbedding(params.cond_dim, params.hidden_dim)
        self.blocks = nn.ModuleList([
            CDiTBlock(self.hidden_dim, self.num_heads, self.dropout, self.mlp_ratio) for _ in range(params.num_block)
        ])
        self.final_layer = FinalLayer(self.hidden_dim, self.output_dim)
 
    def forward(self, x, t, c):
        x = x.reshape(-1,512,1,2)
        x = self.p_embed(x)
        t = self.t_embed(t)
        c = self.c_embed(c)
        c = c + t
        for block in self.blocks:
            x = block(x, c)
        x = self.final_layer(x, c)
        return x


================================================
FILE: tfdiff/fmcw_model.py
================================================
import math
from math import sqrt
import numpy as np
import torch
from torch import nn
from torch.nn import functional as F

import complex.complex_module as cm


def init_weight_norm(module):
    if isinstance(module, nn.Linear):
        nn.init.normal_(module.weight, std=0.02)
        if module.bias is not None:
            nn.init.constant_(module.bias, 0)


def init_weight_zero(module):
    if isinstance(module, nn.Linear):
        nn.init.constant_(module.weight, 0)
        if module.bias is not None
Download .txt
gitextract_yuerfw2n/

├── LICENSE
├── README.md
├── complex/
│   ├── __init__.py
│   ├── complex_functions.py
│   ├── complex_layers.py
│   └── complex_module.py
├── inference.py
├── plots/
│   ├── code/
│   │   ├── Fig10-Scalability-analysis.py
│   │   ├── Fig11(a)-Cross-domain-Performance-of-augmented-Wi-Fi-sensing.py
│   │   ├── Fig11(b)-In-domain-Performance-of-augmented-Wi-Fi-sensing.py
│   │   ├── Fig12-Impact-of-synthetic-data-volume.py
│   │   ├── Fig13(a)-Performance-of-channel-estimation-amplitude-phase.py
│   │   ├── Fig13(b)-Performance-of-channel-estimation-SNR.py
│   │   ├── Fig6(a)-exp-overall-wifi-ssim.py
│   │   ├── Fig6(b)-exp-overall-wifi-fid.py
│   │   ├── Fig7(a)-exp-overall-fmcw-ssim.py
│   │   ├── Fig7(b)-exp-overall-fmcw-fid.py
│   │   ├── Fig8-Impact-of-diffusion-method.py
│   │   └── Fig9-Impact-of-network-design.py
│   ├── data/
│   │   ├── exp_MIMO.mat
│   │   ├── exp_cross_domain.mat
│   │   ├── exp_impact_diffusion_method.mat
│   │   ├── exp_impact_network_design.mat
│   │   ├── exp_impact_synthetic_data.mat
│   │   ├── exp_in_domain.mat
│   │   ├── exp_mimo_snr.mat
│   │   ├── exp_overall_fid_fmcw.mat
│   │   ├── exp_overall_fid_wifi.mat
│   │   ├── exp_overall_ssim_fmcw.mat
│   │   ├── exp_overall_ssim_wifi.mat
│   │   ├── exp_scalability_analysis.mat
│   │   ├── untitled.asv
│   │   └── untitled.m
│   └── requirements.txt
├── tfdiff/
│   ├── __init__.py
│   ├── dataset.py
│   ├── diffusion.py
│   ├── eeg_model.py
│   ├── fmcw_model.py
│   ├── learner.py
│   ├── mimo_model.py
│   ├── params.py
│   └── wifi_model.py
└── train.py
Download .txt
SYMBOL INDEX (339 symbols across 14 files)

FILE: complex/complex_functions.py
  function complex_matmul (line 10) | def complex_matmul(A, B):
  function complex_avg_pool1d (line 20) | def complex_avg_pool1d(input, *args, **kwargs):
  function complex_avg_pool2d (line 26) | def complex_avg_pool2d(input, *args, **kwargs):
  function complex_normalize (line 35) | def complex_normalize(input):
  function complex_leaky_relu (line 45) | def complex_leaky_relu(input, negative_slope):
  function complex_relu (line 48) | def complex_relu(input):
  function complex_sigmoid (line 51) | def complex_sigmoid(input):
  function complex_tanh (line 54) | def complex_tanh(input):
  function complex_opposite (line 57) | def complex_opposite(input):
  function complex_stack (line 60) | def complex_stack(input, dim):
  function _retrieve_elements_from_indices (line 65) | def _retrieve_elements_from_indices(tensor, indices):
  function _retrieve_elements_from_indices3d (line 70) | def _retrieve_elements_from_indices3d(tensor, indices):
  function complex_upsample (line 75) | def complex_upsample(input, size=None, scale_factor=None, mode='nearest',
  function complex_upsample2 (line 87) | def complex_upsample2(input, size=None, scale_factor=None, mode='nearest',
  function complex_max_pool2d (line 102) | def complex_max_pool2d(input,kernel_size, stride=None, padding=0,
  function complex_max_pool3d (line 126) | def complex_max_pool3d(input,kernel_size, stride=None, padding=0,
  function complex_adaptive_avg_pool3d (line 151) | def complex_adaptive_avg_pool3d(input,kernel_size, stride=None, padding=0,
  function complex_dropout (line 176) | def complex_dropout(input, p=0.5, training=True):
  function complex_dropout2d (line 186) | def complex_dropout2d(input, p=0.5, training=True):
  function complex_dropout3d (line 195) | def complex_dropout3d(input, p=0.5, training=True):

FILE: complex/complex_layers.py
  function apply_complex (line 20) | def apply_complex(fr, fi, input, dtype = torch.complex64):
  class ComplexDropout (line 24) | class ComplexDropout(Module):
    method __init__ (line 25) | def __init__(self,p=0.5):
    method forward (line 29) | def forward(self,input):
  class ComplexDropout2d (line 35) | class ComplexDropout2d(Module):
    method __init__ (line 36) | def __init__(self,p=0.5):
    method forward (line 40) | def forward(self,input):
  class ComplexDropout3d (line 46) | class ComplexDropout3d(Module):
    method __init__ (line 47) | def __init__(self,p=0.5):
    method forward (line 51) | def forward(self,input):
  class ComplexMaxPool2d (line 57) | class ComplexMaxPool2d(Module):
    method __init__ (line 59) | def __init__(self,kernel_size, stride= None, padding = 0,
    method forward (line 69) | def forward(self,input):
  class ComplexMaxPool3d (line 75) | class ComplexMaxPool3d(Module):
    method __init__ (line 77) | def __init__(self,kernel_size, stride=None, padding = 0,
    method forward (line 87) | def forward(self,input):
  class ComplexAvgPool2d (line 94) | class ComplexAvgPool2d(Module):
    method __init__ (line 96) | def __init__(self,kernel_size, stride= None, padding = 0,
    method forward (line 106) | def forward(self,input):
  class ComplexReLU (line 113) | class ComplexReLU(Module):
    method forward (line 115) | def forward(self,input):
  class ComplexSigmoid (line 118) | class ComplexSigmoid(Module):
    method forward (line 120) | def forward(self,input):
  class ComplexTanh (line 123) | class ComplexTanh(Module):
    method forward (line 125) | def forward(self,input):
  class ComplexConvTranspose2d (line 128) | class ComplexConvTranspose2d(Module):
    method __init__ (line 130) | def __init__(self,in_channels, out_channels, kernel_size, stride=1, pa...
    method forward (line 141) | def forward(self,input):
  class ComplexConv2d (line 144) | class ComplexConv2d(Module):
    method __init__ (line 146) | def __init__(self,in_channels, out_channels, kernel_size=3, stride=1, ...
    method forward (line 152) | def forward(self,input):
  class ComplexConv3d (line 155) | class ComplexConv3d(Module):
    method __init__ (line 157) | def __init__(self, in_channels, out_channels, kernel_size=3, stride=1,...
    method forward (line 163) | def forward(self,input):
  class ComplexLinear (line 167) | class ComplexLinear(Module):
    method __init__ (line 169) | def __init__(self, in_features, out_features):
    method forward (line 174) | def forward(self, input):
  class NaiveComplexBatchNorm1d (line 178) | class NaiveComplexBatchNorm1d(Module):
    method __init__ (line 182) | def __init__(self, num_features, eps=1e-5, momentum=0.1, affine=True, \
    method forward (line 188) | def forward(self,input):
  class NaiveComplexBatchNorm2d (line 191) | class NaiveComplexBatchNorm2d(Module):
    method __init__ (line 195) | def __init__(self, num_features, eps=1e-5, momentum=0.1, affine=True, \
    method forward (line 201) | def forward(self,input):
  class NaiveComplexBatchNorm3d (line 204) | class NaiveComplexBatchNorm3d(Module):
    method __init__ (line 208) | def __init__(self, num_features, eps=1e-5, momentum=0.1, affine=True, \
    method forward (line 214) | def forward(self,input):
  class NaiveComplexLayerNorm (line 217) | class NaiveComplexLayerNorm(Module):
    method __init__ (line 221) | def __init__(self, normalized_shape, eps=1e-5, elementwise_affine=True):
    method forward (line 226) | def forward(self,input):
  class _ComplexBatchNorm (line 229) | class _ComplexBatchNorm(Module):
    method __init__ (line 231) | def __init__(self, num_features, eps=1e-5, momentum=0.1, affine=True,
    method reset_running_stats (line 257) | def reset_running_stats(self):
    method reset_parameters (line 265) | def reset_parameters(self):
  class ComplexBatchNorm2d (line 272) | class ComplexBatchNorm2d(_ComplexBatchNorm):
    method forward (line 274) | def forward(self, input):
  class ComplexBatchNorm1d (line 345) | class ComplexBatchNorm1d(_ComplexBatchNorm):
    method forward (line 347) | def forward(self, input):
  class ComplexGRUCell (line 419) | class ComplexGRUCell(Module):
    method __init__ (line 424) | def __init__(self, input_length=10, hidden_length=20):
    method reset_gate (line 443) | def reset_gate(self, x, h):
    method update_gate (line 450) | def update_gate(self, x, h):
    method update_component (line 456) | def update_component(self, x, h, r):
    method forward (line 462) | def forward(self, x, h):
  class ComplexBNGRUCell (line 477) | class ComplexBNGRUCell(Module):
    method __init__ (line 482) | def __init__(self, input_length=10, hidden_length=20):
    method reset_gate (line 503) | def reset_gate(self, x, h):
    method update_gate (line 510) | def update_gate(self, x, h):
    method update_component (line 516) | def update_component(self, x, h, r):
    method forward (line 522) | def forward(self, x, h):

FILE: complex/complex_module.py
  function apply_complex (line 9) | def apply_complex(F_r, F_i, X):
  function apply_complex_sep (line 13) | def apply_complex_sep(F_r, F_i, X):
  function complex_mul (line 18) | def complex_mul(X, Y):
  function complex_bmm (line 26) | def complex_bmm(X, Y):
  function complex_softmax (line 34) | def complex_softmax(X):
  function transpose_qkv (line 39) | def transpose_qkv(x, num_heads: int):
  function transpose_output (line 45) | def transpose_output(x, num_heads: int):
  class ComplexDropout (line 51) | class ComplexDropout(nn.Module):
    method __init__ (line 52) | def __init__(self, p=0.5):
    method forward (line 56) | def forward(self, X):
  class ComplexGELU (line 64) | class ComplexGELU(nn.Module):
    method __init__ (line 65) | def __init__(self, approximate='none'):
    method forward (line 70) | def forward(self, X):
  class ComplexSiLU (line 74) | class ComplexSiLU(nn.Module):
    method __init__ (line 75) | def __init__(self):
    method forward (line 80) | def forward(self, X):
  class ComplexReLU (line 84) | class ComplexReLU(nn.Module):
    method __init__ (line 85) | def __init__(self):
    method forward (line 90) | def forward(self, X):
  class ComplexAvgPool3d (line 94) | class ComplexAvgPool3d(nn.Module):
    method __init__ (line 95) | def __init__(self, kernel_size, stride, padding):
    method forward (line 104) | def forward(self, X):
  class ComplexFlatten (line 108) | class ComplexFlatten(nn.Module):
    method __init__ (line 109) | def __init__(self, start_dim=1, end_dim=-1):
    method forward (line 114) | def forward(self, X):
  class NaiveComplexBatchNorm3d (line 118) | class NaiveComplexBatchNorm3d(nn.Module):
    method __init__ (line 119) | def __init__(
    method forward (line 135) | def forward(self, X):
  class NaiveComplexLayerNorm (line 139) | class NaiveComplexLayerNorm(nn.Module):
    method __init__ (line 140) | def __init__(self, normalized_shape, eps=1e-5, elementwise_affine=True):
    method forward (line 145) | def forward(self, X):
  class ComplexLinear (line 149) | class ComplexLinear(nn.Module):
    method __init__ (line 150) | def __init__(self, in_features, out_features, bias=True):
    method forward (line 155) | def forward(self, X):
  class ComplexMLP (line 159) | class ComplexMLP(nn.Module):
    method __init__ (line 160) | def __init__(self, in_features, hidden_features=None, out_features=Non...
    method forward (line 170) | def forward(self, x):
  class ComplexConv3d (line 178) | class ComplexConv3d(nn.Module):
    method __init__ (line 179) | def __init__(self, input_channels, num_channels, kernel_size, padding,...
    method forward (line 198) | def forward(self, X):
  class ComplexResidual3d (line 202) | class ComplexResidual3d(nn.Module):
    method __init__ (line 203) | def __init__(self, input_channels, num_channels, kernel_size, padding,...
    method forward (line 227) | def forward(self, X):
  class ComplexSegment (line 234) | class ComplexSegment(nn.Module):
    method __init__ (line 235) | def __init__(self, input_channels, seg_channels, seg_size):
    method forward (line 246) | def forward(self, X):
  class Complex2Real (line 253) | class Complex2Real(nn.Module):
    method __init__ (line 254) | def __init__(self):
    method forward (line 259) | def forward(self, X):
  class ComplexDotProductAttention (line 265) | class ComplexDotProductAttention(nn.Module):
    method __init__ (line 271) | def __init__(self, dropout, **kwargs):
    method forward (line 275) | def forward(self, queries, keys, values):
  class ComplexMultiHeadAttention (line 284) | class ComplexMultiHeadAttention(nn.Module):
    method __init__ (line 285) | def __init__(
    method forward (line 306) | def forward(self, queries, keys, values):
  class ComplexPositionalEncoding (line 316) | class ComplexPositionalEncoding(nn.Module):
    method __init__ (line 317) | def __init__(self, hidden_dim, dropout, max_len=10000):
    method forward (line 328) | def forward(self, X):
  class PositionWiseFFN (line 334) | class PositionWiseFFN(nn.Module):
    method __init__ (line 335) | def __init__(self, input_dim, hidden_dim, output_dim, **kwargs):
    method forward (line 341) | def forward(self, X):
  class ComplexAddNorm (line 346) | class ComplexAddNorm(nn.Module):
    method __init__ (line 347) | def __init__(self, normalized_shape, dropout, **kwargs):
    method forward (line 352) | def forward(self, X, Y):
  class ComplexEncoderBlock (line 357) | class ComplexEncoderBlock(nn.Module):
    method __init__ (line 358) | def __init__(
    method forward (line 380) | def forward(self, X):
  class ComplexTransformerEncoder (line 386) | class ComplexTransformerEncoder(nn.Module):
    method __init__ (line 387) | def __init__(
    method forward (line 423) | def forward(self, X, *args):

FILE: inference.py
  function gaussian (line 31) | def gaussian(window_size: int, tfdiff: float):
  function create_window (line 37) | def create_window(height: int, width: int):
  function eval_ssim (line 45) | def eval_ssim(pred, data, height, width, device):
  function cal_SNR_EEG (line 61) | def cal_SNR_EEG(predict, truth):
  function cal_SNR_MIMO (line 71) | def cal_SNR_MIMO(predict, truth):
  function save (line 84) | def save(out_dir, data, cond, batch, index=0):
  function save_mimo (line 93) | def save_mimo(out_dir, data, pred, cond, batch, index=0):
  function save_wifi (line 133) | def save_wifi(out_dir, data, pred, cond, batch, index=0):
  function save_fmcw (line 188) | def save_fmcw(out_dir, data, pred, cond, batch,index=0):
  function print_fid (line 251) | def print_fid(out_dir,data_dir,task_id):
  function main (line 265) | def main(args):

FILE: plots/code/Fig13(b)-Performance-of-channel-estimation-SNR.py
  function read_data_from_txt (line 8) | def read_data_from_txt(filename):

FILE: tfdiff/dataset.py
  function _nested_map (line 20) | def _nested_map(struct, map_fn):
  class WiFiDataset (line 30) | class WiFiDataset(torch.utils.data.Dataset):
    method __init__ (line 31) | def __init__(self, paths):
    method __len__ (line 37) | def __len__(self):
    method __getitem__ (line 40) | def __getitem__(self, idx):
  class FMCWDataset (line 52) | class FMCWDataset(torch.utils.data.Dataset):
    method __init__ (line 53) | def __init__(self, paths):
    method __len__ (line 59) | def __len__(self):
    method __getitem__ (line 62) | def __getitem__(self, idx):
  class MIMODataset (line 72) | class MIMODataset(torch.utils.data.Dataset):
    method __init__ (line 73) | def __init__(self, paths):
    method __len__ (line 79) | def __len__(self):
    method __getitem__ (line 82) | def __getitem__(self,idx):
  class EEGDataset (line 92) | class EEGDataset(torch.utils.data.Dataset):
    method __init__ (line 93) | def __init__(self, paths):
    method __len__ (line 99) | def __len__(self):
    method __getitem__ (line 102) | def __getitem__(self,idx):
  class Collator (line 112) | class Collator:
    method __init__ (line 113) | def __init__(self, params):
    method collate (line 116) | def collate(self, minibatch):
  function from_path (line 195) | def from_path(params, is_distributed=False):
  function from_path_inference (line 220) | def from_path_inference(params):

FILE: tfdiff/diffusion.py
  class SignalDiffusion (line 6) | class SignalDiffusion(nn.Module):
    method __init__ (line 7) | def __init__(self, params):
    method get_kernel (line 28) | def get_kernel(self, var_kernel):
    method get_noise_weights (line 34) | def get_noise_weights(self):
    method get_noise_weights_stats (line 50) | def get_noise_weights_stats(self):
    method get_noise_weights_div (line 58) | def get_noise_weights_div(self):
    method get_noise_weights_prod (line 69) | def get_noise_weights_prod(self):
    method degrade_fn (line 82) | def degrade_fn(self, x_0, t, task_id):
    method sampling (line 97) | def sampling(self, restore_fn, cond, device):
    method robust_sampling (line 121) | def robust_sampling(self, restore_fn, cond, device):
    method fast_sampling (line 144) | def fast_sampling(self, restore_fn, cond, device):
    method native_sampling (line 159) | def native_sampling(self, restore_fn, data, cond, device):
  class GaussianDiffusion (line 169) | class GaussianDiffusion(nn.Module):
    method __init__ (line 170) | def __init__(self, params):
    method degrade_fn (line 183) | def degrade_fn(self, x_0, t):
    method sampling (line 192) | def sampling(self, restore_fn, cond, device):
    method robust_sampling (line 206) | def robust_sampling(self, restore_fn, cond, device):
    method fast_sampling (line 220) | def fast_sampling(self, restore_fn, cond, device):
    method native_sampling (line 232) | def native_sampling(self, restore_fn, data, cond, device):

FILE: tfdiff/eeg_model.py
  function init_weight_norm (line 11) | def init_weight_norm(module):
  function init_weight_zero (line 18) | def init_weight_zero(module):
  function init_weight_xavier (line 25) | def init_weight_xavier(module):
  function modulate (line 33) | def modulate(x, shift, scale):
  class DiffusionEmbedding (line 37) | class DiffusionEmbedding(nn.Module):
    method __init__ (line 38) | def __init__(self, max_step, embed_dim=256, hidden_dim=256):
    method forward (line 50) | def forward(self, t):
    method _lerp_embedding (line 57) | def _lerp_embedding(self, t):
    method _build_embedding (line 64) | def _build_embedding(self, max_step, embed_dim):
  class MLPConditionEmbedding (line 74) | class MLPConditionEmbedding(nn.Module):
    method __init__ (line 75) | def __init__(self, cond_dim, hidden_dim=256):
    method forward (line 86) | def forward(self, c):
  class PositionEmbedding (line 89) | class PositionEmbedding(nn.Module):
    method __init__ (line 90) | def __init__(self, max_len, input_dim, hidden_dim):
    method forward (line 97) | def forward(self, x):
    method _build_embedding (line 101) | def _build_embedding(self, max_len, hidden_dim):
  class CDiTBlock (line 110) | class CDiTBlock(nn.Module):
    method __init__ (line 111) | def __init__(self, hidden_dim, num_heads, dropout, mlp_ratio=4.0, **bl...
    method forward (line 130) | def forward(self, x, c):
  class FinalLayer (line 144) | class FinalLayer(nn.Module):
    method __init__ (line 145) | def __init__(self, hidden_dim, out_dim):
    method forward (line 156) | def forward(self, x, c):
  class tfdiff_eeg (line 163) | class tfdiff_eeg(nn.Module):
    method __init__ (line 164) | def __init__(self, params):
    method forward (line 186) | def forward(self, x, t, c):

FILE: tfdiff/fmcw_model.py
  function init_weight_norm (line 11) | def init_weight_norm(module):
  function init_weight_zero (line 18) | def init_weight_zero(module):
  function init_weight_xavier (line 25) | def init_weight_xavier(module):
  function modulate (line 33) | def modulate(x, shift, scale):
  class DiffusionEmbedding (line 37) | class DiffusionEmbedding(nn.Module):
    method __init__ (line 38) | def __init__(self, max_step, embed_dim=256, hidden_dim=256):
    method forward (line 50) | def forward(self, t):
    method _lerp_embedding (line 57) | def _lerp_embedding(self, t):
    method _build_embedding (line 64) | def _build_embedding(self, max_step, embed_dim):
  class MLPConditionEmbedding (line 74) | class MLPConditionEmbedding(nn.Module):
    method __init__ (line 75) | def __init__(self, cond_dim, hidden_dim=256):
    method forward (line 86) | def forward(self, c):
  class PositionEmbedding (line 90) | class PositionEmbedding(nn.Module):
    method __init__ (line 91) | def __init__(self, max_len, input_dim, hidden_dim):
    method forward (line 98) | def forward(self, x):
    method _build_embedding (line 102) | def _build_embedding(self, max_len, hidden_dim):
  class DiA (line 111) | class DiA(nn.Module):
    method __init__ (line 112) | def __init__(self, hidden_dim, num_heads, dropout, mlp_ratio=4.0, **bl...
    method forward (line 133) | def forward(self, x, c):
  class FinalLayer (line 154) | class FinalLayer(nn.Module):
    method __init__ (line 155) | def __init__(self, hidden_dim, out_dim):
    method forward (line 166) | def forward(self, x, c):
  class tfdiff_fmcw (line 320) | class tfdiff_fmcw(nn.Module):
    method __init__ (line 321) | def __init__(self, params):
    method forward (line 343) | def forward(self, x, t, c):

FILE: tfdiff/learner.py
  class tfdiffLoss (line 11) | class tfdiffLoss(nn.Module):
    method __init__ (line 12) | def __init__(self, w=0.1):
    method forward (line 16) | def forward(self, target, est, target_noise=None, est_noise=None):
    method complex_mse_loss (line 24) | def complex_mse_loss(self, target, est):
  class tfdiffLearner (line 30) | class tfdiffLearner:
    method __init__ (line 31) | def __init__(self, log_dir, model_dir, model, dataset, optimizer, para...
    method state_dict (line 58) | def state_dict(self):
    method load_state_dict (line 70) | def load_state_dict(self, state_dict):
    method save_to_checkpoint (line 78) | def save_to_checkpoint(self, filename='weights'):
    method restore_from_checkpoint (line 90) | def restore_from_checkpoint(self, filename='weights'):
    method train (line 98) | def train(self, max_iter=None):
    method train_iter (line 121) | def train_iter(self, features):
    method _write_summary (line 140) | def _write_summary(self, iter, features, loss):

FILE: tfdiff/mimo_model.py
  function init_weight_norm (line 11) | def init_weight_norm(module):
  function init_weight_zero (line 18) | def init_weight_zero(module):
  function init_weight_xavier (line 25) | def init_weight_xavier(module):
  function modulate (line 33) | def modulate(x, shift, scale):
  class DiffusionEmbedding (line 37) | class DiffusionEmbedding(nn.Module):
    method __init__ (line 38) | def __init__(self, max_step, embed_dim=256, hidden_dim=256):
    method forward (line 50) | def forward(self, t):
    method _lerp_embedding (line 57) | def _lerp_embedding(self, t):
    method _build_embedding (line 64) | def _build_embedding(self, max_step, embed_dim):
  class MLPConditionEmbedding (line 74) | class MLPConditionEmbedding(nn.Module):
    method __init__ (line 75) | def __init__(self, cond_dim, hidden_dim=256):
    method forward (line 86) | def forward(self, c):
  class PositionEmbedding (line 90) | class PositionEmbedding(nn.Module):
    method __init__ (line 91) | def __init__(self, max_len, input_dim, hidden_dim):
    method forward (line 98) | def forward(self, x):
    method _build_embedding (line 102) | def _build_embedding(self, max_len, hidden_dim):
  class DiA (line 111) | class DiA(nn.Module):
    method __init__ (line 112) | def __init__(self, hidden_dim, num_heads, dropout, mlp_ratio=4.0, **bl...
    method forward (line 139) | def forward(self, x, t, c):
  class FinalLayer (line 162) | class FinalLayer(nn.Module):
    method __init__ (line 163) | def __init__(self, hidden_dim, out_dim):
    method forward (line 174) | def forward(self, x, t):
  class SpatialDiffusion (line 181) | class SpatialDiffusion(nn.Module):
    method __init__ (line 193) | def __init__(self, params):
    method forward (line 226) | def forward(self, x, t, c):
  class TimeFrequencyDiffusion (line 236) | class TimeFrequencyDiffusion(nn.Module):
    method __init__ (line 248) | def __init__(self, params):
    method forward (line 274) | def forward(self, x, t, c):
  class tfdiff_mimo (line 285) | class tfdiff_mimo(nn.Module):
    method __init__ (line 297) | def __init__(self, params):
    method forward (line 309) | def forward(self, x, t, c):

FILE: tfdiff/params.py
  class AttrDict (line 4) | class AttrDict(dict):
    method __init__ (line 5) | def __init__(self, *args, **kwargs):
    method override (line 9) | def override(self, attrs):

FILE: tfdiff/wifi_model.py
  function init_weight_norm (line 11) | def init_weight_norm(module):
  function init_weight_zero (line 18) | def init_weight_zero(module):
  function init_weight_xavier (line 25) | def init_weight_xavier(module):
  function modulate (line 33) | def modulate(x, shift, scale):
  class DiffusionEmbedding (line 37) | class DiffusionEmbedding(nn.Module):
    method __init__ (line 38) | def __init__(self, max_step, embed_dim=256, hidden_dim=256):
    method forward (line 50) | def forward(self, t):
    method _lerp_embedding (line 57) | def _lerp_embedding(self, t):
    method _build_embedding (line 64) | def _build_embedding(self, max_step, embed_dim):
  class MLPConditionEmbedding (line 74) | class MLPConditionEmbedding(nn.Module):
    method __init__ (line 75) | def __init__(self, cond_dim, hidden_dim=256):
    method forward (line 86) | def forward(self, c):
  class PositionEmbedding (line 90) | class PositionEmbedding(nn.Module):
    method __init__ (line 91) | def __init__(self, max_len, input_dim, hidden_dim):
    method forward (line 98) | def forward(self, x):
    method _build_embedding (line 102) | def _build_embedding(self, max_len, hidden_dim):
  class DiA (line 111) | class DiA(nn.Module):
    method __init__ (line 112) | def __init__(self, hidden_dim, num_heads, dropout, mlp_ratio=4.0, **bl...
    method forward (line 133) | def forward(self, x, c):
  class FinalLayer (line 154) | class FinalLayer(nn.Module):
    method __init__ (line 155) | def __init__(self, hidden_dim, out_dim):
    method forward (line 166) | def forward(self, x, c):
  class tfdiff_WiFi (line 320) | class tfdiff_WiFi(nn.Module):
    method __init__ (line 321) | def __init__(self, params):
    method forward (line 343) | def forward(self, x, t, c):

FILE: train.py
  function _get_free_port (line 18) | def _get_free_port():
  function _train_impl (line 23) | def _train_impl(replica_id, model, dataset, params):
  function train (line 31) | def train(params):
  function train_distributed (line 42) | def train_distributed(replica_id, replica_count, port, params):
  function main (line 64) | def main(args):
Condensed preview — 44 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (259K chars).
[
  {
    "path": "LICENSE",
    "chars": 35149,
    "preview": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free "
  },
  {
    "path": "README.md",
    "chars": 12569,
    "preview": "# Artifact for MobiCom'24: RF-Diffusion: Radio Signal Generation via Time-Frequency Diffusion\r\n[![License: GPL v3](https"
  },
  {
    "path": "complex/__init__.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "complex/complex_functions.py",
    "chars": 9259,
    "preview": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\n@author: spopoff\n\"\"\"\nimport torch\nfrom torch.nn.functional import re"
  },
  {
    "path": "complex/complex_layers.py",
    "chars": 21686,
    "preview": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Mar 19 10:30:02 2019\n\n@author: Sebastien M. Popoff\n\n\nB"
  },
  {
    "path": "complex/complex_module.py",
    "chars": 13792,
    "preview": "import torch\nimport torch.nn as nn\nfrom torch.nn import functional as F\n\nimport numpy as np\nimport math\n\n\ndef apply_comp"
  },
  {
    "path": "inference.py",
    "chars": 16562,
    "preview": "import math\nimport numpy as np\nimport os\nimport torch\nimport scipy.io as scio\nimport matplotlib.pyplot as plt\nimport num"
  },
  {
    "path": "plots/code/Fig10-Scalability-analysis.py",
    "chars": 4759,
    "preview": "import numpy as np\r\nfrom matplotlib.font_manager import FontProperties\r\nfrom matplotlib.backends.backend_pdf import PdfP"
  },
  {
    "path": "plots/code/Fig11(a)-Cross-domain-Performance-of-augmented-Wi-Fi-sensing.py",
    "chars": 3579,
    "preview": "import numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.ticker as mtick\r\nfrom matplotlib.ticker import Ma"
  },
  {
    "path": "plots/code/Fig11(b)-In-domain-Performance-of-augmented-Wi-Fi-sensing.py",
    "chars": 3577,
    "preview": "import numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.ticker as mtick\r\nfrom matplotlib.ticker import Ma"
  },
  {
    "path": "plots/code/Fig12-Impact-of-synthetic-data-volume.py",
    "chars": 2399,
    "preview": "import numpy as np\r\nfrom matplotlib.font_manager import FontProperties\r\nfrom matplotlib.backends.backend_pdf import PdfP"
  },
  {
    "path": "plots/code/Fig13(a)-Performance-of-channel-estimation-amplitude-phase.py",
    "chars": 2199,
    "preview": "import matplotlib.pyplot as plt\nimport numpy as np\nimport scipy.io as scio\nfrom matplotlib.font_manager import FontPrope"
  },
  {
    "path": "plots/code/Fig13(b)-Performance-of-channel-estimation-SNR.py",
    "chars": 4307,
    "preview": "import matplotlib.pyplot as plt\r\nimport matplotlib.font_manager as fm\r\nimport numpy as np\r\nfrom matplotlib.font_manager "
  },
  {
    "path": "plots/code/Fig6(a)-exp-overall-wifi-ssim.py",
    "chars": 2572,
    "preview": "import numpy as np\r\nfrom matplotlib.font_manager import FontProperties\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib"
  },
  {
    "path": "plots/code/Fig6(b)-exp-overall-wifi-fid.py",
    "chars": 2566,
    "preview": "import numpy as np\r\nfrom matplotlib.font_manager import FontProperties\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib"
  },
  {
    "path": "plots/code/Fig7(a)-exp-overall-fmcw-ssim.py",
    "chars": 2570,
    "preview": "import numpy as np\r\nfrom matplotlib.font_manager import FontProperties\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib"
  },
  {
    "path": "plots/code/Fig7(b)-exp-overall-fmcw-fid.py",
    "chars": 2791,
    "preview": "import numpy as np\r\nfrom matplotlib.font_manager import FontProperties\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib"
  },
  {
    "path": "plots/code/Fig8-Impact-of-diffusion-method.py",
    "chars": 2555,
    "preview": "import numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.ticker as mtick\r\nfrom matplotlib.ticker import Ma"
  },
  {
    "path": "plots/code/Fig9-Impact-of-network-design.py",
    "chars": 2535,
    "preview": "import numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.ticker as mtick\r\nfrom matplotlib.ticker import Ma"
  },
  {
    "path": "plots/data/untitled.asv",
    "chars": 202,
    "preview": "ssim_mean = [0.8064, 0.7135, 0.4391];\nssim_std = [0.1128, 0.1547, 0.1958];\n\nfsd_mean = [4.417, 7.534, 14.72];\nfsd_std = "
  },
  {
    "path": "plots/data/untitled.m",
    "chars": 18845,
    "preview": "mimo = [28.203256130218506,29.796597957611084,26.367104053497314,27.574849128723145,28.815438747406006,28.87958526611328"
  },
  {
    "path": "plots/requirements.txt",
    "chars": 22,
    "preview": "matplotlib\nscipy\nnumpy"
  },
  {
    "path": "tfdiff/__init__.py",
    "chars": 0,
    "preview": ""
  },
  {
    "path": "tfdiff/dataset.py",
    "chars": 8259,
    "preview": "import numpy as np\nimport os\nimport random\nimport torch\nimport torch.nn.functional as F\nimport scipy.io as scio\nfrom tfd"
  },
  {
    "path": "tfdiff/diffusion.py",
    "chars": 15759,
    "preview": "import numpy as np\nimport torch\nfrom torch import nn\nfrom torch.nn import functional as F\n\nclass SignalDiffusion(nn.Modu"
  },
  {
    "path": "tfdiff/eeg_model.py",
    "chars": 7180,
    "preview": "import math\nfrom math import sqrt\nimport numpy as np\nimport torch\nfrom torch import nn\nfrom torch.nn import functional a"
  },
  {
    "path": "tfdiff/fmcw_model.py",
    "chars": 12915,
    "preview": "import math\nfrom math import sqrt\nimport numpy as np\nimport torch\nfrom torch import nn\nfrom torch.nn import functional a"
  },
  {
    "path": "tfdiff/learner.py",
    "chars": 6258,
    "preview": "import numpy as np\nimport os\nimport torch\nimport torch.nn as nn\nfrom torch.utils.tensorboard import SummaryWriter\nfrom t"
  },
  {
    "path": "tfdiff/mimo_model.py",
    "chars": 11535,
    "preview": "import math\nfrom math import sqrt\nimport numpy as np\nimport torch\nfrom torch import nn\nfrom torch.nn import functional a"
  },
  {
    "path": "tfdiff/params.py",
    "chars": 5346,
    "preview": "import numpy as np\n\n\nclass AttrDict(dict):\n    def __init__(self, *args, **kwargs):\n        super(AttrDict, self).__init"
  },
  {
    "path": "tfdiff/wifi_model.py",
    "chars": 12914,
    "preview": "import math\nfrom math import sqrt\nimport numpy as np\nimport torch\nfrom torch import nn\nfrom torch.nn import functional a"
  },
  {
    "path": "train.py",
    "chars": 4168,
    "preview": "import os\n\nimport torch\nfrom torch.cuda import device_count\nfrom torch.multiprocessing import spawn\nfrom torch.nn.parall"
  }
]

// ... and 12 more files (download for full content)

About this extraction

This page contains the full source code of the mobicom24/RF-Diffusion GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 44 files (243.0 KB), approximately 69.0k tokens, and a symbol index with 339 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!