public repository of the uncongeniality_analysis. Initial publication

This commit is contained in:
Orihara Izaya 2024-07-22 09:51:10 +02:00
commit f2bb63be67
159 changed files with 9611 additions and 0 deletions

16
.gitignore vendored Normal file
View File

@ -0,0 +1,16 @@
# PyCharm IDE
.idea/
*.iml
# Byte-compiled / optimized / DLL files
__pycache__/
# Environments
.env
.venv
env/
venv/
ENV/
# Logfiles
.log

331
LICENSE Normal file
View File

@ -0,0 +1,331 @@
uncongeniality_analysis source code is provided under the GPLv3 license.
*************************************************************************************
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright © 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.
*************************************************************************************
Creative Commons Attribution-NonCommercial 4.0 International Public License
By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-NonCommercial 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions.
Section 1 Definitions.
Adapted Material means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image.
Adapter's License means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License.
Copyright and Similar Rights means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights.
Effective Technological Measures means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements.
Exceptions and Limitations means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material.
Licensed Material means the artistic or literary work, database, or other material to which the Licensor applied this Public License.
Licensed Rights means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license.
Licensor means the individual(s) or entity(ies) granting rights under this Public License.
NonCommercial means not primarily intended for or directed towards commercial advantage or monetary compensation. For purposes of this Public License, the exchange of the Licensed Material for other material subject to Copyright and Similar Rights by digital file-sharing or similar means is NonCommercial provided there is no payment of monetary compensation in connection with the exchange.
Share means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them.
Sui Generis Database Rights means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world.
You means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning.
Section 2 Scope.
License grant. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to:
reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and
produce, reproduce, and Share Adapted Material for NonCommercial purposes only.
Exceptions and Limitations. For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions.
Term. The term of this Public License is specified in Section 6(a).
Media and formats; technical modifications allowed. The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material.
Downstream recipients.
Offer from the Licensor Licensed Material. Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License.
No downstream restrictions. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material.
No endorsement. Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i).
Other rights. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise.
Patent and trademark rights are not licensed under this Public License.
To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties, including when the Licensed Material is used other than for NonCommercial purposes.
Section 3 License Conditions.
Your exercise of the Licensed Rights is expressly made subject to the following conditions.
Attribution. If You Share the Licensed Material (including in modified form), You must:
retain the following if it is supplied by the Licensor with the Licensed Material:
identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated);
a copyright notice;
a notice that refers to this Public License;
a notice that refers to the disclaimer of warranties;
a URI or hyperlink to the Licensed Material to the extent reasonably practicable;
indicate if You modified the Licensed Material and retain an indication of any previous modifications; and
indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License.
You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information.
If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable.
If You Share Adapted Material You produce, the Adapter's License You apply must not prevent recipients of the Adapted Material from complying with this Public License.
Section 4 Sui Generis Database Rights.
Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material: for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database for NonCommercial purposes only; if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material; and You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database.
For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights.
Section 5 Disclaimer of Warranties and Limitation of Liability.
Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You.
To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You.
The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability.
Section 6 Term and Termination.
This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically.
Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates:
automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or
upon express reinstatement by the Licensor.
For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License.
For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License.
Sections 1, 5, 6, 7, and 8 survive termination of this Public License.
Section 7 Other Terms and Conditions.
The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed.
Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License.
Section 8 Interpretation.
For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License.
To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions.
No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor.
Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority.

120
README.md Normal file
View File

@ -0,0 +1,120 @@
# uncongeniality_analysis
## Project Contributors
This analysis project has been executed by Gerrit Anders and Jürgen Buder from IWM Tuebingen.
For project-related queries, please contact Gerrit Anders at g.anders@iwm-tuebingen.de.
## Project Overview
This repository host a general data analysis framework employed to investigate reply behaviour and polarization in the
comment section of "Spiegel Online" (SPON). The research, focuses on understanding uncongeniality within a large
online sample and examining polarization in online discussions.
The dataset for analysis can be found on the [Open Science Framework](https://osf.io/t6eph).
## Setup
To set up the analysis, follow the steps below:
### Clone the Repository
```bash
git clone --branch public https://gitea.iwm-tuebingen.de/ganders/project_SPON1_code.git
```
### Install non-python prerequisites
In order to run the analysis R needs to be installed. The analysis was conducted using R version 4.1.1.
Please install R from the [official website](https://cran.r-project.org/).
In addition, development tools is recommended. This can be done via apt-get on Linux systems:
```bash
sudo apt-get update
sudo apt-get install build-essential
```
Furthermore, to enable the generation of pdf reports, pandoc and texlive needs to be installed.
pandoc installation can be done via apt-get on Linux systems:
```bash
sudo apt-get install pandoc
sudo apt-get install texlive-latex-recommended
```
The code runs without these functionalities if in the config file the pdf flag is set to false.
Please note that the markdown versions of result reports use relative paths to images,
thus they will only display those while being in the `results_reports` folder (in contrast to pdf reports)
### Install requirements
The code was tested under python 3.10.2.
It is recommended to run the code in a virtual environment. To create a virtual environment, run the following commands:
```bash
python3 -m venv venv
source venv/bin/activate
```
To install the required python packages, run:
```bash
pip3 install -r requirements.txt
```
## Running analysis
To run analysis with these frameworks one needs to adapt the configuration file `config.yaml` to the desired settings.
Adapt the `data_path` to the directory in which the dataset that is available on the
[Open Science Framework](https://osf.io/t6eph) is stored.
To replicate the analysis provided in "Polarizing reply patterns in comment sections of a large German news outlet"
all other settings can be unchanged.
The analysis can be run by executing the following command:
```bash
python3 main.py
```
### Configuring analysis
This framework allows to run a wide range of analyses on a dataset or subsets by defining analysis jobs as yaml files.
Such files consist of four parts:
- `preprocessing`: defines all subsets of the dataset that will be targeted in the analysis
- `descriptive`: defines all descriptive analyses that will be conducted
- `analysis`: defines all other analysis jobs that will be conducted (e.g. regression, correlation, etc.)
- `visualizations`: defines all visualizations that will be created (e.g. histograms, scatterplots, etc.)
Examples for all supported analysis and their arguments can be found in the `analysis_config_templates` folder.
The general structure of an analysis job consists of a tag that names the analysis followed by a list of arguments.
The `name` argument is mandatory and is used for identification and naming of the output files.
Please note that `dataset` argument refers to the names of the datasets in preprocessing. Some other analysis
(e.g. forest plots) require addition information referring to specific models also defined in the analysis job.
### Output
An analysis job creates three types of outputs:
- A markdown report in the `results_reports` folder which for each analysis give the settings of the analysis and the result
- A pdf report in the `results_reports` folder which is the conversion of the pdf (that can be shared)
- For each analysis a file in the `results` folder that contains the results of the analysis and is named the same as the result
### Contributing: Extending the framework
If you want to extend the framework with new analysis, you can do so by following these steps:
- Fork the repository
- add your analysis function class to the `analysis_functions` folder
- write a wrapper function for your analysis that takes a list of job arguments and calls the analysis.
- add the wrapper function to the `analysis.py` file and extend it to create a list of analysis jobs for the
newly created analysis type
- create a parameter dataclass in the `data_classes` folder that is inherited from `GeneralParameters`.
- Add your dataclass to the `constructor.py` in order for it to be readable from the job yaml file.
- Extend `utils/helper_logging.py` to log the settings for your analysis in order for them to be documented in the report.
- Either use the extended analysis framework or create a merge request for it to be included in the main repository.
## License
See the LICENSE file for the GNU General Public License v3.0 related details.
## Contact
For queries, feedback, or issue reporting, please e-mail Gerrit Anders at g.anders@iwm-tuebingen.de.

View File

@ -0,0 +1,10 @@
---
analysis:
- !bayesian_regression
name: "Example_bayes_regression"
dataset: "data"
independent_variables:
- 'bayes-corrected (q=0.25) valence'
- 'totalvotes'
dependent_variable: 'number O(n+1)-replies'
...

View File

@ -0,0 +1,8 @@
---
analysis:
- !comparison_variance_in_and_between_group
name: "Example_comparison_variance_in_and_between_group"
dataset: "data"
variable: 'bayes-corrected (q=0.25) variance'
group: 'user_id'
...

View File

@ -0,0 +1,22 @@
---
analysis:
- !linear_regression
name: "Example_linear_regression"
dataset: "data"
independent_variables:
- 'bayes-corrected (q=0.25) valence'
- 'totalvotes'
dependent_variable: 'number O(n+1)-replies'
standardize: false
- !increase_per_up_and_downvote_from_totalvotes_and_valence
name: "Example_increase_per_up_and_downvote"
dataset: "data"
weight_as_distribution_quantile: true
weight_m: 0.25
model_name: "Example_linear_regression"
step:
- 0
- 1
startpoint: "average"
...

View File

@ -0,0 +1,17 @@
---
analysis:
- !linear_regression
name: "Example_linear_regression"
dataset: "data"
independent_variables:
- 'bayes-corrected (q=0.25) valence'
- 'totalvotes'
dependent_variable: 'number O(n+1)-replies'
standardize: false
report_effect_size: false
- !function_inverse_bayes_transformed_regression
name: "function_Example"
dataset: "data"
model_name: "Example_linear_regression"
...

View File

@ -0,0 +1,17 @@
---
analysis:
- !linear_regression_grouped
name: "Example_grouped_linear_regression"
dataset: "data"
independent_variables:
- 'bayes-corrected (q=0.25) valence'
- 'totalvotes'
dependent_variable: 'number O(n+1)-replies'
aggregation_functions:
- 'mean'
- 'sum'
- 'sum'
group_by: 'user_id'
standardize: false
print_detailed_coefficients: true
...

View File

@ -0,0 +1,11 @@
---
analysis:
- !linear_regression
name: "Example_linear_regression"
dataset: "data"
independent_variables:
- 'bayes-corrected (q=0.25) valence'
- 'totalvotes'
dependent_variable: 'number O(n+1)-replies'
standardize: false
...

View File

@ -0,0 +1,8 @@
---
analysis:
- !paired_ttest
name: "Example_paired_ttest"
dataset: "data"
variable_1: 'bayes-corrected (q=0.25) extremity'
variable_2: 'mean bayes-corrected (q=0.25) extremity of replies'
...

View File

@ -0,0 +1,8 @@
---
analysis:
- !pearson_correlation
name: "Example_pearson_correlation"
dataset: "data"
variable_1: 'bayes-corrected (q=0.25) extremity'
variable_2: 'mean bayes-corrected (q=0.25) extremity of replies'
...

View File

@ -0,0 +1,8 @@
---
analysis:
- !ttest
name: "Example_ttest"
dataset: "data"
variable_1: 'bayes-corrected (q=0.25) extremity'
variable_2: 'mean bayes-corrected (q=0.25) extremity of replies'
...

View File

@ -0,0 +1,11 @@
---
descriptive:
- !descriptive_aggregated
name: "Example_overview"
dataset: "data"
variables:
- 'Count'
- 'totalvotes'
aggregation_function: "sum"
group_by: "user_id"
...

View File

@ -0,0 +1,40 @@
---
descriptive:
- !descriptive_overview
name: "Example_overview"
dataset: "data"
group_by: "order"
metrics:
- operation: "count"
column: null
- operation: "sum"
column: "number O(n+1)-replies"
- operation: "count_nonzero"
column: "number O(n+1)-replies"
- operation: "count_nonzero"
column: "totalvotes"
- operation: "sum"
column: "totalvotes"
- operation: "sum"
column: "upvotes"
- operation: "sum"
column: "downvotes"
- operation: "count_nonzero"
column: "totalvotes"
- operation: "mean"
column: "valence"
- operation: "std_dev"
column: "valence"
- operation: "mean"
column: "bayes-corrected (q=0.25) valence"
- operation: "std_dev"
column: "bayes-corrected (q=0.25) valence"
- operation: "mean"
column: "extremity"
- operation: "std_dev"
column: "extremity"
- operation: "mean"
column: "bayes-corrected (q=0.25) extremity"
- operation: "std_dev"
column: "bayes-corrected (q=0.25) extremity"
...

View File

@ -0,0 +1,9 @@
---
descriptive:
- !percentage_of_dataset_under_condition
name: "Example_percentage_of_dataset_under_condition"
dataset: "data"
variable: "totalvotes"
comparison: "smaller"
condition: 10
...

View File

@ -0,0 +1,13 @@
---
visualization:
- !barchart
name: 'Example_barchart'
dataset: "data"
variable_x_axis: 'bayes-corrected (q=0.25) extremity'
variable_y_axis: None
x_axis_label: 'bayes-corrected (q=0.25) extremity'
y_axis_label: 'Count'
chart_orientation: 'h'
sort_order: 'ascending'
title: 'Barchart'
...

View File

@ -0,0 +1,11 @@
---
visualization:
- !boxplot
name: 'Example_boxplot'
dataset: "data"
variable_1: 'bayes-corrected (q=0.25) extremity'
variable_2: 'mean bayes-corrected (q=0.25) extremity of replies'
x_axis_label: ''
y_axis_label: 'Extremity value'
title: 'Box plot comparing bayes-corrected extremity with the mean extremity of replies'
...

View File

@ -0,0 +1,27 @@
---
analysis:
- !linear_regression
name: "Example_linear_regression"
dataset: "data"
independent_variables:
- 'bayes-corrected (q=0.25) valence'
- 'totalvotes'
dependent_variable: 'number O(n+1)-replies'
standardize: false
report_effect_size: false
- !function_inverse_bayes_transformed_regression
name: "function_Example"
dataset: "data"
model_name: "Example_linear_regression"
visualization:
- !contourplot
name: "Example_surfaceplot"
dataset: "data"
function_name: "function_Example"
x_axis_maximum: 20
y_axis_maximum: 20
x_axis_label: "downvotes"
y_axis_label: "upvotes"
...

View File

@ -0,0 +1,15 @@
---
visualization:
- !count_distribution
name: 'Example_count_distribution'
dataset: "data"
variable: 'user_id'
x_axis_label: 'Number of comments'
y_axis_label: 'Number of users'
x_axis_limits:
- 0
- 10
x_axis_logarithmic_scaling: false
y_axis_logarithmic_scaling: false
title: 'Distribution of Comments over Users'
...

View File

@ -0,0 +1,10 @@
---
visualization:
- !densityplot
name: 'Example_densityplot'
dataset: "data"
variable_x_axis: 'bayes-corrected (q=0.25) extremity'
variable_y_axis: 'mean bayes-corrected (q=0.25) extremity of replies'
data_breakpoints:
- 0
...

View File

@ -0,0 +1,37 @@
---
analysis:
- !linear_regression
name: "Example_linear_regression_subset_1"
dataset: "data_subset_1"
independent_variables:
- 'bayes-corrected (q=0.25) valence'
- 'totalvotes'
dependent_variable: 'number O(n+1)-replies'
standardize: true
- !linear_regression
name: "Example_linear_regression_subset_2"
dataset: "data_subset_2"
independent_variables:
- 'bayes-corrected (q=0.25) valence'
- 'totalvotes'
dependent_variable: 'number O(n+1)-replies'
standardize: true
visualization:
- !forestplot:
name: "Example_forestplot"
regression_model_names:
- "Example_linear_regression_subset_1"
- "Example_linear_regression_subset_2"
regression_model_labels:
- "Subset 1"
- "Subset 2"
coefficient_names:
- "bayes-corrected (q=0.25) valence"
- "totalvotes"
x_axis_minimum: 0
dotsize: 5
x_axis_label: "Standardized coefficient (95% Confidence Interval)"
...

View File

@ -0,0 +1,27 @@
---
analysis:
- !paired_ttest
name: "Example_paired_ttest_subset_1"
dataset: "data_subset_1"
variable_1: 'bayes-corrected (q=0.25) extremity'
variable_2: 'mean bayes-corrected (q=0.25) extremity of replies'
- !paired_ttest
name: "Example_paired_ttest_subset_2"
dataset: "data_subset_2"
variable_1: 'bayes-corrected (q=0.25) extremity'
variable_2: 'mean bayes-corrected (q=0.25) extremity of replies'
visualization:
- !forestplot:
name: "Example_forestplot_paired_ttest"
paired_ttest_names:
- "Example_paired_ttest_subset_1"
- "Example_paired_ttest_subset_2"
paired_ttest_labels:
- "Subset 1"
- "Subset 2"
x_axis_minimum: 0
dotsize: 5
x_axis_label: "Mean difference bayes-corrected (q=0.25) extremity (95% Confidence Interval)"
...

View File

@ -0,0 +1,12 @@
---
visualization:
- !grouped_histogram
name: "Example_grouped_histogram"
dataset: "data"
group_by: 'user_id'
aggregation_variable: 'bayes-corrected (q=0.25) valence'
aggregation_function: 'mean'
x_axis_label: 'Valence'
y_axis_label: 'Number of users'
title: 'Histogram of Mean Valence per User'
...

View File

@ -0,0 +1,17 @@
---
visualization:
- !heatmap
name: "Example_heatmap"
dataset: "data"
axis_variables:
- 'bayes-corrected (q=0.25) valence'
- 'totalvotes'
heat_variable: 'number O(n+1)-replies'
axis_maxima:
- 1
- 40
axis_minima:
- 0
- 0
logarithmic_heat_scaling: 'false'
...

View File

@ -0,0 +1,12 @@
---
visualization:
- !hexbinplot
name: "Example_hexbinplot"
dataset: "data"
variable_x_axis: 'bayes-corrected (q=0.25) extremity'
variable_y_axis: 'mean bayes-corrected (q=0.25) extremity of replies'
x_axis_maximum: 1
y_axis_maximum: 1
trendline: false
logarithmic_hex_scaling: false
...

View File

@ -0,0 +1,12 @@
---
visualization:
- !histogram
name: 'Descriptive_histogram_comments_over_totalvotes'
dataset: "data"
variable: 'totalvotes'
x_axis_label: 'Number of total votes'
y_axis_label: 'Number of comments'
x_axis_logarithmic_scaling: false
y_axis_logarithmic_scaling: true
title: ''
...

View File

@ -0,0 +1,14 @@
---
visualization:
- !percentage_stacked_barchart
name: 'Example_percentage_stacked_barchart'
dataset: "data"
variable_x_axis: 'section'
variables_to_compare:
- 'upvotes'
- 'downvotes'
x_axis_label: 'Section'
chart_orientation: 'h'
sort_order: 'ascending'
title: 'Stacked Barchart of Upvotes and Downvotes by Section'
...

View File

@ -0,0 +1,10 @@
---
visualization:
- !ridgelineplot
name: "Example_ridgelineplot"
dataset: "data"
variable_x_axis: 'bayes-corrected (q=0.25) extremity'
variable_y_axis: 'mean bayes-corrected (q=0.25) extremity of replies'
data_breakpoints:
- 0.5
...

View File

@ -0,0 +1,8 @@
---
visualization:
- !simple_scatterplot
name: "Example_simple_scatterplot"
dataset: "data"
variable_x_axis: 'bayes-corrected (q=0.25) extremity'
variable_y_axis: 'mean bayes-corrected (q=0.25) extremity of replies'
...

View File

@ -0,0 +1,14 @@
---
visualization:
- !stacked_barchart
name: 'Example_stacked_barchart'
dataset: "data"
variable_x_axis: 'section'
variable_y_axis: None
x_axis_label: 'section'
y_axis_label: 'Count'
hue: 'order'
chart_orientation: 'h'
sort_order: 'ascending'
title: 'Stacked Barchart of Comments by Section and Order'
...

View File

@ -0,0 +1,31 @@
---
analysis:
- !linear_regression
name: "Example_linear_regression"
dataset: "data"
independent_variables:
- 'bayes-corrected (q=0.25) valence'
- 'totalvotes'
dependent_variable: 'number O(n+1)-replies'
standardize: false
report_effect_size: false
- !function_inverse_bayes_transformed_regression
name: "function_Example"
dataset: "data"
model_name: "Example_linear_regression"
visualization:
- !surfaceplot
name: "Example_surfaceplot"
dataset: "data"
function_name: "function_Example"
x_axis_maximum: 20
y_axis_maximum: 20
x_axis_label: "downvotes"
y_axis_label: "upvotes"
z_axis_label: "replies"
elevation_angle: 45
azimuth_angle: 205
title: 'Effect of up- and downvotes according to example linear regression'
...

View File

@ -0,0 +1,8 @@
---
visualization:
- !violinplot
name: "Example_violinplot"
dataset: "data"
variable_x_axis: 'bayes-corrected (q=0.25) extremity'
variable_y_axis: 'mean bayes-corrected (q=0.25) extremity of replies'
...

View File

@ -0,0 +1,667 @@
---
preprocessing:
data_order0:
- method: data_order
param: 0
data_order1:
- method: data_order
param: 1
data_politics:
- method: data_order
param: 0
- method: data_section
param: 'Politics'
data_foreign_affairs:
- method: data_order
param: 0
- method: data_section
param: 'Foreign affairs'
data_science:
- method: data_order
param: 0
- method: data_section
param: 'Science'
data_economy:
- method: data_order
param: 0
- method: data_section
param: 'Economy'
data_miscellaneous:
- method: data_order
param: 0
- method: data_section
param: 'Miscellaneous'
data_culture:
- method: data_order
param: 0
- method: data_section
param: 'Culture'
data_sports:
- method: data_order
param: 0
- method: data_section
param: 'Sports'
data_mobility:
- method: data_order
param: 0
- method: data_section
param: 'Mobility'
data_internet:
- method: data_order
param: 0
- method: data_section
param: 'Internet'
data_health:
- method: data_order
param: 0
- method: data_section
param: 'Health'
data_order0_with_minimum_one_vote:
- method: data_order
param: 0
- method: exclude_data_with_value
param: {'column': 'totalvotes', 'value': 0}
descriptive:
- !descriptive_overview
name: "Extended_Data_Table_1_Descriptive_Data_for_different_comment_levels"
dataset: "data"
group_by: "order"
metrics:
- operation: "count"
column: null
- operation: "count_nonzero"
column: "totalvotes"
- operation: "sum"
column: "totalvotes"
- operation: "mean"
column: "totalvotes"
- operation: "std_dev"
column: "totalvotes"
- operation: "sum"
column: "upvotes"
- operation: "sum"
column: "downvotes"
- operation: "mean"
column: "bayes-corrected (q=0.25) valence"
- operation: "std_dev"
column: "bayes-corrected (q=0.25) valence"
- operation: "mean"
column: "bayes-corrected (q=0.25) extremity"
- operation: "std_dev"
column: "bayes-corrected (q=0.25) extremity"
- !descriptive_overview
name: "Extended_Data_Table_2_Descriptive_Data_for_different_news_categories"
dataset: "data"
group_by: "section"
metrics:
- operation: "count"
column: null
- operation: "sum"
column: "number O(n+1)-replies"
- operation: "count_nonzero"
column: "number O(n+1)-replies"
- operation: "count_nonzero"
column: "totalvotes"
- operation: "sum"
column: "totalvotes"
- operation: "sum"
column: "upvotes"
- operation: "sum"
column: "downvotes"
- operation: "count_nonzero"
column: "totalvotes"
- operation: "mean"
column: "valence"
- operation: "std_dev"
column: "valence"
- operation: "mean"
column: "bayes-corrected (q=0.25) valence"
- operation: "std_dev"
column: "bayes-corrected (q=0.25) valence"
- operation: "mean"
column: "extremity"
- operation: "std_dev"
column: "extremity"
- operation: "mean"
column: "bayes-corrected (q=0.25) extremity"
- operation: "std_dev"
column: "bayes-corrected (q=0.25) extremity"
analysis:
- !linear_regression
name: "Evidence_uncongeniality_simplest_model_linear_regression_only_valence_non_standardized"
dataset: "data_order0"
independent_variables:
- 'valence'
dependent_variable: 'number O(n+1)-replies'
standardize: false
report_effect_size: true
- !linear_regression
name: "Evidence_uncongeniality_preregistered_model"
dataset: "data_order0"
independent_variables:
- 'bayes-corrected (q=0.25) valence'
- 'totalvotes'
dependent_variable: 'number O(n+1)-replies'
standardize: true
report_effect_size: true
- !linear_regression
name: "Evidence_uncongeniality_stability_against_variation_in_weight_q5"
dataset: "data_order0"
independent_variables:
- 'bayes-corrected (q=0.5) valence'
- 'totalvotes'
dependent_variable: 'number O(n+1)-replies'
standardize: true
- !linear_regression
name: "Evidence_uncongeniality_stability_against_variation_in_weight_q75"
dataset: "data_order0"
independent_variables:
- 'bayes-corrected (q=0.75) valence'
- 'totalvotes'
dependent_variable: 'number O(n+1)-replies'
standardize: true
- !linear_regression
name: "Evidence_uncongeniality_stability_against_variation_in_weight__no_bayes_correction"
dataset: "data_order0"
independent_variables:
- 'valence'
- 'totalvotes'
dependent_variable: 'number O(n+1)-replies'
standardize: true
- !linear_regression_grouped
name: "Evidence_uncongeniality_robustness_analysis_on_person_level"
dataset: "data_order0"
independent_variables:
- 'bayes-corrected (q=0.25) valence'
- 'totalvotes'
dependent_variable: 'number O(n+1)-replies'
aggregation_functions:
- 'mean'
- 'sum'
- 'sum'
group_by: 'user_id'
standardize: true
print_detailed_coefficients: true
- !linear_regression_grouped
name: "Evidence_uncongeniality_robustness_analysis_on_section_level"
dataset: "data_order0"
independent_variables:
- 'bayes-corrected (q=0.25) valence'
- 'totalvotes'
dependent_variable: 'number O(n+1)-replies'
aggregation_functions:
- 'mean'
- 'sum'
- 'sum'
group_by: 'section'
standardize: true
print_detailed_coefficients: true
- !linear_regression
name: "Evidence_uncongenialty_section_politics"
dataset: "data_politics"
independent_variables:
- 'bayes-corrected (q=0.25) valence'
- 'totalvotes'
dependent_variable: 'number O(n+1)-replies'
standardize: true
- !linear_regression
name: "Evidence_uncongenialty_section_affairs"
dataset: "data_foreign_affairs"
independent_variables:
- 'bayes-corrected (q=0.25) valence'
- 'totalvotes'
dependent_variable: 'number O(n+1)-replies'
standardize: true
- !linear_regression
name: "Evidence_uncongenialty_section_science"
dataset: "data_science"
independent_variables:
- 'bayes-corrected (q=0.25) valence'
- 'totalvotes'
dependent_variable: 'number O(n+1)-replies'
standardize: true
- !linear_regression
name: "Evidence_uncongenialty_section_economy"
dataset: "data_economy"
independent_variables:
- 'bayes-corrected (q=0.25) valence'
- 'totalvotes'
dependent_variable: 'number O(n+1)-replies'
standardize: true
- !linear_regression
name: "Evidence_uncongenialty_section_miscellaneous"
dataset: "data_miscellaneous"
independent_variables:
- 'bayes-corrected (q=0.25) valence'
- 'totalvotes'
dependent_variable: 'number O(n+1)-replies'
standardize: true
- !linear_regression
name: "Evidence_uncongenialty_section_culture"
dataset: "data_culture"
independent_variables:
- 'bayes-corrected (q=0.25) valence'
- 'totalvotes'
dependent_variable: 'number O(n+1)-replies'
standardize: true
- !linear_regression
name: "Evidence_uncongenialty_section_sports"
dataset: "data_sports"
independent_variables:
- 'bayes-corrected (q=0.25) valence'
- 'totalvotes'
dependent_variable: 'number O(n+1)-replies'
standardize: true
- !linear_regression
name: "Evidence_uncongenialty_section_mobility"
dataset: "data_mobility"
independent_variables:
- 'bayes-corrected (q=0.25) valence'
- 'totalvotes'
dependent_variable: 'number O(n+1)-replies'
standardize: true
- !linear_regression
name: "Evidence_uncongenialty_section_internet"
dataset: "data_internet"
independent_variables:
- 'bayes-corrected (q=0.25) valence'
- 'totalvotes'
dependent_variable: 'number O(n+1)-replies'
standardize: true
- !linear_regression
name: "Evidence_uncongenialty_section_health"
dataset: "data_health"
independent_variables:
- 'bayes-corrected (q=0.25) valence'
- 'totalvotes'
dependent_variable: 'number O(n+1)-replies'
standardize: true
- !linear_regression
name: "Evidence_uncongeniality_robustness_order1"
dataset: "data_order1"
independent_variables:
- 'bayes-corrected (q=0.25) valence'
- 'totalvotes'
dependent_variable: 'number O(n+1)-replies'
standardize: true
- !linear_regression
name: "Evidence_uncogeniality_model_with_seperate_upvotes_downvotes"
dataset: "data_order0"
independent_variables:
- 'upvotes'
- 'downvotes'
dependent_variable: 'number O(n+1)-replies'
standardize: true
- !linear_regression
name: "Evidence_antagonism_preregistered_model"
dataset: "data_order0"
independent_variables:
- 'mean bayes-corrected (q=0.25) valence of replies'
dependent_variable: 'bayes-corrected (q=0.25) valence'
standardize: true
- !linear_regression
name: "Evidence_antagonism_stability_against_variation_in_weight_q5"
dataset: "data_order0"
independent_variables:
- 'mean bayes-corrected (q=0.5) valence of replies'
dependent_variable: 'bayes-corrected (q=0.5) valence'
standardize: true
- !linear_regression
name: "Evidence_antagonism_stability_against_variation_in_weight_q75"
dataset: "data_order0"
independent_variables:
- 'mean bayes-corrected (q=0.75) valence of replies'
dependent_variable: 'bayes-corrected (q=0.75) valence'
standardize: true
- !linear_regression
name: "Evidence_antagonism_stability_against_variation_in_weight_no_bayes_correction"
dataset: "data_order0"
independent_variables:
- 'mean valence of replies'
dependent_variable: 'valence'
standardize: true
- !linear_regression
name: "Evidence_antagonism_section_politics"
dataset: "data_politics"
independent_variables:
- 'mean bayes-corrected (q=0.25) valence of replies'
dependent_variable: 'bayes-corrected (q=0.25) valence'
standardize: true
- !linear_regression
name: "Evidence_antagonism_section_affairs"
dataset: "data_foreign_affairs"
independent_variables:
- 'mean bayes-corrected (q=0.25) valence of replies'
dependent_variable: 'bayes-corrected (q=0.25) valence'
standardize: true
- !linear_regression
name: "Evidence_antagonism_section_science"
dataset: "data_science"
independent_variables:
- 'mean bayes-corrected (q=0.25) valence of replies'
dependent_variable: 'bayes-corrected (q=0.25) valence'
standardize: true
- !linear_regression
name: "Evidence_antagonism_section_economy"
dataset: "data_economy"
independent_variables:
- 'mean bayes-corrected (q=0.25) valence of replies'
dependent_variable: 'bayes-corrected (q=0.25) valence'
standardize: true
- !linear_regression
name: "Evidence_antagonism_section_miscellaneous"
dataset: "data_miscellaneous"
independent_variables:
- 'mean bayes-corrected (q=0.25) valence of replies'
dependent_variable: 'bayes-corrected (q=0.25) valence'
standardize: true
- !linear_regression
name: "Evidence_antagonism_section_culture"
dataset: "data_culture"
independent_variables:
- 'mean bayes-corrected (q=0.25) valence of replies'
dependent_variable: 'bayes-corrected (q=0.25) valence'
standardize: true
- !linear_regression
name: "Evidence_antagonism_section_sports"
dataset: "data_sports"
independent_variables:
- 'mean bayes-corrected (q=0.25) valence of replies'
dependent_variable: 'bayes-corrected (q=0.25) valence'
standardize: true
- !linear_regression
name: "Evidence_antagonism_section_mobility"
dataset: "data_mobility"
independent_variables:
- 'mean bayes-corrected (q=0.25) valence of replies'
dependent_variable: 'bayes-corrected (q=0.25) valence'
standardize: true
- !linear_regression
name: "Evidence_antagonism_section_internet"
dataset: "data_internet"
independent_variables:
- 'mean bayes-corrected (q=0.25) valence of replies'
dependent_variable: 'bayes-corrected (q=0.25) valence'
standardize: true
- !linear_regression
name: "Evidence_antagonism_section_health"
dataset: "data_health"
independent_variables:
- 'mean bayes-corrected (q=0.25) valence of replies'
dependent_variable: 'bayes-corrected (q=0.25) valence'
standardize: true
- !linear_regression
name: "Evidence_antagonism_robustness_order1"
dataset: "data_order1"
independent_variables:
- 'mean bayes-corrected (q=0.25) valence of replies'
dependent_variable: 'bayes-corrected (q=0.25) valence'
standardize: true
- !paired_ttest
name: "Evidence_polarization_paired_ttest_extremity"
dataset: "data_order0"
variable_1: 'bayes-corrected (q=0.25) extremity'
variable_2: 'mean bayes-corrected (q=0.25) extremity of replies'
- !paired_ttest
name: "Evidence_polarization_stability_against_variation_in_weight_paired_ttest_q5"
dataset: "data_order0"
variable_1: 'bayes-corrected (q=0.5) extremity'
variable_2: 'mean bayes-corrected (q=0.5) extremity of replies'
- !paired_ttest
name: "Evidence_polarization_stability_against_variation_in_weight_paired_ttest_q75"
dataset: "data_order0"
variable_1: 'bayes-corrected (q=0.75) extremity'
variable_2: 'mean bayes-corrected (q=0.75) extremity of replies'
- !paired_ttest
name: "Evidence_polarization_stability_against_variation_in_weight_paired_ttest_bayes"
dataset: "data_order0"
variable_1: 'extremity'
variable_2: 'mean extremity of replies'
- !paired_ttest
name: "Evidence_polarization_robustness_paired_ttest_order1"
dataset: "data_order1"
variable_1: 'bayes-corrected (q=0.25) extremity'
variable_2: 'mean bayes-corrected (q=0.25) extremity of replies'
- !paired_ttest
name: "Evidence_polarization_paired_ttest_extremity_politics"
dataset: "data_politics"
variable_1: 'bayes-corrected (q=0.25) extremity'
variable_2: 'mean bayes-corrected (q=0.25) extremity of replies'
- !paired_ttest
name: "Evidence_polarization_paired_ttest_extremity_foreign_affairs"
dataset: "data_foreign_affairs"
variable_1: 'bayes-corrected (q=0.25) extremity'
variable_2: 'mean bayes-corrected (q=0.25) extremity of replies'
- !paired_ttest
name: "Evidence_polarization_paired_ttest_extremity_science"
dataset: "data_science"
variable_1: 'bayes-corrected (q=0.25) extremity'
variable_2: 'mean bayes-corrected (q=0.25) extremity of replies'
- !paired_ttest
name: "Evidence_polarization_paired_ttest_extremity_economy"
dataset: "data_economy"
variable_1: 'bayes-corrected (q=0.25) extremity'
variable_2: 'mean bayes-corrected (q=0.25) extremity of replies'
- !paired_ttest
name: "Evidence_polarization_paired_ttest_extremity_miscellaneous"
dataset: "data_miscellaneous"
variable_1: 'bayes-corrected (q=0.25) extremity'
variable_2: 'mean bayes-corrected (q=0.25) extremity of replies'
- !paired_ttest
name: "Evidence_polarization_paired_ttest_extremity_culture"
dataset: "data_culture"
variable_1: 'bayes-corrected (q=0.25) extremity'
variable_2: 'mean bayes-corrected (q=0.25) extremity of replies'
- !paired_ttest
name: "Evidence_polarization_paired_ttest_extremity_sports"
dataset: "data_sports"
variable_1: 'bayes-corrected (q=0.25) extremity'
variable_2: 'mean bayes-corrected (q=0.25) extremity of replies'
- !paired_ttest
name: "Evidence_polarization_paired_ttest_extremity_mobility"
dataset: "data_mobility"
variable_1: 'bayes-corrected (q=0.25) extremity'
variable_2: 'mean bayes-corrected (q=0.25) extremity of replies'
- !paired_ttest
name: "Evidence_polarization_paired_ttest_extremity_internet"
dataset: "data_internet"
variable_1: 'bayes-corrected (q=0.25) extremity'
variable_2: 'mean bayes-corrected (q=0.25) extremity of replies'
- !paired_ttest
name: "Evidence_polarization_paired_ttest_extremity_health"
dataset: "data_health"
variable_1: 'bayes-corrected (q=0.25) extremity'
variable_2: 'mean bayes-corrected (q=0.25) extremity of replies'
visualization:
- !hexbinplot
name: "Fig_2a"
dataset: "data_order0"
variable_x_axis: 'bayes-corrected (q=0.25) valence'
variable_y_axis: 'number O(n+1)-replies'
y_axis_maximum: 40
trendline: True
logarithmic_hex_scaling: True
- !forestplot
name: "Fig_2b"
regression_model_names:
- "Evidence_uncongenialty_section_politics"
- "Evidence_uncongenialty_section_foreign_affairs"
- "Evidence_uncongenialty_section_science"
- "Evidence_uncongenialty_section_economy"
- "Evidence_uncongenialty_section_miscellaneous"
- "Evidence_uncongenialty_section_culture"
- "Evidence_uncongenialty_section_sports"
- "Evidence_uncongenialty_section_mobility"
- "Evidence_uncongenialty_section_internet"
- "Evidence_uncongenialty_section_health"
regression_model_labels:
- "Politics"
- "Foreign Affairs"
- "Science"
- "Economy"
- "Miscellaneous"
- "Culture"
- "Sports"
- "Mobility"
- "Internet"
- "Health"
coefficient_names:
- "bayes-corrected (q=0.25) valence"
- "totalvotes"
x_axis_minimum: -0.6
dotsize: 2
x_axis_label: "Standardized coefficient (95% Confidence Interval)"
- !heatmap
name: "Fig_2c"
dataset: "data_order0_with_minimum_one_vote"
axis_variables:
- 'upvotes'
- 'downvotes'
heat_variable: 'number O(n+1)-replies'
axis_maxima:
- 20
- 20
axis_minima:
- 0
- 0
logarithmic_heat_scaling: 'false'
- !densityplot
name: 'Fig_3a'
dataset: "data_order0"
variable_x_axis: 'mean bayes-corrected (q=0.25) valence of replies'
variable_y_axis: 'bayes-corrected (q=0.25) valence'
data_breakpoints:
- 0
- !forestplot
name: "Fig_3b"
regression_model_names:
- "Evidence_antagonism_section_politics"
- "Evidence_antagonism_section_foreign_affairs"
- "Evidence_antagonism_section_science"
- "Evidence_antagonism_section_economy"
- "Evidence_antagonism_section_miscellaneous"
- "Evidence_antagonism_section_culture"
- "Evidence_antagonism_section_sports"
- "Evidence_antagonism_section_mobility"
- "Evidence_antagonism_section_internet"
- "Evidence_antagonism_section_health"
regression_model_labels:
- "Politics"
- "Foreign Affairs"
- "Science"
- "Economy"
- "Miscellaneous"
- "Culture"
- "Sports"
- "Mobility"
- "Internet"
- "Health"
coefficient_names:
- 'mean bayes-corrected (q=0.25) valence of replies'
x_axis_minimum: -0.1
dotsize: 2
x_axis_label: "Standardized coefficient (95% Confidence Interval)"
- !violinplot
name: "Fig_4a"
dataset: "data_order0"
variable_x_axis: 'bayes-corrected (q=0.25) extremity'
variable_y_axis: 'mean bayes-corrected (q=0.25) extremity of replies'
x_axis_label: ''
y_axis_label: 'Extremity value'
title: ''
- !forestplot_paired_ttest
name: "Fig_4b"
paired_ttest_names:
- "Evidence_polarization_paired_ttest_extremity_politics"
- "Evidence_polarization_paired_ttest_extremity_affairs"
- "Evidence_polarization_paired_ttest_extremity_science"
- "Evidence_polarization_paired_ttest_extremity_economy"
- "Evidence_polarization_paired_ttest_extremity_miscellaneous"
- "Evidence_polarization_paired_ttest_extremity_culture"
- "Evidence_polarization_paired_ttest_extremity_sports"
- "Evidence_polarization_paired_ttest_extremity_mobility"
- "Evidence_polarization_paired_ttest_extremity_internet"
- "Evidence_polarization_paired_ttest_extremity_health"
paired_ttest_labels:
- "Politics"
- "Foreign Affairs"
- "Science"
- "Economy"
- "Miscellaneous"
- "Culture"
- "Sports"
- "Mobility"
- "Internet"
- "Health"
x_axis_minimum: -0.06
dotsize: 2
x_axis_label: "Mean difference bayes-corrected (q=0.25) extremity (95% Confidence Interval)"
- !histogram
name: 'Extended_Fig_1'
dataset: "data"
variable: 'totalvotes'
x_axis_label: 'Number of total votes'
y_axis_label: 'Number of comments'
x_axis_logarithmic_scaling: false
y_axis_logarithmic_scaling: true
title: ''
...

6
config.yaml Normal file
View File

@ -0,0 +1,6 @@
---
data_path: 'put-path-to-the-data-directory-here'
dataset_name: '2024-02-28_preprocessed_data.parquet'
analysis_job_file: 'analysis_jobs/analysis_job_manuscript.yaml'
create_pdf_report: true
...

60
main.py Normal file
View File

@ -0,0 +1,60 @@
import pandas as pd
import yaml
import logging
import datetime
from pathlib import Path
from src.analysis import run_analyses
from src.preprocessor import Preprocessing
from src.data_loading_and_saving.constructor import custom_constructor
from src.data_loading_and_saving.create_results_report import (
create_markdown_report,
create_pdf_report,
)
def main():
yaml.SafeLoader.add_multi_constructor("!", custom_constructor)
with open("config.yaml", "r") as file:
config = yaml.safe_load(file)
path_to_data: str = config["data_path"]
name_data: str = config["dataset_name"]
name_analysis_job_file: str = config["analysis_job_file"]
bool_create_pdf_report: bool = config["create_pdf_report"]
log_filename: str = "log.log"
todays_date: str = datetime.date.today().strftime("%B %d, %Y")
output_name: str = f"{todays_date}_analysis_report"
logging.basicConfig(
filename=log_filename,
filemode="w",
format="%(message)s",
level=logging.INFO,
)
preprocessor: Preprocessing = Preprocessing(path_to_data, name_data)
with open(name_analysis_job_file, "r") as file:
analysis_config = yaml.safe_load(file)
datasets: dict[str, pd.DataFrame] = preprocessor.preprocess_datasets(analysis_config["preprocessing"])
run_analyses(analysis_config, datasets)
create_markdown_report(
log_filename=Path(log_filename),
output_name=Path(output_name),
output_dir=Path("results_reports"),
)
if bool_create_pdf_report:
create_pdf_report(
markdown_filename=Path(output_name), output_dir=Path("results_reports")
)
if __name__ == "__main__":
main()

13
requirements.txt Normal file
View File

@ -0,0 +1,13 @@
statsmodels==0.14.2
numpy==2.0.0
scipy==1.13.1
scikit-learn==1.5.0
matplotlib==3.9.0
seaborn==0.13.2
pandas==2.2.2
rpy2==3.5.16
pyarrow==16.1.0
pingouin==0.5.4
attrs==23.2.0
pyyaml==6.0.1
pypandoc==1.13

View File

@ -0,0 +1,25 @@
OLS Regression Results
============================================================================================
Dep. Variable: bayes-corrected (q=0.25) valence R-squared: 0.021
Model: OLS Adj. R-squared: 0.021
Method: Least Squares F-statistic: 5.020e+04
Date: Mon, 22 Jul 2024 Prob (F-statistic): 0.00
Time: 09:31:51 Log-Likelihood: -221.34
No. Observations: 2392896 AIC: 446.7
Df Residuals: 2392894 BIC: 472.1
Df Model: 1
Covariance Type: nonrobust
====================================================================================================================
coef std err t P>|t| [0.025 0.975]
--------------------------------------------------------------------------------------------------------------------
const 0.1246 0.000 796.722 0.000 0.124 0.125
mean bayes-corrected (q=0.25) valence of replies -0.0351 0.000 -224.063 0.000 -0.035 -0.035
==============================================================================
Omnibus: 426104.077 Durbin-Watson: 1.729
Prob(Omnibus): 0.000 Jarque-Bera (JB): 131391.270
Skew: -0.336 Prob(JB): 0.00
Kurtosis: 2.070 Cond. No. 1.00
==============================================================================
Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.

View File

@ -0,0 +1,25 @@
OLS Regression Results
============================================================================================
Dep. Variable: bayes-corrected (q=0.25) valence R-squared: 0.057
Model: OLS Adj. R-squared: 0.057
Method: Least Squares F-statistic: 9.915e+04
Date: Mon, 22 Jul 2024 Prob (F-statistic): 0.00
Time: 09:31:54 Log-Likelihood: 2.1429e+05
No. Observations: 1630262 AIC: -4.286e+05
Df Residuals: 1630260 BIC: -4.286e+05
Df Model: 1
Covariance Type: nonrobust
====================================================================================================================
coef std err t P>|t| [0.025 0.975]
--------------------------------------------------------------------------------------------------------------------
const 0.1419 0.000 854.072 0.000 0.142 0.142
mean bayes-corrected (q=0.25) valence of replies -0.0523 0.000 -314.877 0.000 -0.053 -0.052
==============================================================================
Omnibus: 101738.374 Durbin-Watson: 1.753
Prob(Omnibus): 0.000 Jarque-Bera (JB): 62821.338
Skew: -0.351 Prob(JB): 0.00
Kurtosis: 2.343 Cond. No. 1.00
==============================================================================
Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.

View File

@ -0,0 +1,25 @@
OLS Regression Results
============================================================================================
Dep. Variable: bayes-corrected (q=0.25) valence R-squared: 0.019
Model: OLS Adj. R-squared: 0.019
Method: Least Squares F-statistic: 8343.
Date: Mon, 22 Jul 2024 Prob (F-statistic): 0.00
Time: 09:31:53 Log-Likelihood: -43060.
No. Observations: 440260 AIC: 8.612e+04
Df Residuals: 440258 BIC: 8.615e+04
Df Model: 1
Covariance Type: nonrobust
====================================================================================================================
coef std err t P>|t| [0.025 0.975]
--------------------------------------------------------------------------------------------------------------------
const 0.1353 0.000 336.404 0.000 0.134 0.136
mean bayes-corrected (q=0.25) valence of replies -0.0367 0.000 -91.341 0.000 -0.038 -0.036
==============================================================================
Omnibus: 129058.321 Durbin-Watson: 1.735
Prob(Omnibus): 0.000 Jarque-Bera (JB): 32315.635
Skew: -0.421 Prob(JB): 0.00
Kurtosis: 1.974 Cond. No. 1.00
==============================================================================
Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.

View File

@ -0,0 +1,25 @@
OLS Regression Results
============================================================================================
Dep. Variable: bayes-corrected (q=0.25) valence R-squared: 0.032
Model: OLS Adj. R-squared: 0.032
Method: Least Squares F-statistic: 3435.
Date: Mon, 22 Jul 2024 Prob (F-statistic): 0.00
Time: 09:31:54 Log-Likelihood: -1315.0
No. Observations: 102305 AIC: 2634.
Df Residuals: 102303 BIC: 2653.
Df Model: 1
Covariance Type: nonrobust
====================================================================================================================
coef std err t P>|t| [0.025 0.975]
--------------------------------------------------------------------------------------------------------------------
const 0.1253 0.001 163.518 0.000 0.124 0.127
mean bayes-corrected (q=0.25) valence of replies -0.0449 0.001 -58.610 0.000 -0.046 -0.043
==============================================================================
Omnibus: 19234.419 Durbin-Watson: 1.748
Prob(Omnibus): 0.000 Jarque-Bera (JB): 5689.759
Skew: -0.334 Prob(JB): 0.00
Kurtosis: 2.057 Cond. No. 1.00
==============================================================================
Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.

View File

@ -0,0 +1,25 @@
OLS Regression Results
============================================================================================
Dep. Variable: bayes-corrected (q=0.25) valence R-squared: 0.017
Model: OLS Adj. R-squared: 0.017
Method: Least Squares F-statistic: 5484.
Date: Mon, 22 Jul 2024 Prob (F-statistic): 0.00
Time: 09:31:53 Log-Likelihood: 24023.
No. Observations: 316428 AIC: -4.804e+04
Df Residuals: 316426 BIC: -4.802e+04
Df Model: 1
Covariance Type: nonrobust
====================================================================================================================
coef std err t P>|t| [0.025 0.975]
--------------------------------------------------------------------------------------------------------------------
const 0.1474 0.000 369.619 0.000 0.147 0.148
mean bayes-corrected (q=0.25) valence of replies -0.0295 0.000 -74.054 0.000 -0.030 -0.029
==============================================================================
Omnibus: 28321.195 Durbin-Watson: 1.760
Prob(Omnibus): 0.000 Jarque-Bera (JB): 17536.904
Skew: -0.450 Prob(JB): 0.00
Kurtosis: 2.278 Cond. No. 1.00
==============================================================================
Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.

View File

@ -0,0 +1,25 @@
OLS Regression Results
============================================================================================
Dep. Variable: bayes-corrected (q=0.25) valence R-squared: 0.043
Model: OLS Adj. R-squared: 0.043
Method: Least Squares F-statistic: 1211.
Date: Mon, 22 Jul 2024 Prob (F-statistic): 1.61e-259
Time: 09:31:54 Log-Likelihood: -439.22
No. Observations: 27005 AIC: 882.4
Df Residuals: 27003 BIC: 898.9
Df Model: 1
Covariance Type: nonrobust
====================================================================================================================
coef std err t P>|t| [0.025 0.975]
--------------------------------------------------------------------------------------------------------------------
const 0.1074 0.001 71.776 0.000 0.104 0.110
mean bayes-corrected (q=0.25) valence of replies -0.0521 0.001 -34.794 0.000 -0.055 -0.049
==============================================================================
Omnibus: 6746.889 Durbin-Watson: 1.761
Prob(Omnibus): 0.000 Jarque-Bera (JB): 1324.435
Skew: -0.197 Prob(JB): 2.53e-288
Kurtosis: 1.989 Cond. No. 1.00
==============================================================================
Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.

View File

@ -0,0 +1,25 @@
OLS Regression Results
============================================================================================
Dep. Variable: bayes-corrected (q=0.25) valence R-squared: 0.028
Model: OLS Adj. R-squared: 0.028
Method: Least Squares F-statistic: 1805.
Date: Mon, 22 Jul 2024 Prob (F-statistic): 0.00
Time: 09:31:54 Log-Likelihood: -3477.5
No. Observations: 63079 AIC: 6959.
Df Residuals: 63077 BIC: 6977.
Df Model: 1
Covariance Type: nonrobust
====================================================================================================================
coef std err t P>|t| [0.025 0.975]
--------------------------------------------------------------------------------------------------------------------
const 0.1191 0.001 117.001 0.000 0.117 0.121
mean bayes-corrected (q=0.25) valence of replies -0.0433 0.001 -42.490 0.000 -0.045 -0.041
==============================================================================
Omnibus: 21454.701 Durbin-Watson: 1.721
Prob(Omnibus): 0.000 Jarque-Bera (JB): 4028.801
Skew: -0.319 Prob(JB): 0.00
Kurtosis: 1.939 Cond. No. 1.00
==============================================================================
Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.

View File

@ -0,0 +1,25 @@
OLS Regression Results
============================================================================================
Dep. Variable: bayes-corrected (q=0.25) valence R-squared: 0.028
Model: OLS Adj. R-squared: 0.028
Method: Least Squares F-statistic: 6790.
Date: Mon, 22 Jul 2024 Prob (F-statistic): 0.00
Time: 09:31:54 Log-Likelihood: -13916.
No. Observations: 235551 AIC: 2.784e+04
Df Residuals: 235549 BIC: 2.786e+04
Df Model: 1
Covariance Type: nonrobust
====================================================================================================================
coef std err t P>|t| [0.025 0.975]
--------------------------------------------------------------------------------------------------------------------
const 0.1362 0.001 257.499 0.000 0.135 0.137
mean bayes-corrected (q=0.25) valence of replies -0.0436 0.001 -82.403 0.000 -0.045 -0.043
==============================================================================
Omnibus: 52959.753 Durbin-Watson: 1.732
Prob(Omnibus): 0.000 Jarque-Bera (JB): 15867.344
Skew: -0.409 Prob(JB): 0.00
Kurtosis: 2.027 Cond. No. 1.00
==============================================================================
Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.

View File

@ -0,0 +1,25 @@
OLS Regression Results
============================================================================================
Dep. Variable: bayes-corrected (q=0.25) valence R-squared: 0.024
Model: OLS Adj. R-squared: 0.024
Method: Least Squares F-statistic: 1726.
Date: Mon, 22 Jul 2024 Prob (F-statistic): 0.00
Time: 09:31:54 Log-Likelihood: 10825.
No. Observations: 69253 AIC: -2.165e+04
Df Residuals: 69251 BIC: -2.163e+04
Df Model: 1
Covariance Type: nonrobust
====================================================================================================================
coef std err t P>|t| [0.025 0.975]
--------------------------------------------------------------------------------------------------------------------
const 0.1109 0.001 141.050 0.000 0.109 0.112
mean bayes-corrected (q=0.25) valence of replies -0.0327 0.001 -41.551 0.000 -0.034 -0.031
==============================================================================
Omnibus: 6922.840 Durbin-Watson: 1.814
Prob(Omnibus): 0.000 Jarque-Bera (JB): 2381.203
Skew: -0.195 Prob(JB): 0.00
Kurtosis: 2.179 Cond. No. 1.00
==============================================================================
Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.

View File

@ -0,0 +1,25 @@
OLS Regression Results
============================================================================================
Dep. Variable: bayes-corrected (q=0.25) valence R-squared: 0.018
Model: OLS Adj. R-squared: 0.018
Method: Least Squares F-statistic: 1.166e+04
Date: Mon, 22 Jul 2024 Prob (F-statistic): 0.00
Time: 09:31:53 Log-Likelihood: 34045.
No. Observations: 621929 AIC: -6.809e+04
Df Residuals: 621927 BIC: -6.806e+04
Df Model: 1
Covariance Type: nonrobust
====================================================================================================================
coef std err t P>|t| [0.025 0.975]
--------------------------------------------------------------------------------------------------------------------
const 0.1305 0.000 449.326 0.000 0.130 0.131
mean bayes-corrected (q=0.25) valence of replies -0.0314 0.000 -107.983 0.000 -0.032 -0.031
==============================================================================
Omnibus: 78154.602 Durbin-Watson: 1.733
Prob(Omnibus): 0.000 Jarque-Bera (JB): 31765.731
Skew: -0.357 Prob(JB): 0.00
Kurtosis: 2.155 Cond. No. 1.00
==============================================================================
Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.

View File

@ -0,0 +1,25 @@
OLS Regression Results
============================================================================================
Dep. Variable: bayes-corrected (q=0.25) valence R-squared: 0.028
Model: OLS Adj. R-squared: 0.028
Method: Least Squares F-statistic: 1.007e+04
Date: Mon, 22 Jul 2024 Prob (F-statistic): 0.00
Time: 09:31:53 Log-Likelihood: 27583.
No. Observations: 345534 AIC: -5.516e+04
Df Residuals: 345532 BIC: -5.514e+04
Df Model: 1
Covariance Type: nonrobust
====================================================================================================================
coef std err t P>|t| [0.025 0.975]
--------------------------------------------------------------------------------------------------------------------
const 0.0723 0.000 190.132 0.000 0.072 0.073
mean bayes-corrected (q=0.25) valence of replies -0.0381 0.000 -100.372 0.000 -0.039 -0.037
==============================================================================
Omnibus: 59103.072 Durbin-Watson: 1.791
Prob(Omnibus): 0.000 Jarque-Bera (JB): 12955.369
Skew: -0.052 Prob(JB): 0.00
Kurtosis: 2.057 Cond. No. 1.00
==============================================================================
Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.

View File

@ -0,0 +1,25 @@
OLS Regression Results
============================================================================================
Dep. Variable: bayes-corrected (q=0.25) valence R-squared: 0.032
Model: OLS Adj. R-squared: 0.032
Method: Least Squares F-statistic: 3344.
Date: Mon, 22 Jul 2024 Prob (F-statistic): 0.00
Time: 09:31:54 Log-Likelihood: -6723.8
No. Observations: 100071 AIC: 1.345e+04
Df Residuals: 100069 BIC: 1.347e+04
Df Model: 1
Covariance Type: nonrobust
====================================================================================================================
coef std err t P>|t| [0.025 0.975]
--------------------------------------------------------------------------------------------------------------------
const 0.1246 0.001 152.318 0.000 0.123 0.126
mean bayes-corrected (q=0.25) valence of replies -0.0473 0.001 -57.827 0.000 -0.049 -0.046
==============================================================================
Omnibus: 28267.899 Durbin-Watson: 1.740
Prob(Omnibus): 0.000 Jarque-Bera (JB): 6368.870
Skew: -0.345 Prob(JB): 0.00
Kurtosis: 1.975 Cond. No. 1.00
==============================================================================
Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.

View File

@ -0,0 +1,25 @@
OLS Regression Results
==============================================================================
Dep. Variable: valence R-squared: 0.010
Model: OLS Adj. R-squared: 0.010
Method: Least Squares F-statistic: 2.337e+04
Date: Mon, 22 Jul 2024 Prob (F-statistic): 0.00
Time: 09:31:53 Log-Likelihood: -4.8218e+05
No. Observations: 2392896 AIC: 9.644e+05
Df Residuals: 2392894 BIC: 9.644e+05
Df Model: 1
Covariance Type: nonrobust
===========================================================================================
coef std err t P>|t| [0.025 0.975]
-------------------------------------------------------------------------------------------
const 0.1158 0.000 604.951 0.000 0.115 0.116
mean valence of replies -0.0293 0.000 -152.877 0.000 -0.030 -0.029
==============================================================================
Omnibus: 785394.853 Durbin-Watson: 1.750
Prob(Omnibus): 0.000 Jarque-Bera (JB): 152455.997
Skew: -0.323 Prob(JB): 0.00
Kurtosis: 1.946 Cond. No. 1.00
==============================================================================
Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.

View File

@ -0,0 +1,25 @@
OLS Regression Results
===========================================================================================
Dep. Variable: bayes-corrected (q=0.5) valence R-squared: 0.027
Model: OLS Adj. R-squared: 0.027
Method: Least Squares F-statistic: 6.556e+04
Date: Mon, 22 Jul 2024 Prob (F-statistic): 0.00
Time: 09:31:52 Log-Likelihood: 3.9215e+05
No. Observations: 2392896 AIC: -7.843e+05
Df Residuals: 2392894 BIC: -7.843e+05
Df Model: 1
Covariance Type: nonrobust
===================================================================================================================
coef std err t P>|t| [0.025 0.975]
-------------------------------------------------------------------------------------------------------------------
const 0.1323 0.000 996.732 0.000 0.132 0.133
mean bayes-corrected (q=0.5) valence of replies -0.0340 0.000 -256.042 0.000 -0.034 -0.034
==============================================================================
Omnibus: 168653.316 Durbin-Watson: 1.726
Prob(Omnibus): 0.000 Jarque-Bera (JB): 107460.980
Skew: -0.396 Prob(JB): 0.00
Kurtosis: 2.328 Cond. No. 1.00
==============================================================================
Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.

View File

@ -0,0 +1,25 @@
OLS Regression Results
============================================================================================
Dep. Variable: bayes-corrected (q=0.75) valence R-squared: 0.032
Model: OLS Adj. R-squared: 0.032
Method: Least Squares F-statistic: 8.012e+04
Date: Mon, 22 Jul 2024 Prob (F-statistic): 0.00
Time: 09:31:52 Log-Likelihood: 8.8112e+05
No. Observations: 2392896 AIC: -1.762e+06
Df Residuals: 2392894 BIC: -1.762e+06
Df Model: 1
Covariance Type: nonrobust
====================================================================================================================
coef std err t P>|t| [0.025 0.975]
--------------------------------------------------------------------------------------------------------------------
const 0.1411 0.000 1303.270 0.000 0.141 0.141
mean bayes-corrected (q=0.75) valence of replies -0.0306 0.000 -283.054 0.000 -0.031 -0.030
==============================================================================
Omnibus: 95205.666 Durbin-Watson: 1.729
Prob(Omnibus): 0.000 Jarque-Bera (JB): 102788.717
Skew: -0.491 Prob(JB): 0.00
Kurtosis: 2.742 Cond. No. 1.00
==============================================================================
Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.

View File

@ -0,0 +1,8 @@
Mean of bayes-corrected (q=0.25) extremity: 0.28634078314814315
Mean of mean bayes-corrected (q=0.25) extremity of replies: 0.31853427098636283
Standard Deviation of bayes-corrected (q=0.25) extremity: 0.12461005214018245
Standard Deviation of mean bayes-corrected (q=0.25) extremity of replies: 0.09803757310470287
Degrees of Freedom: 2392895
Cohen's d: -0.28714996199978216
T-statistic: -396.76675511778956
P-value: 0.0

View File

@ -0,0 +1,8 @@
Mean of bayes-corrected (q=0.25) extremity: 0.2873043034163312
Mean of mean bayes-corrected (q=0.25) extremity of replies: 0.3180681433274033
Standard Deviation of bayes-corrected (q=0.25) extremity: 0.12427097360816901
Standard Deviation of mean bayes-corrected (q=0.25) extremity of replies: 0.10041204122831116
Degrees of Freedom: 102304
Cohen's d: -0.27231114070182555
T-statistic: -77.26207861609845
P-value: 0.0

View File

@ -0,0 +1,8 @@
Mean of bayes-corrected (q=0.25) extremity: 0.28753090601867964
Mean of mean bayes-corrected (q=0.25) extremity of replies: 0.3206172046668397
Standard Deviation of bayes-corrected (q=0.25) extremity: 0.12269603857552688
Standard Deviation of mean bayes-corrected (q=0.25) extremity of replies: 0.09544219919767762
Degrees of Freedom: 316427
Cohen's d: -0.3010114266220678
T-statistic: -144.89599610520233
P-value: 0.0

View File

@ -0,0 +1,8 @@
Mean of bayes-corrected (q=0.25) extremity: 0.30983360408913946
Mean of mean bayes-corrected (q=0.25) extremity of replies: 0.330913534598374
Standard Deviation of bayes-corrected (q=0.25) extremity: 0.1266220167440838
Standard Deviation of mean bayes-corrected (q=0.25) extremity of replies: 0.0994658270407316
Degrees of Freedom: 440259
Cohen's d: -0.18514479506979328
T-statistic: -116.67457613500132
P-value: 0.0

View File

@ -0,0 +1,8 @@
Mean of bayes-corrected (q=0.25) extremity: 0.286001211119296
Mean of mean bayes-corrected (q=0.25) extremity of replies: 0.32344058185785135
Standard Deviation of bayes-corrected (q=0.25) extremity: 0.12360412242902419
Standard Deviation of mean bayes-corrected (q=0.25) extremity of replies: 0.09582069057098505
Degrees of Freedom: 27004
Cohen's d: -0.3385470290175242
T-statistic: -48.09524752175683
P-value: 0.0

View File

@ -0,0 +1,8 @@
Mean of bayes-corrected (q=0.25) extremity: 0.30568494651578504
Mean of mean bayes-corrected (q=0.25) extremity of replies: 0.33706126033387757
Standard Deviation of bayes-corrected (q=0.25) extremity: 0.12135285517757544
Standard Deviation of mean bayes-corrected (q=0.25) extremity of replies: 0.09268724557998224
Degrees of Freedom: 63078
Cohen's d: -0.2905871965145026
T-statistic: -63.21801300923011
P-value: 0.0

View File

@ -0,0 +1,8 @@
Mean of bayes-corrected (q=0.25) extremity: 0.3045872088628839
Mean of mean bayes-corrected (q=0.25) extremity of replies: 0.33005502824126426
Standard Deviation of bayes-corrected (q=0.25) extremity: 0.12405998014131653
Standard Deviation of mean bayes-corrected (q=0.25) extremity of replies: 0.09742991339150692
Degrees of Freedom: 235550
Cohen's d: -0.22832386975048508
T-statistic: -97.05206575930157
P-value: 0.0

View File

@ -0,0 +1,8 @@
Mean of bayes-corrected (q=0.25) extremity: 0.25434099233474056
Mean of mean bayes-corrected (q=0.25) extremity of replies: 0.3002874727751491
Standard Deviation of bayes-corrected (q=0.25) extremity: 0.1194543498720806
Standard Deviation of mean bayes-corrected (q=0.25) extremity of replies: 0.09661488578718154
Degrees of Freedom: 69252
Cohen's d: -0.4229377864257918
T-statistic: -93.24696971910268
P-value: 0.0

View File

@ -0,0 +1,8 @@
Mean of bayes-corrected (q=0.25) extremity: 0.2747813213977206
Mean of mean bayes-corrected (q=0.25) extremity of replies: 0.31051648819461664
Standard Deviation of bayes-corrected (q=0.25) extremity: 0.1232411698734475
Standard Deviation of mean bayes-corrected (q=0.25) extremity of replies: 0.09815038738028235
Degrees of Freedom: 621928
Cohen's d: -0.3207697725588003
T-statistic: -224.4339595489235
P-value: 0.0

View File

@ -0,0 +1,8 @@
Mean of bayes-corrected (q=0.25) extremity: 0.25732194943047365
Mean of mean bayes-corrected (q=0.25) extremity of replies: 0.3019777399435376
Standard Deviation of bayes-corrected (q=0.25) extremity: 0.1187657730515952
Standard Deviation of mean bayes-corrected (q=0.25) extremity of replies: 0.09498121080140695
Degrees of Freedom: 345533
Cohen's d: -0.4152747999524859
T-statistic: -212.56678640514008
P-value: 0.0

View File

@ -0,0 +1,8 @@
Mean of bayes-corrected (q=0.25) extremity: 0.30601102207250513
Mean of mean bayes-corrected (q=0.25) extremity of replies: 0.328439915246921
Standard Deviation of bayes-corrected (q=0.25) extremity: 0.12292708240128108
Standard Deviation of mean bayes-corrected (q=0.25) extremity of replies: 0.098047183761713
Degrees of Freedom: 100070
Cohen's d: -0.20172544463043993
T-statistic: -55.9671976011527
P-value: 0.0

View File

@ -0,0 +1,8 @@
Mean of bayes-corrected (q=0.25) extremity: 0.29265411081901965
Mean of mean bayes-corrected (q=0.25) extremity of replies: 0.316766141686027
Standard Deviation of bayes-corrected (q=0.25) extremity: 0.11701339959130957
Standard Deviation of mean bayes-corrected (q=0.25) extremity of replies: 0.09812627267575441
Degrees of Freedom: 1630261
Cohen's d: -0.2232935227954181
T-statistic: -248.9875068375778
P-value: 0.0

View File

@ -0,0 +1,8 @@
Mean of extremity: 0.2786279465660722
Mean of mean extremity of replies: 0.33064022086792666
Standard Deviation of extremity: 0.15566001726472525
Standard Deviation of mean extremity of replies: 0.15685179947476463
Degrees of Freedom: 2392895
Cohen's d: -0.332863548235494
T-statistic: -441.7826610833192
P-value: 0.0

View File

@ -0,0 +1,8 @@
Mean of bayes-corrected (q=0.5) extremity: 0.2934997056888845
Mean of mean bayes-corrected (q=0.5) extremity of replies: 0.31880240669265064
Standard Deviation of bayes-corrected (q=0.5) extremity: 0.10366027656607042
Standard Deviation of mean bayes-corrected (q=0.5) extremity of replies: 0.07259709613375841
Degrees of Freedom: 2392895
Cohen's d: -0.28275329909468133
T-statistic: -394.7125869249032
P-value: 0.0

View File

@ -0,0 +1,8 @@
Mean of bayes-corrected (q=0.75) extremity: 0.3010823980840001
Mean of mean bayes-corrected (q=0.75) extremity of replies: 0.32039106933723704
Standard Deviation of bayes-corrected (q=0.75) extremity: 0.08248076963764756
Standard Deviation of mean bayes-corrected (q=0.75) extremity of replies: 0.05223289636934443
Degrees of Freedom: 2392895
Cohen's d: -0.2796984844303324
T-statistic: -391.6388789093796
P-value: 0.0

View File

@ -0,0 +1,26 @@
OLS Regression Results
=================================================================================
Dep. Variable: number O(n+1)-replies R-squared: 0.194
Model: OLS Adj. R-squared: 0.194
Method: Least Squares F-statistic: 7.311e+05
Date: Mon, 22 Jul 2024 Prob (F-statistic): 0.00
Time: 09:31:51 Log-Likelihood: -1.0415e+07
No. Observations: 6069971 AIC: 2.083e+07
Df Residuals: 6069968 BIC: 2.083e+07
Df Model: 2
Covariance Type: nonrobust
==============================================================================
coef std err t P>|t| [0.025 0.975]
------------------------------------------------------------------------------
const 1.1129 0.001 2037.629 0.000 1.112 1.114
upvotes 0.0893 0.001 162.278 0.000 0.088 0.090
downvotes 0.6433 0.001 1168.654 0.000 0.642 0.644
==============================================================================
Omnibus: 3179849.625 Durbin-Watson: 1.812
Prob(Omnibus): 0.000 Jarque-Bera (JB): 138815450.026
Skew: 1.836 Prob(JB): 0.00
Kurtosis: 26.138 Cond. No. 1.13
==============================================================================
Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.

View File

@ -0,0 +1,26 @@
OLS Regression Results
=================================================================================
Dep. Variable: number O(n+1)-replies R-squared: 0.220
Model: OLS Adj. R-squared: 0.220
Method: Least Squares F-statistic: 6.744e+05
Date: Mon, 22 Jul 2024 Prob (F-statistic): 0.00
Time: 09:31:43 Log-Likelihood: -8.1863e+06
No. Observations: 4786218 AIC: 1.637e+07
Df Residuals: 4786215 BIC: 1.637e+07
Df Model: 2
Covariance Type: nonrobust
====================================================================================================
coef std err t P>|t| [0.025 0.975]
----------------------------------------------------------------------------------------------------
const 1.1760 0.001 1922.382 0.000 1.175 1.177
bayes-corrected (q=0.25) valence -0.4349 0.001 -707.468 0.000 -0.436 -0.434
totalvotes 0.5207 0.001 847.067 0.000 0.520 0.522
==============================================================================
Omnibus: 2282674.662 Durbin-Watson: 1.758
Prob(Omnibus): 0.000 Jarque-Bera (JB): 64040137.713
Skew: 1.723 Prob(JB): 0.00
Kurtosis: 20.586 Cond. No. 1.10
==============================================================================
Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.

View File

@ -0,0 +1 @@
totalvotes: 208.8619281171 (CI: [ 208.5635392284, 209.1603170058])

View File

@ -0,0 +1 @@
totalvotes: 444292.7728500224 (CI: [ 403421.6792516428, 485163.8664484020])

View File

@ -0,0 +1,26 @@
OLS Regression Results
=================================================================================
Dep. Variable: number O(n+1)-replies R-squared: 0.136
Model: OLS Adj. R-squared: 0.136
Method: Least Squares F-statistic: 3.982e+05
Date: Mon, 22 Jul 2024 Prob (F-statistic): 0.00
Time: 09:31:50 Log-Likelihood: -6.2998e+06
No. Observations: 5050120 AIC: 1.260e+07
Df Residuals: 5050117 BIC: 1.260e+07
Df Model: 2
Covariance Type: nonrobust
====================================================================================================
coef std err t P>|t| [0.025 0.975]
----------------------------------------------------------------------------------------------------
const 0.6133 0.000 1636.095 0.000 0.613 0.614
bayes-corrected (q=0.25) valence -0.2055 0.000 -548.027 0.000 -0.206 -0.205
totalvotes 0.2575 0.000 686.512 0.000 0.257 0.258
==============================================================================
Omnibus: 2832727.339 Durbin-Watson: 1.864
Prob(Omnibus): 0.000 Jarque-Bera (JB): 85433368.019
Skew: 2.153 Prob(JB): 0.00
Kurtosis: 22.684 Cond. No. 1.03
==============================================================================
Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.

View File

@ -0,0 +1,25 @@
OLS Regression Results
=================================================================================
Dep. Variable: number O(n+1)-replies R-squared: 0.077
Model: OLS Adj. R-squared: 0.077
Method: Least Squares F-statistic: 4.005e+05
Date: Mon, 22 Jul 2024 Prob (F-statistic): 0.00
Time: 09:31:42 Log-Likelihood: -8.5881e+06
No. Observations: 4786218 AIC: 1.718e+07
Df Residuals: 4786216 BIC: 1.718e+07
Df Model: 1
Covariance Type: nonrobust
==============================================================================
coef std err t P>|t| [0.025 0.975]
------------------------------------------------------------------------------
const 1.4225 0.001 1845.132 0.000 1.421 1.424
valence -1.3913 0.002 -632.878 0.000 -1.396 -1.387
==============================================================================
Omnibus: 2883084.941 Durbin-Watson: 1.828
Prob(Omnibus): 0.000 Jarque-Bera (JB): 98618092.392
Skew: 2.349 Prob(JB): 0.00
Kurtosis: 24.736 Cond. No. 3.42
==============================================================================
Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.

View File

@ -0,0 +1,26 @@
OLS Regression Results
=================================================================================
Dep. Variable: number O(n+1)-replies R-squared: 0.199
Model: OLS Adj. R-squared: 0.199
Method: Least Squares F-statistic: 5.941e+05
Date: Mon, 22 Jul 2024 Prob (F-statistic): 0.00
Time: 09:31:47 Log-Likelihood: -8.2498e+06
No. Observations: 4786218 AIC: 1.650e+07
Df Residuals: 4786215 BIC: 1.650e+07
Df Model: 2
Covariance Type: nonrobust
==============================================================================
coef std err t P>|t| [0.025 0.975]
------------------------------------------------------------------------------
const 1.1760 0.001 1897.046 0.000 1.175 1.177
valence -0.3745 0.001 -601.728 0.000 -0.376 -0.373
totalvotes 0.5306 0.001 852.573 0.000 0.529 0.532
==============================================================================
Omnibus: 2293481.647 Durbin-Watson: 1.752
Prob(Omnibus): 0.000 Jarque-Bera (JB): 63398255.054
Skew: 1.739 Prob(JB): 0.00
Kurtosis: 20.487 Cond. No. 1.09
==============================================================================
Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.

View File

@ -0,0 +1,26 @@
OLS Regression Results
=================================================================================
Dep. Variable: number O(n+1)-replies R-squared: 0.229
Model: OLS Adj. R-squared: 0.229
Method: Least Squares F-statistic: 7.096e+05
Date: Mon, 22 Jul 2024 Prob (F-statistic): 0.00
Time: 09:31:44 Log-Likelihood: -8.1590e+06
No. Observations: 4786218 AIC: 1.632e+07
Df Residuals: 4786215 BIC: 1.632e+07
Df Model: 2
Covariance Type: nonrobust
===================================================================================================
coef std err t P>|t| [0.025 0.975]
---------------------------------------------------------------------------------------------------
const 1.1760 0.001 1933.368 0.000 1.175 1.177
bayes-corrected (q=0.5) valence -0.4582 0.001 -749.070 0.000 -0.459 -0.457
totalvotes 0.5147 0.001 841.341 0.000 0.513 0.516
==============================================================================
Omnibus: 2271398.527 Durbin-Watson: 1.760
Prob(Omnibus): 0.000 Jarque-Bera (JB): 63503192.358
Skew: 1.712 Prob(JB): 0.00
Kurtosis: 20.513 Cond. No. 1.11
==============================================================================
Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.

View File

@ -0,0 +1,26 @@
OLS Regression Results
=================================================================================
Dep. Variable: number O(n+1)-replies R-squared: 0.236
Model: OLS Adj. R-squared: 0.236
Method: Least Squares F-statistic: 7.380e+05
Date: Mon, 22 Jul 2024 Prob (F-statistic): 0.00
Time: 09:31:45 Log-Likelihood: -8.1372e+06
No. Observations: 4786218 AIC: 1.627e+07
Df Residuals: 4786215 BIC: 1.627e+07
Df Model: 2
Covariance Type: nonrobust
====================================================================================================
coef std err t P>|t| [0.025 0.975]
----------------------------------------------------------------------------------------------------
const 1.1760 0.001 1942.187 0.000 1.175 1.177
bayes-corrected (q=0.75) valence -0.4762 0.001 -781.029 0.000 -0.477 -0.475
totalvotes 0.5081 0.001 833.387 0.000 0.507 0.509
==============================================================================
Omnibus: 2256599.632 Durbin-Watson: 1.761
Prob(Omnibus): 0.000 Jarque-Bera (JB): 62251699.550
Skew: 1.700 Prob(JB): 0.00
Kurtosis: 20.338 Cond. No. 1.12
==============================================================================
Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.

View File

@ -0,0 +1,26 @@
OLS Regression Results
=================================================================================
Dep. Variable: number O(n+1)-replies R-squared: 0.237
Model: OLS Adj. R-squared: 0.237
Method: Least Squares F-statistic: 1.380e+05
Date: Mon, 22 Jul 2024 Prob (F-statistic): 0.00
Time: 09:31:48 Log-Likelihood: -1.5539e+06
No. Observations: 890221 AIC: 3.108e+06
Df Residuals: 890218 BIC: 3.108e+06
Df Model: 2
Covariance Type: nonrobust
====================================================================================================
coef std err t P>|t| [0.025 0.975]
----------------------------------------------------------------------------------------------------
const 1.1789 0.001 802.397 0.000 1.176 1.182
bayes-corrected (q=0.25) valence -0.4979 0.001 -337.303 0.000 -0.501 -0.495
totalvotes 0.5435 0.001 368.179 0.000 0.541 0.546
==============================================================================
Omnibus: 415616.007 Durbin-Watson: 1.775
Prob(Omnibus): 0.000 Jarque-Bera (JB): 8567668.092
Skew: 1.765 Prob(JB): 0.00
Kurtosis: 17.782 Cond. No. 1.10
==============================================================================
Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.

View File

@ -0,0 +1,26 @@
OLS Regression Results
=================================================================================
Dep. Variable: number O(n+1)-replies R-squared: 0.243
Model: OLS Adj. R-squared: 0.243
Method: Least Squares F-statistic: 3.781e+04
Date: Mon, 22 Jul 2024 Prob (F-statistic): 0.00
Time: 09:31:48 Log-Likelihood: -3.6290e+05
No. Observations: 235911 AIC: 7.258e+05
Df Residuals: 235908 BIC: 7.258e+05
Df Model: 2
Covariance Type: nonrobust
====================================================================================================
coef std err t P>|t| [0.025 0.975]
----------------------------------------------------------------------------------------------------
const 0.9173 0.002 395.396 0.000 0.913 0.922
bayes-corrected (q=0.25) valence -0.3334 0.002 -142.771 0.000 -0.338 -0.329
totalvotes 0.5075 0.002 217.346 0.000 0.503 0.512
==============================================================================
Omnibus: 99947.806 Durbin-Watson: 1.805
Prob(Omnibus): 0.000 Jarque-Bera (JB): 886847.368
Skew: 1.813 Prob(JB): 0.00
Kurtosis: 11.779 Cond. No. 1.12
==============================================================================
Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.

View File

@ -0,0 +1,26 @@
OLS Regression Results
=================================================================================
Dep. Variable: number O(n+1)-replies R-squared: 0.196
Model: OLS Adj. R-squared: 0.196
Method: Least Squares F-statistic: 7.576e+04
Date: Mon, 22 Jul 2024 Prob (F-statistic): 0.00
Time: 09:31:48 Log-Likelihood: -1.0058e+06
No. Observations: 620776 AIC: 2.012e+06
Df Residuals: 620773 BIC: 2.012e+06
Df Model: 2
Covariance Type: nonrobust
====================================================================================================
coef std err t P>|t| [0.025 0.975]
----------------------------------------------------------------------------------------------------
const 1.1396 0.002 734.230 0.000 1.137 1.143
bayes-corrected (q=0.25) valence -0.3478 0.002 -223.518 0.000 -0.351 -0.345
totalvotes 0.4695 0.002 301.664 0.000 0.466 0.473
==============================================================================
Omnibus: 202475.900 Durbin-Watson: 1.799
Prob(Omnibus): 0.000 Jarque-Bera (JB): 1088427.374
Skew: 1.479 Prob(JB): 0.00
Kurtosis: 8.773 Cond. No. 1.08
==============================================================================
Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.

View File

@ -0,0 +1,26 @@
OLS Regression Results
=================================================================================
Dep. Variable: number O(n+1)-replies R-squared: 0.257
Model: OLS Adj. R-squared: 0.257
Method: Least Squares F-statistic: 8576.
Date: Mon, 22 Jul 2024 Prob (F-statistic): 0.00
Time: 09:31:48 Log-Likelihood: -86794.
No. Observations: 49462 AIC: 1.736e+05
Df Residuals: 49459 BIC: 1.736e+05
Df Model: 2
Covariance Type: nonrobust
====================================================================================================
coef std err t P>|t| [0.025 0.975]
----------------------------------------------------------------------------------------------------
const 1.3371 0.006 212.544 0.000 1.325 1.349
bayes-corrected (q=0.25) valence -0.4685 0.006 -73.917 0.000 -0.481 -0.456
totalvotes 0.6228 0.006 98.259 0.000 0.610 0.635
==============================================================================
Omnibus: 17663.533 Durbin-Watson: 1.771
Prob(Omnibus): 0.000 Jarque-Bera (JB): 106942.347
Skew: 1.595 Prob(JB): 0.00
Kurtosis: 9.459 Cond. No. 1.13
==============================================================================
Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.

View File

@ -0,0 +1,26 @@
OLS Regression Results
=================================================================================
Dep. Variable: number O(n+1)-replies R-squared: 0.256
Model: OLS Adj. R-squared: 0.256
Method: Least Squares F-statistic: 2.267e+04
Date: Mon, 22 Jul 2024 Prob (F-statistic): 0.00
Time: 09:31:48 Log-Likelihood: -2.1421e+05
No. Observations: 131977 AIC: 4.284e+05
Df Residuals: 131974 BIC: 4.284e+05
Df Model: 2
Covariance Type: nonrobust
====================================================================================================
coef std err t P>|t| [0.025 0.975]
----------------------------------------------------------------------------------------------------
const 1.0804 0.003 320.014 0.000 1.074 1.087
bayes-corrected (q=0.25) valence -0.4040 0.003 -118.355 0.000 -0.411 -0.397
totalvotes 0.5375 0.003 157.450 0.000 0.531 0.544
==============================================================================
Omnibus: 54168.298 Durbin-Watson: 1.825
Prob(Omnibus): 0.000 Jarque-Bera (JB): 590918.640
Skew: 1.674 Prob(JB): 0.00
Kurtosis: 12.811 Cond. No. 1.16
==============================================================================
Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.

View File

@ -0,0 +1,26 @@
OLS Regression Results
=================================================================================
Dep. Variable: number O(n+1)-replies R-squared: 0.246
Model: OLS Adj. R-squared: 0.246
Method: Least Squares F-statistic: 7.921e+04
Date: Mon, 22 Jul 2024 Prob (F-statistic): 0.00
Time: 09:31:48 Log-Likelihood: -8.1045e+05
No. Observations: 485006 AIC: 1.621e+06
Df Residuals: 485003 BIC: 1.621e+06
Df Model: 2
Covariance Type: nonrobust
====================================================================================================
coef std err t P>|t| [0.025 0.975]
----------------------------------------------------------------------------------------------------
const 1.1141 0.002 602.981 0.000 1.110 1.118
bayes-corrected (q=0.25) valence -0.4406 0.002 -237.533 0.000 -0.444 -0.437
totalvotes 0.5508 0.002 296.904 0.000 0.547 0.554
==============================================================================
Omnibus: 308614.044 Durbin-Watson: 1.795
Prob(Omnibus): 0.000 Jarque-Bera (JB): 33388300.741
Skew: 2.187 Prob(JB): 0.00
Kurtosis: 43.411 Cond. No. 1.09
==============================================================================
Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.

View File

@ -0,0 +1,26 @@
OLS Regression Results
=================================================================================
Dep. Variable: number O(n+1)-replies R-squared: 0.198
Model: OLS Adj. R-squared: 0.198
Method: Least Squares F-statistic: 1.449e+04
Date: Mon, 22 Jul 2024 Prob (F-statistic): 0.00
Time: 09:31:48 Log-Likelihood: -1.9705e+05
No. Observations: 117051 AIC: 3.941e+05
Df Residuals: 117048 BIC: 3.941e+05
Df Model: 2
Covariance Type: nonrobust
====================================================================================================
coef std err t P>|t| [0.025 0.975]
----------------------------------------------------------------------------------------------------
const 1.3476 0.004 353.887 0.000 1.340 1.355
bayes-corrected (q=0.25) valence -0.3144 0.004 -80.973 0.000 -0.322 -0.307
totalvotes 0.5090 0.004 131.111 0.000 0.501 0.517
==============================================================================
Omnibus: 32287.766 Durbin-Watson: 1.796
Prob(Omnibus): 0.000 Jarque-Bera (JB): 111823.546
Skew: 1.377 Prob(JB): 0.00
Kurtosis: 6.917 Cond. No. 1.22
==============================================================================
Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.

View File

@ -0,0 +1,26 @@
OLS Regression Results
=================================================================================
Dep. Variable: number O(n+1)-replies R-squared: 0.209
Model: OLS Adj. R-squared: 0.209
Method: Least Squares F-statistic: 1.708e+05
Date: Mon, 22 Jul 2024 Prob (F-statistic): 0.00
Time: 09:31:48 Log-Likelihood: -2.1743e+06
No. Observations: 1295105 AIC: 4.349e+06
Df Residuals: 1295102 BIC: 4.349e+06
Df Model: 2
Covariance Type: nonrobust
====================================================================================================
coef std err t P>|t| [0.025 0.975]
----------------------------------------------------------------------------------------------------
const 1.1182 0.001 981.264 0.000 1.116 1.120
bayes-corrected (q=0.25) valence -0.3909 0.001 -341.822 0.000 -0.393 -0.389
totalvotes 0.5079 0.001 444.124 0.000 0.506 0.510
==============================================================================
Omnibus: 680589.819 Durbin-Watson: 1.782
Prob(Omnibus): 0.000 Jarque-Bera (JB): 49094495.451
Skew: 1.699 Prob(JB): 0.00
Kurtosis: 32.971 Cond. No. 1.09
==============================================================================
Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.

View File

@ -0,0 +1,26 @@
OLS Regression Results
=================================================================================
Dep. Variable: number O(n+1)-replies R-squared: 0.253
Model: OLS Adj. R-squared: 0.253
Method: Least Squares F-statistic: 9.746e+04
Date: Mon, 22 Jul 2024 Prob (F-statistic): 0.00
Time: 09:31:48 Log-Likelihood: -1.0810e+06
No. Observations: 575190 AIC: 2.162e+06
Df Residuals: 575187 BIC: 2.162e+06
Df Model: 2
Covariance Type: nonrobust
====================================================================================================
coef std err t P>|t| [0.025 0.975]
----------------------------------------------------------------------------------------------------
const 1.6458 0.002 787.663 0.000 1.642 1.650
bayes-corrected (q=0.25) valence -0.3951 0.002 -184.289 0.000 -0.399 -0.391
totalvotes 0.7495 0.002 349.574 0.000 0.745 0.754
==============================================================================
Omnibus: 194870.309 Durbin-Watson: 1.765
Prob(Omnibus): 0.000 Jarque-Bera (JB): 1100608.449
Skew: 1.527 Prob(JB): 0.00
Kurtosis: 9.050 Cond. No. 1.26
==============================================================================
Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.

View File

@ -0,0 +1,26 @@
OLS Regression Results
=================================================================================
Dep. Variable: number O(n+1)-replies R-squared: 0.256
Model: OLS Adj. R-squared: 0.256
Method: Least Squares F-statistic: 3.965e+04
Date: Mon, 22 Jul 2024 Prob (F-statistic): 0.00
Time: 09:31:48 Log-Likelihood: -3.4768e+05
No. Observations: 230524 AIC: 6.954e+05
Df Residuals: 230521 BIC: 6.954e+05
Df Model: 2
Covariance Type: nonrobust
====================================================================================================
coef std err t P>|t| [0.025 0.975]
----------------------------------------------------------------------------------------------------
const 0.8891 0.002 390.420 0.000 0.885 0.894
bayes-corrected (q=0.25) valence -0.3918 0.002 -171.548 0.000 -0.396 -0.387
totalvotes 0.4784 0.002 209.473 0.000 0.474 0.483
==============================================================================
Omnibus: 109314.794 Durbin-Watson: 1.837
Prob(Omnibus): 0.000 Jarque-Bera (JB): 1540320.347
Skew: 1.926 Prob(JB): 0.00
Kurtosis: 15.063 Cond. No. 1.08
==============================================================================
Notes:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.

View File

@ -0,0 +1,6 @@
,total_count,totalvotes_nonzero,totalvotes_sum,totalvotes_mean,totalvotes_std_dev,upvotes_sum,downvotes_sum,bayes-corrected (q=0.25) valence_mean,bayes-corrected (q=0.25) valence_std_dev,bayes-corrected (q=0.25) extremity_mean,bayes-corrected (q=0.25) extremity_std_dev
Total,20161317,14706588,154821490,7.679135742967585,11.556761173578584,102022297,52799193,0.17704715667464238,0.2021943857837279,0.3158469490984941,0.11041613015478122
0,6069971,4786218,77964965,12.84437190886085,15.885943210670801,50729878,27235087,0.17395713322300024,0.2242844895596835,0.3081309024315796,0.11996477068190904
1,6755090,5050120,46320518,6.857128180379536,9.434159387282262,31970589,14349929,0.19288237536756858,0.19202605012773946,0.3198901628191536,0.10879194365502998
2,3786555,2608297,18126241,4.787000584964433,7.119372189759389,11414766,6711475,0.16402235924006153,0.19272989539907023,0.31758620689084427,0.10383240571773994
3,3549701,2261953,12409766,3.496003184493567,5.5015115601260955,7907064,4502702,0.16325036748997546,0.1823236133759817,0.3211412527772316,0.09881505843280065
1 total_count totalvotes_nonzero totalvotes_sum totalvotes_mean totalvotes_std_dev upvotes_sum downvotes_sum bayes-corrected (q=0.25) valence_mean bayes-corrected (q=0.25) valence_std_dev bayes-corrected (q=0.25) extremity_mean bayes-corrected (q=0.25) extremity_std_dev
2 Total 20161317 14706588 154821490 7.679135742967585 11.556761173578584 102022297 52799193 0.17704715667464238 0.2021943857837279 0.3158469490984941 0.11041613015478122
3 0 6069971 4786218 77964965 12.84437190886085 15.885943210670801 50729878 27235087 0.17395713322300024 0.2242844895596835 0.3081309024315796 0.11996477068190904
4 1 6755090 5050120 46320518 6.857128180379536 9.434159387282262 31970589 14349929 0.19288237536756858 0.19202605012773946 0.3198901628191536 0.10879194365502998
5 2 3786555 2608297 18126241 4.787000584964433 7.119372189759389 11414766 6711475 0.16402235924006153 0.19272989539907023 0.31758620689084427 0.10383240571773994
6 3 3549701 2261953 12409766 3.496003184493567 5.5015115601260955 7907064 4502702 0.16325036748997546 0.1823236133759817 0.3211412527772316 0.09881505843280065

View File

@ -0,0 +1,28 @@
,total_count,number O(n+1)-replies_sum,number O(n+1)-replies_nonzero,totalvotes_nonzero,totalvotes_sum,upvotes_sum,downvotes_sum,valence_mean,valence_std_dev,bayes-corrected (q=0.25) valence_mean,bayes-corrected (q=0.25) valence_std_dev,extremity_mean,extremity_std_dev,bayes-corrected (q=0.25) extremity_mean,bayes-corrected (q=0.25) extremity_std_dev
Total,20161317,14091458,7495456,14706588,154821490,102022297,52799193,0.1809732449640069,0.3221017025345512,0.17704715667464238,0.2021943857837279,0.3263665242005636,0.17316382137734357,0.3158469490984941,0.11041613015478122
Backstage,2638,1309,916,2091,19339,14013,5326,0.23396256608765395,0.306585082923225,0.21223527077342733,0.18627809433377085,0.34578357774960666,0.1706915190446471,0.3284342540070973,0.10947346803113846
Career,125360,84283,47627,94139,991285,688567,302718,0.23144672748128672,0.31736287806178626,0.207642429386839,0.20352379529383485,0.3562556537779823,0.165432505887087,0.33650872389557185,0.10619423486404499
Community,2546,1519,921,1691,10943,7543,3400,0.22997949625046876,0.31967854887735475,0.200451242569652,0.17131680735740445,0.35250476788410146,0.17545113771119852,0.3275935830615364,0.09841736341890532
Culture,783764,492965,283683,594634,7485201,4965916,2519285,0.18924208094858397,0.31430902283965584,0.18237701691103533,0.2075772292325427,0.3257271885165046,0.16883248354886274,0.3165073708092221,0.11183033084670414
Economy,2532709,1753030,981305,1832061,15418671,10477493,4941178,0.19695589659717094,0.3200608942654652,0.1874348176320727,0.18779895991104745,0.33178431101377187,0.17649287038142622,0.3182130588344701,0.10772151446952792
Family,49628,31670,18194,38744,504399,350538,153861,0.2207067677046886,0.3014587355657185,0.2041527930238584,0.2020069369216948,0.33366309594582666,0.1680957128606617,0.32246786364599994,0.11428810172513852
Fitness,3010,2211,1182,2183,22484,14215,8269,0.15967373329129744,0.30431877346003455,0.1619996073865862,0.1864234078141263,0.29418798473390506,0.17756989413975396,0.29151785340526726,0.1149792183614986
Foreign affairs,3677268,2544425,1330773,2734274,33483913,22653979,10829934,0.2002575026917707,0.325382737606063,0.1904666416894296,0.21644036248740706,0.34356756409069306,0.16714752082493223,0.32992358948836636,0.1107027200883534
Health,232501,170195,87992,169188,1861800,1220143,641657,0.18424450969159725,0.32460476601354893,0.17814240568123157,0.20780662621629975,0.3319043469304209,0.17074351373987692,0.3200033262093227,0.10944699632311113
History,72480,47028,26802,56445,679183,472071,207112,0.22095860634303593,0.31534867450645176,0.2039420491794974,0.2117808348179994,0.3471692447301984,0.1665525064085087,0.3331839376145845,0.11121773599665685
International,1778,661,443,1021,5800,3874,1926,0.19351189270788866,0.3781743471452822,0.18492958397224973,0.194320028301713,0.3900060650559993,0.16806412167150314,0.3495507394881325,0.08766877038980984
Internet,498610,333659,186807,367308,3674903,2466723,1208180,0.2091647658832731,0.3286639549837689,0.19303117978437134,0.2079459094850678,0.3515812393300087,0.16781033736005121,0.3332794356286173,0.10537720414529439
Miscellaneous,1962726,1352139,729325,1449191,17475106,11899133,5575973,0.20487949983503603,0.32223613216900404,0.1930421103534628,0.21138823123717118,0.3434851196383367,0.16682222414119258,0.3292431100186108,0.10905631859394622
Mobility,554408,415352,219481,421827,3502371,2196167,1306204,0.16054863670067138,0.31191065777214666,0.1618961069183528,0.18002270627566236,0.30120556091206946,0.1798309742036998,0.2958943291943663,0.10998330012774073
Politics,5116347,3451139,1901059,3675657,39155173,25667532,13487641,0.17444454738877926,0.3163335278430911,0.17315213087529358,0.19604468474970993,0.31674249710795505,0.17370081307098184,0.3084535160005122,0.11058794557807118
Psychology,77714,49836,28755,59103,731898,505589,226309,0.20632700233260906,0.31154092970651803,0.1944627043194951,0.20658764113640296,0.3333799252712208,0.1687757327928834,0.3224848844257549,0.1127179346512217
Relationships,8131,4828,2914,6585,117075,86625,30450,0.24777040590992844,0.29358367752069375,0.22795252407820465,0.21253014623413818,0.34813759810576583,0.1623966700762943,0.33698553182471686,0.11775078466218207
Science,3525557,2774136,1307843,2480281,21660444,12904848,8755596,0.13124914209737715,0.3254561015718625,0.14358107029299916,0.1929315922045766,0.30217351871367176,0.17843527137661813,0.29726966358820944,0.10920227830101752
Services,15,6,4,13,70,49,21,0.11337188452573069,0.33244948852144557,0.16113358674678163,0.17243290163606495,0.2928590640129101,0.17757621269031232,0.3027156286778409,0.09718850862453934
Sports,742645,458996,266832,573957,6603661,4457164,2146497,0.19390481300491805,0.324823993978004,0.1866839749335055,0.21488052454498108,0.3392841168420786,0.1673196240006354,0.3276705379187469,0.1093840089279375
Start,59059,38288,22794,45209,446297,312161,134136,0.23012121622760803,0.3130036249047111,0.20696856220124274,0.20060384009293042,0.35070753025975687,0.16712187857191027,0.33303728389868575,0.10782854662594989
Style,30611,17243,10890,24054,237133,168395,68738,0.24331081020636638,0.3088338815884642,0.2153432930645136,0.20011272670414704,0.35698752853489446,0.1647288201407465,0.3384781050249686,0.10535514942392003
Tests,14585,8163,5413,11604,99542,73441,26101,0.27363177574221587,0.2996883510847475,0.23290915494157782,0.1893771434271009,0.37215267353257064,0.1618158234175073,0.3471946880707655,0.10229356775332507
Total,2638,2185,922,1915,17354,9336,8018,0.0677696797423411,0.3072866586840947,0.10190539473940045,0.18182325609165528,0.2587321299251362,0.17900538958637705,0.266230689221851,0.11332285476209328
Travel,84136,55950,32431,63101,614135,404586,209549,0.19389251358743367,0.31251346847520517,0.18297252866496708,0.19464504647573025,0.32412318682777963,0.1737874145135004,0.3130547750304372,0.1114047246370484
Your SPIEGEL,453,242,148,312,3310,2196,1114,0.18208463027330246,0.2940537652828505,0.17712455278668807,0.1727453899902895,0.29483491204446555,0.1803382964418267,0.29333866069487885,0.10993924168770208
1 total_count number O(n+1)-replies_sum number O(n+1)-replies_nonzero totalvotes_nonzero totalvotes_sum upvotes_sum downvotes_sum valence_mean valence_std_dev bayes-corrected (q=0.25) valence_mean bayes-corrected (q=0.25) valence_std_dev extremity_mean extremity_std_dev bayes-corrected (q=0.25) extremity_mean bayes-corrected (q=0.25) extremity_std_dev
2 Total 20161317 14091458 7495456 14706588 154821490 102022297 52799193 0.1809732449640069 0.3221017025345512 0.17704715667464238 0.2021943857837279 0.3263665242005636 0.17316382137734357 0.3158469490984941 0.11041613015478122
3 Backstage 2638 1309 916 2091 19339 14013 5326 0.23396256608765395 0.306585082923225 0.21223527077342733 0.18627809433377085 0.34578357774960666 0.1706915190446471 0.3284342540070973 0.10947346803113846
4 Career 125360 84283 47627 94139 991285 688567 302718 0.23144672748128672 0.31736287806178626 0.207642429386839 0.20352379529383485 0.3562556537779823 0.165432505887087 0.33650872389557185 0.10619423486404499
5 Community 2546 1519 921 1691 10943 7543 3400 0.22997949625046876 0.31967854887735475 0.200451242569652 0.17131680735740445 0.35250476788410146 0.17545113771119852 0.3275935830615364 0.09841736341890532
6 Culture 783764 492965 283683 594634 7485201 4965916 2519285 0.18924208094858397 0.31430902283965584 0.18237701691103533 0.2075772292325427 0.3257271885165046 0.16883248354886274 0.3165073708092221 0.11183033084670414
7 Economy 2532709 1753030 981305 1832061 15418671 10477493 4941178 0.19695589659717094 0.3200608942654652 0.1874348176320727 0.18779895991104745 0.33178431101377187 0.17649287038142622 0.3182130588344701 0.10772151446952792
8 Family 49628 31670 18194 38744 504399 350538 153861 0.2207067677046886 0.3014587355657185 0.2041527930238584 0.2020069369216948 0.33366309594582666 0.1680957128606617 0.32246786364599994 0.11428810172513852
9 Fitness 3010 2211 1182 2183 22484 14215 8269 0.15967373329129744 0.30431877346003455 0.1619996073865862 0.1864234078141263 0.29418798473390506 0.17756989413975396 0.29151785340526726 0.1149792183614986
10 Foreign affairs 3677268 2544425 1330773 2734274 33483913 22653979 10829934 0.2002575026917707 0.325382737606063 0.1904666416894296 0.21644036248740706 0.34356756409069306 0.16714752082493223 0.32992358948836636 0.1107027200883534
11 Health 232501 170195 87992 169188 1861800 1220143 641657 0.18424450969159725 0.32460476601354893 0.17814240568123157 0.20780662621629975 0.3319043469304209 0.17074351373987692 0.3200033262093227 0.10944699632311113
12 History 72480 47028 26802 56445 679183 472071 207112 0.22095860634303593 0.31534867450645176 0.2039420491794974 0.2117808348179994 0.3471692447301984 0.1665525064085087 0.3331839376145845 0.11121773599665685
13 International 1778 661 443 1021 5800 3874 1926 0.19351189270788866 0.3781743471452822 0.18492958397224973 0.194320028301713 0.3900060650559993 0.16806412167150314 0.3495507394881325 0.08766877038980984
14 Internet 498610 333659 186807 367308 3674903 2466723 1208180 0.2091647658832731 0.3286639549837689 0.19303117978437134 0.2079459094850678 0.3515812393300087 0.16781033736005121 0.3332794356286173 0.10537720414529439
15 Miscellaneous 1962726 1352139 729325 1449191 17475106 11899133 5575973 0.20487949983503603 0.32223613216900404 0.1930421103534628 0.21138823123717118 0.3434851196383367 0.16682222414119258 0.3292431100186108 0.10905631859394622
16 Mobility 554408 415352 219481 421827 3502371 2196167 1306204 0.16054863670067138 0.31191065777214666 0.1618961069183528 0.18002270627566236 0.30120556091206946 0.1798309742036998 0.2958943291943663 0.10998330012774073
17 Politics 5116347 3451139 1901059 3675657 39155173 25667532 13487641 0.17444454738877926 0.3163335278430911 0.17315213087529358 0.19604468474970993 0.31674249710795505 0.17370081307098184 0.3084535160005122 0.11058794557807118
18 Psychology 77714 49836 28755 59103 731898 505589 226309 0.20632700233260906 0.31154092970651803 0.1944627043194951 0.20658764113640296 0.3333799252712208 0.1687757327928834 0.3224848844257549 0.1127179346512217
19 Relationships 8131 4828 2914 6585 117075 86625 30450 0.24777040590992844 0.29358367752069375 0.22795252407820465 0.21253014623413818 0.34813759810576583 0.1623966700762943 0.33698553182471686 0.11775078466218207
20 Science 3525557 2774136 1307843 2480281 21660444 12904848 8755596 0.13124914209737715 0.3254561015718625 0.14358107029299916 0.1929315922045766 0.30217351871367176 0.17843527137661813 0.29726966358820944 0.10920227830101752
21 Services 15 6 4 13 70 49 21 0.11337188452573069 0.33244948852144557 0.16113358674678163 0.17243290163606495 0.2928590640129101 0.17757621269031232 0.3027156286778409 0.09718850862453934
22 Sports 742645 458996 266832 573957 6603661 4457164 2146497 0.19390481300491805 0.324823993978004 0.1866839749335055 0.21488052454498108 0.3392841168420786 0.1673196240006354 0.3276705379187469 0.1093840089279375
23 Start 59059 38288 22794 45209 446297 312161 134136 0.23012121622760803 0.3130036249047111 0.20696856220124274 0.20060384009293042 0.35070753025975687 0.16712187857191027 0.33303728389868575 0.10782854662594989
24 Style 30611 17243 10890 24054 237133 168395 68738 0.24331081020636638 0.3088338815884642 0.2153432930645136 0.20011272670414704 0.35698752853489446 0.1647288201407465 0.3384781050249686 0.10535514942392003
25 Tests 14585 8163 5413 11604 99542 73441 26101 0.27363177574221587 0.2996883510847475 0.23290915494157782 0.1893771434271009 0.37215267353257064 0.1618158234175073 0.3471946880707655 0.10229356775332507
26 Total 2638 2185 922 1915 17354 9336 8018 0.0677696797423411 0.3072866586840947 0.10190539473940045 0.18182325609165528 0.2587321299251362 0.17900538958637705 0.266230689221851 0.11332285476209328
27 Travel 84136 55950 32431 63101 614135 404586 209549 0.19389251358743367 0.31251346847520517 0.18297252866496708 0.19464504647573025 0.32412318682777963 0.1737874145135004 0.3130547750304372 0.1114047246370484
28 Your SPIEGEL 453 242 148 312 3310 2196 1114 0.18208463027330246 0.2940537652828505 0.17712455278668807 0.1727453899902895 0.29483491204446555 0.1803382964418267 0.29333866069487885 0.10993924168770208

BIN
results/Extended_Fig_1.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 90 KiB

BIN
results/Fig_2a.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 196 KiB

BIN
results/Fig_2b.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 88 KiB

BIN
results/Fig_2c.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 91 KiB

BIN
results/Fig_3a.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 225 KiB

BIN
results/Fig_3b.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 61 KiB

BIN
results/Fig_4a.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 168 KiB

BIN
results/Fig_4b.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 64 KiB

File diff suppressed because it is too large Load Diff

Binary file not shown.

2
src/__init__.py Normal file
View File

@ -0,0 +1,2 @@
"""Functions to handle data and perform analysis on Spiegel Online Data"""

174
src/analysis.py Normal file
View File

@ -0,0 +1,174 @@
from statsmodels.regression.linear_model import RegressionResults
from src.analysis_functions.comparison_variance_in_and_between_group import (
ComparisonVariance,
)
from src.analysis_functions.descriptive import DescriptiveAnalysis
from src.analysis_functions.regression import Regression
from src.analysis_functions.specific_analysis.increase_per_up_and_downvote import (
InfluenceOfUpAndDownvotesOnReplies,
)
from src.analysis_functions.ttest import TTest
from src.analysis_functions.pearson_correlation import PearsonCorrelation
from src.analysis_functions.visualization import DataVisualizer
from src.analysis_wrappers.comparison_variance_in_and_between_group_wrapper import (
run_comparison_variance_in_and_between_group,
)
from src.analysis_wrappers.descriptive_wrapper import run_descriptive_analysis
from src.analysis_wrappers.regression_wrapper import run_regression
from src.analysis_wrappers.pearson_correlation_wrapper import run_pearson_correlation
from src.analysis_wrappers.specific_analysis_wrappers.get_function_inverse_bayes_transformed_regression import (
run_get_function_inverse_bayes_transformed_regression,
)
from src.analysis_wrappers.specific_analysis_wrappers.increase_per_up_and_downvote_wrapper import (
run_report_influence_of_up_and_downvotes_on_replies,
)
from src.analysis_wrappers.ttest_wrapper import run_ttest
from src.analysis_wrappers.visualization_wrapper import run_visualization
from src.data_classes.parameters_analysis_comparison_variance_in_and_between_group import (
ComparisonVarianceInAndBetweenGroupParameters,
)
from src.data_classes.parameters_analysis_get_function_inverse_bayes_transformed_regression import (
GetFunctionInverseBayesTransformedRegressionParameters,
)
from src.data_classes.parameters_analysis_influence_of_up_and_downvotes import (
InfluenceOfVotesParameters,
)
from src.data_classes.parameters_analysis_regression import (
BayesianRegressionParameters,
LinearRegressionParameters,
GroupedLinearRegressionParameters,
)
from src.data_classes.parameters_analysis_pearson_correlation import (
PearsonCorrelationParameters,
)
from src.data_classes.parameters_analysis_ttest import (
TTestParameters,
PairedTTestParameters,
)
from src.utils.helper_functions import FunctionData
def run_analyses(analyses: dict, preprocessed_datasets: dict) -> None:
"""
Orchestrates the execution of various statistical analyses and visualizations based on a configuration file.
This function initializes analysis and visualization classes, assigns preprocessed data to analyses,
categorizes analyses by type, and sequentially executes them. It supports descriptive statistics,
regression analyses, t-tests, Pearson correlation analyses, comparison of variance, influence of up and downvotes,
and data visualization. The function ensures that the necessary data and results are passed between analyses
and visualizations as required.
Parameters
----------
analyses : dict
A dictionary containing configurations for different categories of analyses
(descriptive, analysis, visualization) and their parameters.
preprocessed_datasets : dict
A dictionary mapping dataset names to their preprocessed forms. This data is used across various analyses.
Raises
------
ValueError
If an unknown analysis type is encountered in the configuration.
"""
regression: Regression = Regression()
comparison_variance: ComparisonVariance = ComparisonVariance()
pearson_correlation: PearsonCorrelation = PearsonCorrelation()
ttest: TTest = TTest()
influence_up_and_downvotes: InfluenceOfUpAndDownvotesOnReplies = InfluenceOfUpAndDownvotesOnReplies()
descriptive: DescriptiveAnalysis = DescriptiveAnalysis()
visualizer: DataVisualizer = DataVisualizer()
for category in ["descriptive", "analysis", "visualization"]:
if category in analyses:
for analysis in analyses[category]:
analysis.data = preprocessed_datasets[analysis.dataset]
regression_analyses: list = []
pearson_correlation_analyses: list = []
ttest_analyses: list = []
comparison_variance_in_and_between_group_analyses: list = []
influence_up_and_downvotes_analyses: list = []
get_function_inverse_bayes_transformed_regression_analyses: list = []
if "descriptive" in analyses:
run_descriptive_analysis(descriptive, analyses["descriptive"])
for analysis in analyses.get("analysis", []):
if isinstance(
analysis,
(
LinearRegressionParameters,
GroupedLinearRegressionParameters,
BayesianRegressionParameters,
),
):
regression_analyses.append(analysis)
elif isinstance(analysis, ComparisonVarianceInAndBetweenGroupParameters):
comparison_variance_in_and_between_group_analyses.append(analysis)
elif isinstance(analysis, PearsonCorrelationParameters):
pearson_correlation_analyses.append(analysis)
elif isinstance(analysis, (TTestParameters, PairedTTestParameters)):
ttest_analyses.append(analysis)
elif isinstance(analysis, InfluenceOfVotesParameters):
influence_up_and_downvotes_analyses.append(analysis)
elif isinstance(
analysis, GetFunctionInverseBayesTransformedRegressionParameters
):
get_function_inverse_bayes_transformed_regression_analyses.append(analysis)
else:
raise ValueError(f"Unknown analysis type for analysis: {analysis}")
regression_results: dict[str, RegressionResults] = {}
if regression_analyses:
regression_results: dict[str, RegressionResults] = run_regression(
regression, regression_analyses
)
if comparison_variance_in_and_between_group_analyses:
run_comparison_variance_in_and_between_group(
comparison_variance, comparison_variance_in_and_between_group_analyses
)
if pearson_correlation_analyses:
run_pearson_correlation(pearson_correlation, pearson_correlation_analyses)
ttest_results: dict[str, tuple[float, float, float]] = {}
if ttest_analyses:
ttest_results: dict[str, tuple[float, float, float]] = run_ttest(
ttest, ttest_analyses
)
if influence_up_and_downvotes_analyses:
if regression_results == {}:
raise ValueError(
"Regression results are required for the influence of up and downvotes analysis"
)
run_report_influence_of_up_and_downvotes_on_replies(
influence_up_and_downvotes,
influence_up_and_downvotes_analyses,
regression_results,
)
functions: dict[str, FunctionData] = {}
if get_function_inverse_bayes_transformed_regression_analyses:
functions: dict[
str, FunctionData
] = run_get_function_inverse_bayes_transformed_regression(
get_function_inverse_bayes_transformed_regression_analyses,
regression_results,
)
if "visualization" in analyses:
run_visualization(
visualizer,
analyses["visualization"],
regression_results,
functions,
ttest_results,
)

View File

View File

@ -0,0 +1,91 @@
import os
from pathlib import Path
import pandas as pd
from src.data_loading_and_saving.print_and_save_results import print_and_save_result
class ComparisonVariance:
"""
A class used to calculate the Pearson's correlation coefficient between two variables.
Attributes:
----------
print_result: bool
A flag to determine if the result should be printed.
save_result: bool
A flag to determine if the result should be saved.
filepath: str
The directory where the result should be saved.
Methods
-------
calculate_correlation(data: pd.DataFrame, first_group_name: str, second_group_name: str, name_save_file: Path):
This method calculates Pearson's correlation coefficient for the given columns
"""
def __init__(
self,
print_result: bool = True,
save_result: bool = True,
filepath: str = "results/",
):
"""
Constructs all the necessary attributes for the PearsonCorrelation object.
Parameters
----------
print_result: bool
A flag to determine if the result should be printed.
save_result: bool
A flag to determine if the result should be saved.
filepath: str
The directory where the result should be saved.
"""
self.print_result: bool = print_result
self.save_result: bool = save_result
self.filepath: str = filepath
if not os.path.isdir(filepath):
os.makedirs(filepath)
def compare_ingroup_intergroup_variance(
self, data: pd.DataFrame, variable: str, group: str, name_save_file: Path
) -> None:
"""
Compares the variance within a group to the variance between groups for a specified variable.
This method calculates the total variance of the variable, the average variance of the variable
within each group, and the variance of the variable between groups. It then prints and/or saves
these results based on the object's attributes.
Parameters
----------
data : pd.DataFrame
The dataset containing the variable and group columns.
variable : str
The name of the column representing the variable for which variance is calculated.
group : str
The name of the column representing the groups.
name_save_file : Path
The name of the file to which the result will be saved (if save_result is True).
"""
total_var: float = data[variable].var()
between_group_var: float = data.groupby(group)[variable].var().mean()
within_group_var: float = total_var - between_group_var
results: str = f"""
Total variance: {total_var}
Between-group variance: {between_group_var}
Within-group variance: {within_group_var}
"""
print_and_save_result(
self.print_result,
self.save_result,
self.filepath,
results,
name_save_file,
)

View File

@ -0,0 +1,351 @@
import os
from typing import Union, Optional
from pathlib import Path
import numpy as np
import pandas as pd
from src.data_classes.parameters_descriptive_overview import Metric
from src.data_loading_and_saving.print_and_save_results import print_and_save_result
class DescriptiveAnalysis:
"""
A class used to perform descriptive data analysis.
Attributes
----------
print_result: bool
A flag used to indicate if the function should print the result to the standard output.
save_result: bool
A flag used to indicate if the function should save the result to a file.
filepath: str
The directory path where the result files will be saved if save_result is True.
...
Methods
-------
create_descriptives_for_metrics(data, metrics, name_save_file, group_by=None):
Performs multiple descriptive analyses on the provided dataset and either prints or saves the result.
create_descriptive_aggregated_for_metrics(data, variables, aggregation_function, group_by, name_save_file):
Performs descriptive analysis on the provided dataset with aggregation and grouping, and either prints
or saves the result.
give_percentage_of_dataset_under_condition(data, variable, comparison, condition, name_save_file):
Calculates and prints/saves the percentage of the dataset that meets a specified condition.
_compute_metrics(group_name, data, metrics, group_column=None):
Helper method to compute specified metrics on the data.
_count_values(data, column):
Counts the non-null values in a specified column or in the dataframe if no column is specified.
_count_nonzero(data, column):
Counts the non-zero/True values in a specified column.
_count_unique(data, column):
Counts the unique values in a specified column.
_sum_values(data, column):
Sums the values in a specified column.
_mean_values(data, column):
Calculates the mean of the values in a specified column.
_std_dev(data, column):
Calculates the standard deviation of the values in a specified column.
"""
def __init__(
self,
print_result: bool = True,
save_result: bool = True,
filepath: str = "results/",
):
"""
Constructs all the necessary attributes for the DescriptiveAnalysis object.
Parameters
----------
print_result: bool
A flag to determine if the result should be printed.
save_result: bool
A flag to determine if the result should be saved.
filepath: str
The directory where the result should be saved.
"""
self.print_result: bool = print_result
self.save_result: bool = save_result
self.filepath: str = filepath
if not os.path.isdir(filepath):
os.makedirs(filepath)
def create_descriptives_for_metrics(
self,
data: pd.DataFrame,
metrics: list[Metric],
name_save_file: Path,
group_by: Optional[str] = None,
) -> None:
"""
This method performs multiple descriptive analysis on the provided dataset and either prints or saves the result
Parameters
----------
data: pandas.DataFrame
The input dataframe which contains the data.
metrics: MetricList
The list of metrics to be calculated.
name_save_file: str
The name of the file to which the result will be saved (if self.save_result is True).
group_by: str
The column to group by. This gives the option to perform the analysis on each unique group member.
Returns
-------
None
"""
dataframes: list = []
result_dataframes: pd.DataFrame = self._compute_metrics("Total", data, metrics)
dataframes.append(result_dataframes)
if group_by:
grouped_dataframe = data.groupby(group_by)
for group_name, group in grouped_dataframe:
result_dataframes: pd.DataFrame = self._compute_metrics(
group_name, group, metrics
)
dataframes.append(result_dataframes)
result_dataframes: pd.DataFrame = pd.concat(dataframes)
result_dataframes.set_index(result_dataframes.columns[0], inplace=True)
print_and_save_result(
self.print_result,
self.save_result,
self.filepath,
result_dataframes,
name_save_file,
)
def create_descriptive_aggregated_for_metrics(
self,
data: pd.DataFrame,
variables: list[str],
aggregation_function: str,
group_by: str,
name_save_file: Path,
) -> None:
"""
This method performs multiple descriptive analysis on the provided dataset with grouping.
Parameters
----------
data : pd.DataFrame
The dataset to perform descriptive analysis on.
variables : list[str]
The list of columns we want information on.
aggregation_function : str
The method to aggregate the data. Either 'sum' or 'mean'.
group_by : str
The column to group by.
name_save_file : str
The name for saving the result.
Returns
-------
None
"""
if aggregation_function == "sum":
if "Count" in variables:
variables.remove("Count")
grouped_data: pd.DataFrame = (
data.groupby(group_by)[variables]
.sum()
.aggregate(["mean", "std", "max", "min"])
)
count_data: pd.DataFrame = (
data.groupby(group_by)
.size()
.reset_index(name="Count")["Count"]
.aggregate(["mean", "std", "max", "min"])
)
grouped_data: pd.DataFrame = pd.concat(
[count_data, grouped_data], axis=1
)
else:
grouped_data: pd.DataFrame = (
data.groupby(group_by)[variables]
.sum()
.aggregate(["mean", "std", "max", "min"])
)
elif aggregation_function == "mean":
if "Count" in variables:
variables.remove("Count")
grouped_data: pd.DataFrame = (
data.groupby(group_by)[variables]
.mean()
.aggregate(["mean", "std", "max", "min"])
)
count_data: pd.DataFrame = (
data.groupby(group_by)
.size()
.reset_index(name="Count")["Count"]
.aggregate(["mean", "std", "max", "min"])
)
grouped_data: pd.DataFrame = pd.concat(
[count_data, grouped_data], axis=1
)
else:
grouped_data: pd.DataFrame = (
data.groupby(group_by)[variables]
.mean()
.aggregate(["mean", "std", "max", "min"])
)
else:
raise ValueError(f"Invalid aggregation: {aggregation_function}")
print_and_save_result(
self.print_result,
self.save_result,
self.filepath,
grouped_data,
name_save_file,
)
def give_percentage_of_dataset_under_condition(
self,
data: pd.DataFrame,
variable: str,
comparison: str,
condition: Union[int, float],
name_save_file: Path,
) -> None:
"""
Calculates the percentage of the dataset that meets a specified condition and either prints or saves the result.
This method evaluates a condition on a specified column of the dataset and calculates the percentage of rows
that meet this condition. The result can be printed to the console or saved to a file, depending on the
object's attributes.
Parameters
----------
data : pd.DataFrame
The dataset to evaluate the condition on.
variable : str
The column name on which the condition will be applied.
comparison : str
The type of comparison to perform. Valid options are "smaller", "larger", or "not".
condition : Union[int, float]
The value to compare against the data in the specified column.
name_save_file : Path
The path (including filename) where the result should be saved if saving is enabled.
Returns
-------
None
"""
total_data: int = len(data)
conditional_data: int = 0
if comparison == "smaller":
conditional_data: int = len(data[data[variable] <= condition])
elif comparison == "larger":
conditional_data: int = len(data[data[variable] >= condition])
elif comparison == "not":
conditional_data: int = len(data[data[variable] != condition])
else:
ValueError("Invalid comparison type")
percentage: float = conditional_data / total_data * 100
percentage_result: str = (
f"The percentage of the dataset under that condition is {percentage} %"
)
print_and_save_result(
self.print_result,
self.save_result,
self.filepath,
percentage_result,
name_save_file,
)
def _compute_metrics(
self, group_name, data: pd.DataFrame, metrics: list[Metric], group_column=None
) -> pd.DataFrame:
"""
Computes specified metrics on the given dataset and returns the results in a DataFrame.
This method iterates over a list of Metric objects, each defining an operation (e.g., count, sum, mean) and
a column on which the operation is to be performed. It constructs a result dictionary where each key is a
metric name with the operation and column, and the value is the result of the operation. This dictionary is
then converted to a DataFrame and returned.
Parameters
----------
group_name : str
The name of the group for which metrics are being computed. This is used as a prefix in the result
dictionary keys if not None.
data : pd.DataFrame
The dataset on which the metrics are to be computed.
metrics : list[Metric]
A list of Metric objects, each specifying an operation and a column.
group_column : str, optional
The name of the column by which the data was grouped, if any. This is used in the result dictionary keys.
Returns
-------
pd.DataFrame
A DataFrame containing the computed metrics, with each row representing the results for a group (if
group_name is not None) or the entire dataset.
"""
result_dict: dict = {group_column: group_name} if group_name is not None else {}
for metric in metrics:
operation: str = metric.operation
column: str = metric.column
if operation == "count":
result_dict[
f'{column if column else "total"}_count'
] = self._count_values(data, column)
elif operation == "count_nonzero":
result_dict[f"{column}_nonzero"] = self._count_nonzero(data, column)
elif operation == "count_unique":
result_dict[f"{column}_unique"] = self._count_unique(data, column)
elif operation == "sum":
result_dict[f"{column}_sum"] = self._sum_values(data, column)
elif operation == "mean":
result_dict[f"{column}_mean"] = self._mean_values(data, column)
elif operation == "std_dev":
result_dict[f"{column}_std_dev"] = self._std_dev(data, column)
return pd.DataFrame(result_dict, index=[0])
@staticmethod
def _count_values(data: pd.DataFrame, column: str) -> int:
return len(data[column].dropna()) if column else len(data)
@staticmethod
def _count_nonzero(data: pd.DataFrame, column: str) -> int:
data_type = data[column].dtype
if data_type == bool:
return len(data[data[column] == True])
return len(data[data[column] != 0])
@staticmethod
def _count_unique(data: pd.DataFrame, column: str) -> int:
first_element = data[column].dropna().iloc[0]
if isinstance(first_element, (list, np.ndarray)):
flattend_entries = pd.Series(
[item for sublist in data[column] for item in sublist]
)
return flattend_entries.nunique()
else:
return data[column].nunique()
@staticmethod
def _sum_values(data: pd.DataFrame, column: str) -> Union[int, float]:
return data[column].sum()
@staticmethod
def _mean_values(data: pd.DataFrame, column: str) -> Union[int, float]:
return data[column].mean()
@staticmethod
def _std_dev(data: pd.DataFrame, column: str) -> Union[int, float]:
return data[column].std()

View File

@ -0,0 +1,94 @@
import os
from pathlib import Path
import pandas as pd
from scipy.stats import pearsonr
from src.data_loading_and_saving.print_and_save_results import print_and_save_result
class PearsonCorrelation:
"""
A class used to calculate the Pearson's correlation coefficient between two variables.
Attributes:
----------
print_result: bool
A flag to determine if the result should be printed.
save_result: bool
A flag to determine if the result should be saved.
filepath: str
The directory where the result should be saved.
Methods
-------
calculate_correlation(data: pd.DataFrame, first_group_name: str, second_group_name: str, name_save_file: Path):
This method calculates Pearson's correlation coefficient for the given columns
"""
def __init__(
self,
print_result: bool = True,
save_result: bool = True,
filepath: str = "results/",
):
"""
Constructs all the necessary attributes for the PearsonCorrelation object.
Parameters
----------
print_result: bool
A flag to determine if the result should be printed.
save_result: bool
A flag to determine if the result should be saved.
filepath: str
The directory where the result should be saved.
"""
self.print_result: bool = print_result
self.save_result: bool = save_result
self.filepath: str = filepath
if not os.path.isdir(filepath):
os.makedirs(filepath)
def calculate_correlation(
self,
data: pd.DataFrame,
first_group_name: str,
second_group_name: str,
name_save_file: Path,
) -> None:
"""
This method calculates Pearson's correlation coefficient for the given columns
and either prints or saves the result based on the object properties.
Parameters
----------
data: pd.DataFrame
The data frame containing the data.
first_group_name: str
The name of the first group.
second_group_name: str
The name of the second group.
name_save_file: Path
The name of the file where the result should be saved.
"""
data: pd.DataFrame = data[[first_group_name, second_group_name]].dropna()
group_1: pd.DataFrame = data[first_group_name]
group_2: pd.DataFrame = data[second_group_name]
pearson_correlation: float
p_value: float
pearson_correlation, p_value = pearsonr(group_1, group_2)
pearson_correlation_summary: str = (
f"Pearson correlation between {first_group_name} and {second_group_name}: {pearson_correlation}\n"
f"P-value: {p_value}"
)
print_and_save_result(
self.print_result,
self.save_result,
self.filepath,
pearson_correlation_summary,
name_save_file,
)

View File

@ -0,0 +1,502 @@
import math
import os
from typing import Union
from pathlib import Path
import numpy as np
import pandas as pd
from rpy2 import robjects as ro
from rpy2.robjects import pandas2ri, Formula
from sklearn.preprocessing import StandardScaler
from statsmodels import api as sm
from statsmodels.iolib.summary import Summary
from statsmodels.regression.linear_model import RegressionResults
from src.data_loading_and_saving.print_and_save_results import print_and_save_result
from src.utils.handle_r_dependencies import BAS
class Regression:
"""
A class used to perform Linear and Bayesian regression analyses.
...
Attributes
----------
print_result: bool
A flag used to indicate if the function should print the result to the standard output.
save_result: bool
A flag used to indicate if the function should save the result to a file.
filepath: str
The directory path where the result files will be saved if save_result is True.
Methods
-------
linear_regression(data, x_vector, y, standardize, name_save_file) -> RegressionResults:
Performs an OLS (Ordinary Least Squares) linear regression on the provided dataset.
linear_regression_grouped(data, x_vector, y, dictionary_aggregation_methods_for_data_columns,
column_to_group_by, standardize, name_save_file) -> RegressionResults:
Performs Linear Regression on the data grouped by the given column as per the aggregation dictionary.
predict_percentage_increase_between_liner_model_points(model, data_point_1, data_point_2) -> float:
Calculates the percentage increase in fitted values between two different data points using a given model.
report_effect_size_of_model(model, name_save_file) -> None:
Computes and reports the effect size of the model
(r-squared, Cohen's f, and equivalent Cohen's d for the regression model).
bayesian_regression(data, x_vector, y, name_save_file) -> None:
Performs a Bayesian linear regression on the provided dataset.
_create_dataframe_of_bayesian_regression(summary, x_vector) -> pd.DataFrame:
Transforms the provided Bayesian regression summary into a DataFrame.
_clean_names(name) -> str:
Cleans the input string by replacing certain characters with underscores or removing them.
_clean_column_names(dataframe) -> pd.DataFrame:
Cleans the DataFrame column names using the "_clean_names" method.
_get_clean_x_vector(x_vector) -> list[str]:
Cleans the elements of the input list using the "_clean_names" method.
"""
def __init__(
self,
print_result: bool = True,
save_result: bool = True,
filepath: str = "results/",
):
"""
Initializes the Regression object with the provided parameters.
Parameters
----------
print_result: bool, optional
A flag to indicate if the function should print the result to the standard output. Default is True.
save_result: bool, optional
A flag to indicate if the function should save the result to a file. Default is True.
filepath: str, optional
The directory path where the result files will be saved if save_result is True. Default is "results/".
"""
self.print_result: bool = print_result
self.save_result: bool = save_result
self.filepath: str = filepath
if not os.path.isdir(filepath):
os.makedirs(filepath)
def linear_regression(
self,
data: pd.DataFrame,
x_vector: list[str],
y: str,
standardize: bool = False,
report_effect_size: bool = False,
name_save_file: Path = "",
) -> RegressionResults:
"""
This method performs Ordinary Least Squares (OLS) Linear Regression using the given parameters
and either prints or saves the result based on the Regression object properties.
Parameters
----------
data: pandas.DataFrame
The input dataframe which contains the data.
x_vector: list
The list of column names to be used as independent variables in the regression model.
y: str
The column name to be used as dependent variable in the regression model.
standardize: bool
If the independent variables should be standardized before fitting for better comparison.
report_effect_size: bool
If the effect size of the model should be reported (r-squared, Cohen's f, and equivalent Cohen's d).
name_save_file: str
The name of the file to which the result will be saved (if self.save_result is True).
Returns
-------
model: RegressionResults
The fitted regression model.
"""
data: pd.DataFrame = data.dropna(subset=x_vector)
data: pd.DataFrame = data.dropna(subset=y)
x_vector_data: pd.DataFrame = data[x_vector]
y_data: pd.Series = data[y]
if standardize:
scaler: StandardScaler = StandardScaler()
x_vector_data_standardized: np.ndarray = scaler.fit_transform(x_vector_data)
x_vector_data: pd.DataFrame = pd.DataFrame(
x_vector_data_standardized, columns=x_vector
)
x_vector_data.set_index(y_data.index, inplace=True)
x_vector_data: pd.DataFrame = sm.add_constant(x_vector_data)
model: RegressionResults = sm.OLS(y_data, x_vector_data).fit()
linear_regression_summary: Summary = model.summary()
print_and_save_result(
self.print_result,
self.save_result,
self.filepath,
linear_regression_summary,
name_save_file,
)
if report_effect_size:
name_save_file_effect_size: Path = name_save_file.with_stem(
name_save_file.stem + "_effect_size"
)
self._report_effect_size_of_model(model, name_save_file_effect_size)
return model
def linear_regression_grouped(
self,
data: pd.DataFrame,
x_vector: list[str],
y: str,
dictionary_aggregation_methods_for_data_columns: dict[str, str],
column_to_group_by: str,
standardize: bool = False,
report_effect_size: bool = False,
print_detailed_coefficients: bool = False,
name_save_file: Path = "",
) -> RegressionResults:
"""
This method performs OLS Linear Regression on the data grouped by the group_by
as per the aggregation dictionary and then the performs regression analysis.
Parameters
----------
data: pandas.DataFrame
The input dataframe which contains the data.
x_vector: list
The list of column names to be used as independent variables in the regression model.
y: str
The column name to be used as dependent variable in the regression model.
dictionary_aggregation_methods_for_data_columns: dict
The dictionary specifying how to aggregate each column before regression.
The keys of the dictionary should include all columns in X and y.
column_to_group_by: str
The column name to group the data by before aggregating.
name_save_file: str
The name of the file to which the result will be saved (if self.save_result is True).
standardize: bool
If the regression should be performed standardized instead to return beta factors.
report_effect_size: bool
If the effect size of the model should be reported (r-squared, Cohen's f, and equivalent Cohen's d).
print_detailed_coefficients: bool
If the coefficients should be printed separately with 10 point float accuracy and 95% CI.
Returns
-------
model: RegressionResults
The fitted regression model.
"""
all_cols = set(x_vector + [y])
if not all_cols.issubset(
set(dictionary_aggregation_methods_for_data_columns.keys())
):
raise ValueError(
"dictionary_aggregation_methods_for_data_columns should contain all columns from X and y."
)
if column_to_group_by not in data.columns:
raise ValueError(
f"'{column_to_group_by}' column to group by not found in data."
)
grouped_data = (
data.groupby(column_to_group_by)
.agg(dictionary_aggregation_methods_for_data_columns)
.reset_index()
)
model = self.linear_regression(
data=grouped_data,
x_vector=x_vector,
y=y,
standardize=standardize,
report_effect_size=report_effect_size,
name_save_file=name_save_file,
)
if print_detailed_coefficients:
coefficients = model.params
confidence_intervals = model.conf_int()
for name, coefficient in coefficients.items():
confidence_interval = confidence_intervals.loc[name]
detailed_coefficient_information: str = f"{name}: {coefficient: .10f} (CI: [{confidence_interval[0]: .10f}, {confidence_interval[1]: .10f}])"
print_and_save_result(
self.print_result,
self.save_result,
self.filepath,
detailed_coefficient_information,
name_save_file,
)
return model
@staticmethod
def predict_percentage_increase_between_liner_model_points(
model: RegressionResults,
data_point_1: Union[list, np.array],
data_point_2: Union[list, np.array],
) -> float:
"""
Calculate the percentage increase in fitted values between two different data points using a given model.
Parameters
----------
model: statsmodels.regression.linear_model.OLS
The fitted regression model.
data_point_1: list or numpy.array
The first data point (a vector of X values).
data_point_2: list or numpy.array
The second data point (a vector of X values).
Returns
-------
percentage_increase: float
The percentage increase in fitted value from data_point1 to data_point2.
"""
if not isinstance(data_point_1, pd.Series):
data_point_1 = pd.Series(data_point_1, index=model.model.exog_names[1:])
if not isinstance(data_point_2, pd.Series):
data_point_2 = pd.Series(data_point_2, index=model.model.exog_names[1:])
if len(data_point_1) != len(data_point_2):
raise ValueError("Data points must have the same dimension.")
if len(data_point_1) != len(model.params) - 1:
raise ValueError("Dimensions of data points and model do not match.")
x_vector_data: pd.DataFrame = pd.DataFrame(
[data_point_1, data_point_2], columns=model.model.data.orig_exog.columns[1:]
)
x_vector_data: pd.DataFrame = sm.add_constant(x_vector_data)
predictions_for_both_datapoints: np.ndarray = model.predict(x_vector_data)
percentage_increase: float = (
(predictions_for_both_datapoints[1] - predictions_for_both_datapoints[0])
/ predictions_for_both_datapoints[0]
) * 100
return percentage_increase
def _report_effect_size_of_model(
self, model: RegressionResults, name_save_file: Path
) -> None:
"""
Computes and reports the effect size of the model (r-squared, Cohen's f and equivalent Cohen's d
for the regression model) and either print or save it based on the Regression object properties.
Parameters
----------
model: RegressionResults
The regression model results obtained from statsmodels regression.
name_save_file: Path
The name of the file to which the result will be saved if self.save_result is True.
"""
r_squared: int = model.rsquared
f_squared: float = r_squared / (1 - r_squared)
cohens_f: float = math.sqrt(f_squared)
equivalent_cohens_d: float = 2 * cohens_f
effect_size_model: str = f"""
R-Square R^2: {r_squared}
Cohen's f: {cohens_f}
Equivalent Cohen's d: {equivalent_cohens_d}
"""
print_and_save_result(
self.print_result,
self.save_result,
self.filepath,
effect_size_model,
name_save_file,
)
def bayesian_regression(
self, data: pd.DataFrame, x_vector: list[str], y: str, name_save_file: Path
) -> None:
"""
This method performs Bayesian Regression using the given parameters and either
prints or saves the result based on the Regression object properties.
the results can be interpreted in the following way:
- `P(B != 0 | Y)`: This column gives the probability that the coefficient,
associated with the factor (the B-value), is not zero given the data Y.
This is a way of measuring the relevance and significance of the predictive factor.
The higher the score, the more likely it is that the factor has an impact on your outcome variable.
- `Model 1, Model 2, Model 3, etc`: These columns represent different models that have been built.
The values in these columns are the specific coefficient values for each factor within each model.
- `BF`: BF is short for Bayes Factor which indicates the strength of evidence for a model as
compared to an alternative model. Higher BF values indicate stronger evidence for a model.
- `PostProbs`: Posterior probabilities for each model. These add up to 1 across all models and
give the probability of each model being the "best" model given the data.
- `R2`: Shows the proportion of the variance for a dependent variable that's explained by
independent variables in the model. Close to 1 indicates the model explains a large amount of the variance.
- `dim`: The dimensionality of the model, which is basically the number of parameters in each model.
- `logmarg`: It is the logarithm of the marginal likelihood for each model.
This is a factor that is used in determining the posterior probabilities of each model.
Parameters
----------
data: pandas.DataFrame
The input dataframe which contains the data.
x_vector: list
The list of column names to be used as independent variables in the regression model.
y: str
The column name to be used as dependent variable in the regression model.
name_save_file: str
The name of the file to which the result will be saved (if self.save_result is True).
Returns
-------
None
"""
data: pd.DataFrame = data.dropna(subset=x_vector)
pandas2ri.activate()
data: pd.DataFrame = self._clean_column_names(data)
x_vector: list[str] = self._get_clean_x_vector(x_vector)
y: str = self._clean_names(y)
formula: Formula = Formula(y + " ~ " + " + ".join(x_vector))
data_r = pandas2ri.py2rpy(data)
bayesian_model = BAS.bas_lm(
formula=formula,
data=data_r,
method="MCMC",
prior="ZS-null",
modelprior=BAS.uniform(),
)
bayesian_regression_summary: np.ndarray = ro.r["summary"](bayesian_model)
try:
dataframe_bayesian_regression_summary = (
self._create_dataframe_of_bayesian_regression(
bayesian_regression_summary, x_vector
)
)
except ValueError:
raise ValueError(
"The number of bayesian models does not match the expected values."
)
print_and_save_result(
self.print_result,
self.save_result,
self.filepath,
dataframe_bayesian_regression_summary,
name_save_file,
)
@staticmethod
def _create_dataframe_of_bayesian_regression(
summary: np.ndarray, x_vector: list[str]
) -> pd.DataFrame:
"""
Create a DataFrame from the summary of Bayesian regression results.
Parameters
----------
summary: np.ndarray
The Bayesian regression summary obtained from performing a Bayesian linear regression.
x_vector: list[str]
The list of column names used as independent variables in the Bayesian regression model.
Returns
-------
pd.DataFrame
A DataFrame that presents the Bayesian regression's summary, including the probability
of the regression coefficients not being zero, model number, intercept, independent variables,
Bayes Factor (BF), posterior probabilities (PostProbs), R squared (R2), dimension (dim),
and log marginal likelihood (logmarg).
"""
base_columns: list[str] = ["P(B != 0 | Y)"]
model_columns: list[str] = [
"model {}".format(i + 1) for i in range(summary.shape[1] - 1)
]
columns: list[str] = base_columns + model_columns
index: list[str] = [
"Intercept",
*x_vector,
"BF",
"PostProbs",
"R2",
"dim",
"logmarg",
]
dataframe_summary: pd.DataFrame = pd.DataFrame(
summary, columns=columns, index=index
)
return dataframe_summary
@staticmethod
def _clean_names(name: str) -> str:
"""
This method performs cleaning of individual name (could be column name or value in X).
Cleaning includes replacing certain characters with underscores or removing them.
Parameters
----------
name: str
Original name (un-cleaned).
Returns
-------
str
Cleaned up name.
"""
return (
name.replace(" ", "_")
.replace("(", "")
.replace(")", "")
.replace("-", "_")
.replace("+", "_")
.replace("=", "")
.replace(".", "")
)
def _clean_column_names(self, dataframe: pd.DataFrame) -> pd.DataFrame:
"""
This method performs cleaning of DataFrame column names using the method clean_names.
It cleans a deep copy to not alter the original dataframe.
Parameters
----------
dataframe: pd.DataFrame
DataFrame with original (un-cleaned) column names.
Returns
-------
pd.DataFrame
DataFrame with cleaned column names.
"""
dataframe: pd.DataFrame = dataframe.copy()
dataframe.columns = [self._clean_names(col) for col in dataframe.columns]
return dataframe
def _get_clean_x_vector(self, x_vector: list[str]) -> list[str]:
"""
This method uses clean_names to clean the individual elements/column names in x_vector.
Parameters
----------
x_vector: list[str]
List with original (un-cleaned) elements.
Returns
-------
list[str]
List where all elements have been cleaned.
"""
return [self._clean_names(x) for x in x_vector]

View File

@ -0,0 +1,57 @@
from collections import namedtuple
from typing import NamedTuple
import pandas as pd
from statsmodels.regression.linear_model import RegressionResults
from src.utils.helper_functions import FunctionData
def get_function_inverse_bayes_transformed_regression(data: pd.DataFrame, model: RegressionResults) -> FunctionData:
"""
Calculate and return a function representing the inverse Bayes transformed regression.
This function constructs a parameter tuple for the regression function, and then returns
a FunctionData object containing the regression
function and its parameters.
Parameters
---------
data: pd.DataFrame
The dataset containing the 'bayes-corrected (q=0.25) valence' column.
model: RegressionResults
The regression model results from which the gradient and intercept parameters are extracted.
Returns
-------
FunctionData: An object containing the regression function and its parameters.
"""
average_valence: float = data["bayes-corrected (q=0.25) valence"].mean()
Param = namedtuple(
"Param",
[
"average_valence",
"gradient_valence",
"gradient_totalvotes",
"intercept",
],
)
def function(x: float, y: float, parameters: Param) -> float:
return (
parameters.gradient_valence
* (-1 * (x / (x + y) + parameters.average_valence / (x + y)) - 0.5)
+ parameters.gradient_totalvotes * (x + y)
+ parameters.intercept
)
params: NamedTuple = Param(
average_valence=average_valence,
gradient_valence=model.params.iloc[1],
gradient_totalvotes=model.params.iloc[2],
intercept=model.params.iloc[0],
)
function_data: FunctionData = FunctionData(function, params)
return function_data

View File

@ -0,0 +1,168 @@
import os
from pathlib import Path
from typing import Union, Optional
import pandas as pd
from statsmodels.regression.linear_model import RegressionResults
from src.analysis_functions.regression import Regression
from src.data_loading_and_saving.print_and_save_results import print_and_save_result
from src.utils.helper_functions import (
calculate_inverse_bayes_correction,
transform_to_bayes_corrected_valence,
)
class InfluenceOfUpAndDownvotesOnReplies:
"""
A class used to perform a dataset specific analysis on the influence of upvotes and downvotes
on the number of replies based on a linear regression model for totalvotes and valence
Attributes
----------
print_result: bool
A flag used to indicate if the function should print the result to the standard output.
save_result: bool
A flag used to indicate if the function should save the result to a file.
filepath: str
The directory path where the result files will be saved if save_result is True.
...
Methods
-------
report_increase_per_up_and_downvote_from_totalvotes_and_valence
(data: pd.DataFrame, weight_as_distribution_quantile: bool, weight_m: float, model: RegressionResults,
step: list, startpoint: Union[str, list], name_save_file: Optional[Path]) -> None:
Gives the % increase in reply likelihood for a given step in upvotes and downvotes
according to a linear regression model
"""
def __init__(
self,
print_result: bool = True,
save_result: bool = True,
filepath: str = "results/",
):
"""
Constructs all the necessary attributes for the InfluenceOfUpAndDownvotesOnReplies object.
Parameters
----------
print_result: bool
A flag to determine if the result should be printed.
save_result: bool
A flag to determine if the result should be saved.
filepath: str
The directory where the result should be saved.
"""
self.print_result: bool = print_result
self.save_result: bool = save_result
self.filepath: str = filepath
if not os.path.isdir(filepath):
os.makedirs(filepath)
def report_increase_per_up_and_downvote_from_totalvotes_and_valence(
self,
data: pd.DataFrame,
weight_as_distribution_quantile: bool,
weight_m: float,
model: RegressionResults,
step: list = None,
startpoint: Union[str, list] = "average",
name_save_file: Optional[Path] = None,
) -> None:
"""
Reports the percentage increase in reply likelihood for specified upvote and downvote steps
from a given startpoint, using a linear regression model.
Parameters
----------
data : pd.DataFrame
The dataset containing 'totalvotes', 'valence', and other relevant metrics.
weight_as_distribution_quantile : bool
Determines if weight_m should be treated as a quantile value for weighting totalvotes.
weight_m : float
The weight factor or quantile value for calculating weighted measures.
model : RegressionResults
The fitted linear regression model used for prediction.
step : list, optional
A list containing the step increase for upvotes and downvotes respectively.
startpoint : Union[str, list], optional
The starting point for calculation. Can be 'average' or a list of [totalvotes, bayes_corrected_valence].
name_save_file : Optional[Path], optional
The name of the file to save the result to.
Returns
-------
None
"""
startpoint_totalvotes: int = 0
startpoint_bayes_corrected_valence: int = 0
average_valence: float = data["valence"].mean()
if isinstance(startpoint, str) and startpoint.lower() == "average":
startpoint_totalvotes: float = data["totalvotes"].mean()
startpoint_bayes_corrected_valence: float = data[
"bayes-corrected (q=0.25) valence"
].mean()
if isinstance(startpoint, list):
startpoint_totalvotes: Union[int, float] = startpoint[0]
startpoint_bayes_corrected_valence: Union[int, float] = startpoint[1]
else:
ValueError("startpoint must be a valid point or 'average'")
if weight_as_distribution_quantile:
weight_m: float = data["totalvotes"].quantile(q=weight_m)
non_bayes_corrected_valence: float = (
calculate_inverse_bayes_correction(
bayes_corrected_value=startpoint_bayes_corrected_valence,
volume=startpoint_totalvotes,
weight_factor_m=weight_m,
average_measure=average_valence,
)
)
downvote_equivalent_average_bayes_corrected_valence: float = (
- (non_bayes_corrected_valence - 0.5) * startpoint_totalvotes
)
average_bayes_corrected_negativty_plus: float = transform_to_bayes_corrected_valence(
upvotes=startpoint_totalvotes
- downvote_equivalent_average_bayes_corrected_valence
+ step[0],
downvotes=downvote_equivalent_average_bayes_corrected_valence + step[1],
average_valence=average_valence,
weight_factor_m=weight_m,
)
increase_per_step: float = (
Regression().predict_percentage_increase_between_liner_model_points(
model=model,
data_point_1=[
startpoint_bayes_corrected_valence,
startpoint_totalvotes,
],
data_point_2=[
average_bayes_corrected_negativty_plus,
startpoint_totalvotes + step[0] + step[1],
],
)
)
result = f"""
your startpoint was: bayes-correced-valence {startpoint_bayes_corrected_valence}, totalvotes {startpoint_totalvotes}
for a step with {step[0]} upvotes and {step[1]} downvotes increase
you obtain an endpoint of: bayes-correced-valence {average_bayes_corrected_negativty_plus}, totalvotes {startpoint_totalvotes + step[0] + step[1]}
the increase in replies is {increase_per_step} %
"""
print_and_save_result(
self.print_result,
self.save_result,
self.filepath,
result,
name_save_file,
)

View File

@ -0,0 +1,195 @@
import os
import pandas as pd
import numpy as np
from scipy import stats as stats
from scipy.stats import ttest_ind, ttest_rel
from pathlib import Path
from src.data_loading_and_saving.print_and_save_results import print_and_save_result
class TTest:
"""
A class used to perform a T-test analysis.
...
Attributes
----------
print_result: bool
A flag used to indicate if the function should print the result to the standard output.
save_result: bool
A flag used to indicate if the function should save the result to a file.
filepath: str
The directory path where the result files will be saved if save_result is True.
Methods
-------
perform_ttest(data, first_group_name, second_group_name, name_save_file) -> None:
Performs an independent samples T-test for the two specified groups in the provided dataset.
perform_paired_ttest(data, first_group_name, second_group_name, name_save_file) -> tuple[float, float, float]:
Performs a paired samples T-test on the two specified groups in the provided dataset.
Returns the mean difference with the 95% confidence interval.
"""
def __init__(
self,
print_result: bool = True,
save_result: bool = True,
filepath: str = "results/",
):
"""
Initializes the TTest object with the provided parameters.
Parameters
----------
print_result: bool, optional
A flag to indicate if the function should print the result to the standard output. Default is True.
save_result: bool, optional
A flag to indicate if the function should save the result to a file. Default is True.
filepath: str, optional
The directory path where the result files will be saved if save_result is True. Default is "results/".
"""
self.print_result: bool = print_result
self.save_result: bool = save_result
self.filepath: str = filepath
if not os.path.isdir(filepath):
os.makedirs(filepath)
def perform_ttest(
self,
data: pd.DataFrame,
first_group_name: str,
second_group_name: str,
name_save_file: Path,
) -> None:
"""
This method performs a T-test for the means of two independent samples of scores using
the given columns and either prints or saves the result based on the TTest object properties.
Parameters
----------
data: pandas.DataFrame
The input dataframe which contains the data.
first_group_name: str
The name of the first column to be used in the t-test.
second_group_name: str
The name of the second column to be used in the t-test.
name_save_file: str
The name of the file to which the result will be saved (if self.save_result is True).
Returns
-------
None
"""
group_1: pd.DataFrame = data[first_group_name].dropna()
group_2: pd.DataFrame = data[second_group_name].dropna()
degrees_of_freedom: int = len(group_1) + len(group_2) - 2
t_statistic: float
p_value: float
t_statistic, p_value = ttest_ind(group_1, group_2)
mean_group_1: float = group_1.mean()
mean_group_2: float = group_2.mean()
standard_deviation_group_1: float = group_1.std()
standard_deviation_group_2: float = group_2.std()
ttest_summary: str = (
f"Mean of {first_group_name}: {mean_group_1}\n"
f"Mean of {second_group_name}: {mean_group_2}\n"
f"Standard Deviation of {first_group_name}: {standard_deviation_group_1}\n"
f"Standard Deviation of {second_group_name}: {standard_deviation_group_2}\n"
f"Degrees of Freedom: {degrees_of_freedom}\n"
f"T-statistic: {t_statistic}\n"
f"P-value: {p_value}"
)
print_and_save_result(
self.print_result,
self.save_result,
self.filepath,
ttest_summary,
name_save_file,
)
def perform_paired_ttest(
self,
data: pd.DataFrame,
first_group_name: str,
second_group_name: str,
name_save_file: Path,
) -> tuple[float, float, float]:
"""
Performs a paired sample t-test and calculates the effect size (Cohen's d) using the given columns
Parameters
----------
data : pd.DataFrame
The DataFrame containing the data of two related groups to be compared
first_group_name : str
The name of the first group (column)
second_group_name : str
the name of the second group (column)
name_save_file: Path
The path of the file to save the result in.
Returns
-------
mean_difference : float
The mean difference between the two samples
confidence_interval[0] : float
The lower bound of the 95% confidence interval
confidence_interval[1] : float
The upper bound of the 95% confidence interval
"""
data: pd.DataFrame = data[[first_group_name, second_group_name]].dropna()
group_1: pd.DataFrame = data[first_group_name]
group_2: pd.DataFrame = data[second_group_name]
degrees_of_freedom: int = len(group_1) - 1
t_statistic: float
p_value: float
t_statistic, p_value = ttest_rel(group_1, group_2)
mean_group_1: float = group_1.mean()
mean_group_2: float = group_2.mean()
standard_deviation_group_1: float = group_1.std()
standard_deviation_group_2: float = group_2.std()
pooled_standard_deviation: float = np.sqrt(
(standard_deviation_group_1**2 + standard_deviation_group_2**2) / 2
)
cohens_d: float = (mean_group_1 - mean_group_2) / pooled_standard_deviation
mean_difference: float = mean_group_1 - mean_group_2
standard_error_difference: float = np.std(group_1 - group_2, ddof=1) / np.sqrt(
len(group_1)
)
confidence_interval: np.ndarray[float] = stats.t.interval(
0.95, len(group_1) - 1, loc=mean_difference, scale=standard_error_difference
)
paired_ttest_summary: str = (
f"Mean of {first_group_name}: {mean_group_1}\n"
f"Mean of {second_group_name}: {mean_group_2}\n"
f"Standard Deviation of {first_group_name}: {standard_deviation_group_1}\n"
f"Standard Deviation of {second_group_name}: {standard_deviation_group_2}\n"
f"Degrees of Freedom: {degrees_of_freedom}\n"
f"Cohen's d: {cohens_d}\n"
f"T-statistic: {t_statistic}\n"
f"P-value: {p_value}"
)
print_and_save_result(
self.print_result,
self.save_result,
self.filepath,
paired_ttest_summary,
name_save_file,
)
return mean_difference, confidence_interval[0], confidence_interval[1]

File diff suppressed because it is too large Load Diff

View File

View File

@ -0,0 +1,42 @@
from src.analysis_functions.comparison_variance_in_and_between_group import (
ComparisonVariance,
)
from src.data_classes.parameters_analysis_comparison_variance_in_and_between_group import (
ComparisonVarianceInAndBetweenGroupParameters,
)
from src.utils.helper_logging import log_comparison_variance_details
def run_comparison_variance_in_and_between_group(
comparison_variance: ComparisonVariance,
analyses_list: list[ComparisonVarianceInAndBetweenGroupParameters],
):
"""
Run a comparison between the mean variance in a variable grouped by a condition and the variance
between group members based on a list of parameter objects.
This function iterates over a list of ComparisonVarianceInAndBetweenGroupParameters objects,
and then reports the total variance, variance between group members and mean variance of group members for
each pair of variables specified in the ComparisonVarianceInAndBetweenGroupParameters object.
Parameters
----------
comparison_variance: ComparisonVariance
An instance of the ComparisonVariance class.
analyses_list: list[ComparisonVarianceInAndBetweenGroupParameters]
A list of ComparisonVarianceInAndBetweenGroupParameters objects.
Each object contains the parameters for a single variation comparison analysis.
Returns
-------
None
"""
for analysis_config in analyses_list:
log_comparison_variance_details(analysis_config)
comparison_variance.compare_ingroup_intergroup_variance(
data=analysis_config.data,
variable=analysis_config.variable,
group=analysis_config.group,
name_save_file=analysis_config.name_save_file,
)

View File

@ -0,0 +1,73 @@
from src.analysis_functions.descriptive import DescriptiveAnalysis
from src.data_classes.parameters_descriptive_aggregated import (
DescriptiveAggregatedParameters,
)
from src.data_classes.parameters_descriptive_overview import (
DescriptiveOverviewParameters,
)
from src.data_classes.parameters_descriptive_percentage_of_dataset_under_condition import (
DescriptivePercentageOfDatasetUnderConditionParameters,
)
from src.data_classes.parameters_general import GeneralParameters
from src.utils.helper_logging import log_descriptive_analysis_details
def run_descriptive_analysis(
descriptive: DescriptiveAnalysis, analyses_list: list[GeneralParameters]
):
"""
Run descriptive analyses based on a list of parameter objects.
This function iterates over a list of GeneralParameters objects,
logs the details of each analysis, and then performs the appropriate
descriptive analysis based on the type of the Parameters object.
Parameters
----------
descriptive: DescriptiveAnalysis
An instance of the DescriptiveAnalysis class.
analyses_list: list[PlotParameters]
A list of PlotParameters objects.
Each object contains the parameters for a single visualization.
Raises
------
ValueError: If the type of the GeneralParameters object is not recognized or not a descriptive analysis.
Returns
-------
None
"""
for analysis_config in analyses_list:
log_descriptive_analysis_details(analysis_config)
if isinstance(analysis_config, DescriptiveAggregatedParameters):
descriptive.create_descriptive_aggregated_for_metrics(
data=analysis_config.data,
variables=analysis_config.variables,
aggregation_function=analysis_config.aggregation_function,
group_by=analysis_config.group_by,
name_save_file=analysis_config.name_save_file,
)
elif isinstance(analysis_config, DescriptiveOverviewParameters):
descriptive.create_descriptives_for_metrics(
data=analysis_config.data,
metrics=analysis_config.metrics,
group_by=analysis_config.group_by,
name_save_file=analysis_config.name_save_file,
)
elif isinstance(
analysis_config, DescriptivePercentageOfDatasetUnderConditionParameters
):
descriptive.give_percentage_of_dataset_under_condition(
data=analysis_config.data,
variable=analysis_config.variable,
comparison=analysis_config.comparison,
condition=analysis_config.condition,
name_save_file=analysis_config.name_save_file,
)
else:
raise ValueError(
f"Invalid type of descriptive analysis requested {type(analysis_config)}"
)

View File

@ -0,0 +1,39 @@
from src.analysis_functions.pearson_correlation import PearsonCorrelation
from src.data_classes.parameters_analysis_pearson_correlation import (
PearsonCorrelationParameters,
)
from src.utils.helper_logging import log_pearson_correlation_details
def run_pearson_correlation(
pearson_correlation: PearsonCorrelation,
analyses_list: list[PearsonCorrelationParameters],
):
"""
Run Pearson correlation analyses based on a list of parameter objects.
This function iterates over a list of PearsonCorrelationParameters objects,
and then calculates the Pearson correlation for each pair of variables specified
in the PearsonCorrelationParameters object.
Parameters
----------
pearson_correlation: PearsonCorrelation
An instance of the PearsonCorrelation class.
analyses_list: list[PearsonCorrelationParameters
A list of PearsonCorrelationParameters objects.
Each object contains the parameters for a single Pearson correlation analysis.
Returns
-------
None
"""
for analysis_config in analyses_list:
log_pearson_correlation_details(analysis_config)
pearson_correlation.calculate_correlation(
data=analysis_config.data,
first_group_name=analysis_config.variable_1,
second_group_name=analysis_config.variable_2,
name_save_file=analysis_config.name_save_file,
)

View File

@ -0,0 +1,85 @@
from statsmodels.regression.linear_model import RegressionResults
from src.analysis_functions.regression import Regression
from src.data_classes.parameters_analysis_regression import (
RegressionParameters,
BayesianRegressionParameters,
LinearRegressionParameters,
GroupedLinearRegressionParameters,
)
from src.utils.helper_logging import log_regression_details
def run_regression(
regression: Regression, analyses_list: list[RegressionParameters]
) -> dict[str, RegressionResults]:
"""
Run regression analyses based on a list of parameter objects.
This function iterates over a list of RegressionParameters objects,
and then performs the appropriate regression analysis based on the
type of the RegressionParameters object.
Parameters
----------
regression: Regression
An instance of the Regression class.
analyses_list: list[RegressionParameters]
A list of RegressionParameters objects.
Each object contains the parameters for a single regression analysis.
Raises
------
ValueError: If the type of the RegressionParameters object is not recognized.
Returns
-------
dict[str, RegressionResults]
A dictionary of regression results, where the key is the name of the analysis
and the value is the regression results.
"""
regression_results: dict = {}
for analysis_config in analyses_list:
result = None
if isinstance(analysis_config, LinearRegressionParameters):
log_regression_details(analysis_config, "Linear")
result = regression.linear_regression(
data=analysis_config.data,
x_vector=analysis_config.independent_variables,
y=analysis_config.dependent_variable,
standardize=analysis_config.standardize,
name_save_file=analysis_config.name_save_file,
)
elif isinstance(analysis_config, BayesianRegressionParameters):
log_regression_details(analysis_config, "Bayesian")
regression.bayesian_regression(
data=analysis_config.data,
x_vector=analysis_config.independent_variables,
y=analysis_config.dependent_variable,
name_save_file=analysis_config.name_save_file,
)
elif isinstance(analysis_config, GroupedLinearRegressionParameters):
log_regression_details(analysis_config, "Grouped")
result = regression.linear_regression_grouped(
data=analysis_config.data,
x_vector=analysis_config.independent_variables,
y=analysis_config.dependent_variable,
dictionary_aggregation_methods_for_data_columns=analysis_config.dictionary_aggregation_methods,
column_to_group_by=analysis_config.group_by,
standardize=analysis_config.standardize,
print_detailed_coefficients=analysis_config.print_detailed_coefficients,
name_save_file=analysis_config.name_save_file,
)
else:
raise ValueError(f"Unknown parameter type: {type(analysis_config)}")
regression_results[analysis_config.name]: RegressionResults = result
return regression_results

View File

@ -0,0 +1,52 @@
import pandas as pd
from statsmodels.regression.linear_model import RegressionResults
from src.analysis_functions.specific_analysis.get_function_inverse_bayes_transformed_regression import (
get_function_inverse_bayes_transformed_regression,
)
from src.data_classes.parameters_analysis_get_function_inverse_bayes_transformed_regression import (
GetFunctionInverseBayesTransformedRegressionParameters,
)
from src.utils.helper_functions import FunctionData
from src.utils.helper_logging import (
log_get_function_inverse_bayes_transformed_regression,
)
def run_get_function_inverse_bayes_transformed_regression(
analyses_list: list[GetFunctionInverseBayesTransformedRegressionParameters],
regression_models: dict[str, RegressionResults],
) -> dict[str, FunctionData]:
"""
Executes the inverse Bayes transformed regression analysis for a list of analysis configurations.
This function iterates over a list of analysis configurations, logs the configuration details,
performs the inverse Bayes transformed regression analysis using the specified regression model,
and collects the results in a dictionary.
Parameters
----------
analyses_list : list[GetFunctionInverseBayesTransformedRegressionParameters]
A list of parameters for each analysis to be run. Each item in the list is an instance
of GetFunctionInverseBayesTransformedRegressionParameters, which includes the data and model name.
regression_models : dict[str, RegressionResults]
A dictionary mapping model names to their corresponding fitted regression models.
Returns
-------
dict[str, FunctionData]
A dictionary mapping the name of each analysis to its resulting FunctionData object.
"""
functions: dict = {}
for analysis_config in analyses_list:
log_get_function_inverse_bayes_transformed_regression(analysis_config)
function: FunctionData = get_function_inverse_bayes_transformed_regression(
data=analysis_config.data,
model=regression_models[analysis_config.model_name],
)
functions[analysis_config.name] = function
return functions

View File

@ -0,0 +1,51 @@
from statsmodels.regression.linear_model import RegressionResults
from src.analysis_functions.specific_analysis.increase_per_up_and_downvote import (
InfluenceOfUpAndDownvotesOnReplies,
)
from src.data_classes.parameters_analysis_influence_of_up_and_downvotes import (
InfluenceOfVotesParameters,
)
from src.utils.helper_logging import log_influence_of_up_and_downvotes_on_replies
def run_report_influence_of_up_and_downvotes_on_replies(
influence_of_up_and_downvotes: InfluenceOfUpAndDownvotesOnReplies,
analyses_list: list[InfluenceOfVotesParameters],
regression_models: dict[str, RegressionResults],
) -> None:
"""
Run specific analyses to find the effect of up-and downvotes on replies based on a list of parameter objects.
This function iterates over a list of InfluenceOfVotesParameters objects,
and then calculates the influence of up-and downvotes on replies based on
the parameters in each object and a given regression model.
Parameters
----------
influence_of_up_and_downvotes: InfluenceOfUpAndDownvotesOnReplies
An instance of the InfluenceOfUpAndDownvotesOnReplies class.
analyses_list: list[PearsonCorrelationParameters
A list of PearsonCorrelationParameters objects.
Each object contains the parameters for a single Pearson correlation analysis.
regression_models: dict[str, RegressionResults]
A dictionary of regression models, where the key is the model name and the value is the regression model.
Created via the regression_wrappers.run_regression function.
Returns
-------
None
"""
for analysis_config in analyses_list:
log_influence_of_up_and_downvotes_on_replies(analysis_config)
influence_of_up_and_downvotes.report_increase_per_up_and_downvote_from_totalvotes_and_valence(
data=analysis_config.data,
weight_as_distribution_quantile=analysis_config.weight_as_distribution_quantile,
weight_m=analysis_config.weight_m,
model=regression_models[analysis_config.model_name],
step=analysis_config.step,
startpoint=analysis_config.startpoint,
name_save_file=analysis_config.name_save_file,
)

View File

@ -0,0 +1,57 @@
from src.analysis_functions.ttest import TTest
from src.data_classes.parameters_analysis_ttest import (
TTestParameters,
PairedTTestParameters,
)
from src.utils.helper_logging import log_ttest_details
def run_ttest(
ttest: TTest, analyses_list: list[TTestParameters]
) -> dict[str, tuple[float, float, float]]:
"""
Run t-test analyses based on a list of parameter objects.
This function iterates over a list of TTestParameters objects,
logs the details of each analysis, and then performs the appropriate
t-test analysis based on the type of the TTestParameters object.
Parameters
----------
ttest: TTest
An instance of the TTest class.
analyses_list: list[TTestParameters]
A list of TTestParameters objects.
Each object contains the parameters for a single t-test analysis.
Returns
-------
dict[str, tuple[float, float, float]]
"""
ttest_results: dict = {}
for analysis_config in analyses_list:
result = None
if isinstance(analysis_config, PairedTTestParameters):
log_ttest_details(analysis_config, "Paired")
result = ttest.perform_paired_ttest(
data=analysis_config.data,
first_group_name=analysis_config.variable_1,
second_group_name=analysis_config.variable_2,
name_save_file=analysis_config.name_save_file,
)
else:
log_ttest_details(analysis_config, "")
ttest.perform_ttest(
data=analysis_config.data,
first_group_name=analysis_config.variable_1,
second_group_name=analysis_config.variable_2,
name_save_file=analysis_config.name_save_file,
)
ttest_results[analysis_config.name] = result
return ttest_results

View File

@ -0,0 +1,360 @@
from statsmodels.regression.linear_model import RegressionResults
from src.analysis_functions.visualization import DataVisualizer
from src.data_classes.parameters_plot_barchart import BarChartPlotParameters
from src.data_classes.parameters_plot_boxplot import BoxPlotParameters
from src.data_classes.parameters_plot_contourplot import ContourPlotParameters
from src.data_classes.parameters_plot_count_distribution import (
CountDistributionPlotParameters,
)
from src.data_classes.parameters_plot_densityplot import DensityPlotParameters
from src.data_classes.parameters_plot_forestplot import ForestPlotParameters
from src.data_classes.parameters_plot_forestplot_paired_ttest import (
ForestPlotPairedTTestParameters,
)
from src.data_classes.parameters_plot_grouped_histogram import (
GroupedHistogramParameters,
)
from src.data_classes.parameters_plot_heatmap import HeatmapParameters
from src.data_classes.parameters_plot_hexbinplot import HexbinPlotParameters
from src.data_classes.parameters_plot_histogram import HistogramPlotParameters
from src.data_classes.parameters_plot_percentage_stacked_barchart import (
PercentageStackedBarChartPlotParameters,
)
from src.data_classes.parameters_plot_ridgelineplot import RidgelineParameters
from src.data_classes.parameters_plot_simple_scatterplot import (
SimpleScatterPlotParameters,
)
from src.data_classes.parameters_plot_stacked_barchart import (
StackedBarChartPlotParameters,
)
from src.data_classes.parameters_plot_surfaceplot import SurfacePlotParameters
from src.data_classes.parameters_plot_violinplot import ViolinPlotParameters
from src.data_classes.parameters_visualization import PlotParameters
from src.utils.helper_functions import FunctionData
from src.utils.helper_logging import log_visualization_details
def run_visualization(
visualizer: DataVisualizer,
analyses_list: list[PlotParameters],
regression_results: dict[str, RegressionResults],
functions: dict[str, FunctionData],
ttest_results: dict[str, tuple[float, float, float]],
) -> None:
"""
Run visualization analyses based on a list of parameter objects.
This function iterates over a list of PlotParameters objects,
logs the details of each analysis, and then performs the appropriate
visualization based on the type of the PlotParameters object.
Parameters
----------
visualizer: DataVisualizer
An instance of the DataVisualizer class.
analyses_list: list[PlotParameters]
A list of PlotParameters objects.
Each object contains the parameters for a single visualization.
regression_results: dict[str, RegressionResults]
A dictionary mapping regression model names to their results.
functions: dict[str, FunctionData]
A dictionary mapping function names to their data.
ttest_results: dict[str, tuple[float, float, float]]
A dictionary mapping paired t-test names to their results.
Raises
------
ValueError: If the type of the PlotParameters object is not recognized.
Returns
-------
None
"""
for analysis_config in analyses_list:
log_visualization_details(analysis_config)
if isinstance(analysis_config, BarChartPlotParameters):
visualizer.create_bar_chart(
data=analysis_config.data,
variable_x_axis=analysis_config.variable_x_axis,
variable_y_axis=analysis_config.variable_y_axis,
x_axis_label=analysis_config.x_axis_label,
y_axis_label=analysis_config.y_axis_label,
chart_orientation=analysis_config.chart_orientation,
sort_order=analysis_config.sort_order,
title=analysis_config.title,
name_save_file=analysis_config.name_save_file,
custom_order=analysis_config.custom_order,
)
elif isinstance(analysis_config, BoxPlotParameters):
visualizer.create_box_plot(
data=analysis_config.data,
variable_1=analysis_config.variable_1,
variable_2=analysis_config.variable_2,
x_axis_label=analysis_config.x_axis_label,
y_axis_label=analysis_config.y_axis_label,
title=analysis_config.title,
name_save_file=analysis_config.name_save_file,
)
elif isinstance(analysis_config, ContourPlotParameters):
visualizer.create_contour_plot(
function=functions[analysis_config.function_name],
x_axis_maximum=analysis_config.x_axis_maximum,
y_axis_maximum=analysis_config.y_axis_maximum,
x_axis_label=analysis_config.x_axis_label,
y_axis_label=analysis_config.y_axis_label,
title=analysis_config.title,
name_save_file=analysis_config.name_save_file,
)
elif isinstance(analysis_config, HistogramPlotParameters):
visualizer.create_histogram(
data=analysis_config.data,
variable=analysis_config.variable,
x_axis_limits=analysis_config.x_axis_limits,
x_axis_logarithmic_scaling=analysis_config.x_axis_logarithmic_scaling,
y_axis_logarithmic_scaling=analysis_config.y_axis_logarithmic_scaling,
x_axis_label=analysis_config.x_axis_label,
y_axis_label=analysis_config.y_axis_label,
title=analysis_config.title,
name_save_file=analysis_config.name_save_file,
)
elif isinstance(analysis_config, CountDistributionPlotParameters):
visualizer.create_count_distribution(
data=analysis_config.data,
variable=analysis_config.variable,
x_axis_limits=analysis_config.x_axis_limits,
x_axis_logarithmic_scaling=analysis_config.x_axis_logarithmic_scaling,
y_axis_logarithmic_scaling=analysis_config.y_axis_logarithmic_scaling,
x_axis_label=analysis_config.x_axis_label,
y_axis_label=analysis_config.y_axis_label,
title=analysis_config.title,
name_save_file=analysis_config.name_save_file,
)
elif isinstance(analysis_config, DensityPlotParameters):
visualizer.create_density_plot(
data=analysis_config.data,
variable_x_axis=analysis_config.variable_x_axis,
variable_y_axis=analysis_config.variable_y_axis,
data_breakpoints=analysis_config.data_breakpoints,
title=analysis_config.title,
name_save_file=analysis_config.name_save_file,
)
elif isinstance(analysis_config, ForestPlotParameters):
visualizer.create_forest_plot(
regression_models=_get_labeled_models_for_forest_plot(
analysis_config, regression_results
),
coefficient_names=analysis_config.coefficient_names,
sort_by_size=analysis_config.sort_by_size,
x_axis_minimum=analysis_config.x_axis_minimum,
x_axis_maximum=analysis_config.x_axis_maximum,
dotsize=analysis_config.dotsize,
colors=analysis_config.colors,
name_save_file=analysis_config.name_save_file,
)
elif isinstance(analysis_config, ForestPlotPairedTTestParameters):
visualizer.create_forest_plot_paired_ttest(
paired_ttests=_get_labeled_ttests_for_forest_plot(
analysis_config, ttest_results
),
x_axis_minimum=analysis_config.x_axis_minimum,
x_axis_maximum=analysis_config.x_axis_maximum,
dotsize=analysis_config.dotsize,
name_save_file=analysis_config.name_save_file,
)
elif isinstance(analysis_config, GroupedHistogramParameters):
visualizer.create_grouped_histogram(
data=analysis_config.data,
group_by=analysis_config.group_by,
aggregation_column=analysis_config.aggregation_variable,
aggregation_function=analysis_config.aggregation_function,
x_axis_label=analysis_config.x_axis_label,
y_axis_label=analysis_config.y_axis_label,
title=analysis_config.title,
name_save_file=analysis_config.name_save_file,
)
elif isinstance(analysis_config, HeatmapParameters):
visualizer.create_heatmap(
data=analysis_config.data,
axis_variables=analysis_config.axis_variables,
heat_variable=analysis_config.heat_variable,
max_values_axes=analysis_config.axis_maxima,
min_values_axes=analysis_config.axis_minima,
log_option=analysis_config.logarithmic_heat_scaling,
name_save_file=analysis_config.name_save_file,
)
elif isinstance(analysis_config, HexbinPlotParameters):
visualizer.create_hexbin_plot(
data=analysis_config.data,
variable_x_axis=analysis_config.variable_x_axis,
variable_y_axis=analysis_config.variable_y_axis,
x_axis_maximum=analysis_config.x_axis_maximum,
y_axis_maximum=analysis_config.y_axis_maximum,
trendline=analysis_config.trendline,
log_scale=analysis_config.logarithmic_hex_scaling,
title=analysis_config.title,
name_save_file=analysis_config.name_save_file,
)
elif isinstance(analysis_config, PercentageStackedBarChartPlotParameters):
visualizer.create_percentage_stacked_bar_chart(
data=analysis_config.data,
variable_x_axis=analysis_config.variable_x_axis,
variables_to_compare=analysis_config.variables_to_compare,
chart_orientation=analysis_config.chart_orientation,
sort_order=analysis_config.sort_order,
title=analysis_config.title,
name_save_file=analysis_config.name_save_file,
)
elif isinstance(analysis_config, RidgelineParameters):
visualizer.create_ridgeline_plot(
data=analysis_config.data,
x_axis_variable=analysis_config.variable_x_axis,
y_axis_variable=analysis_config.variable_y_axis,
data_breakpoints=analysis_config.data_breakpoints,
title=analysis_config.title,
name_save_file=analysis_config.name_save_file,
)
elif isinstance(analysis_config, StackedBarChartPlotParameters):
visualizer.create_stacked_bar_chart(
data=analysis_config.data,
variable_x_axis=analysis_config.variable_x_axis,
variable_y_axis=analysis_config.variable_y_axis,
x_axis_label=analysis_config.x_axis_label,
y_axis_label=analysis_config.y_axis_label,
hue=analysis_config.hue,
chart_orientation=analysis_config.chart_orientation,
sort_order=analysis_config.sort_order,
title=analysis_config.title,
name_save_file=analysis_config.name_save_file,
custom_order=analysis_config.custom_order,
)
elif isinstance(analysis_config, SimpleScatterPlotParameters):
visualizer.create_scatter_plot_simple(
data=analysis_config.data,
variable_x_axis=analysis_config.variable_x_axis,
variable_y_axis=analysis_config.variable_y_axis,
title=analysis_config.title,
name_save_file=analysis_config.name_save_file,
)
elif isinstance(analysis_config, SurfacePlotParameters):
visualizer.generate_surface_plot(
function=functions[analysis_config.function_name],
x_axis_maximum=analysis_config.x_axis_maximum,
y_axis_maximum=analysis_config.y_axis_maximum,
x_axis_label=analysis_config.x_axis_label,
y_axis_label=analysis_config.y_axis_label,
z_axis_label=analysis_config.z_axis_label,
elevation_angle=analysis_config.elevation_angle,
azimuth_angle=analysis_config.azimuth_angle,
title=analysis_config.title,
name_save_file=analysis_config.name_save_file,
)
elif isinstance(analysis_config, ViolinPlotParameters):
visualizer.create_violin_plot(
data=analysis_config.data,
variable_x_axis=analysis_config.variable_x_axis,
variable_y_axis=analysis_config.variable_y_axis,
x_axis_label=analysis_config.x_axis_label,
y_axis_label=analysis_config.y_axis_label,
title=analysis_config.title,
name_save_file=analysis_config.name_save_file,
)
else:
raise ValueError(
f"Invalid type of visualization requested {type(analysis_config)}"
)
def _get_labeled_models_for_forest_plot(
analysis_config: ForestPlotParameters,
regression_results: dict[str, RegressionResults],
) -> dict:
"""
Maps regression model names to their labels for forest plot visualization.
This function takes an analysis configuration for a forest plot and a dictionary
of regression results. It maps the specified regression model names to their
corresponding labels as defined in the analysis configuration. This mapping is
used for labeling the models in the forest plot visualization.
Parameters
----------
analysis_config : ForestPlotParameters
The configuration parameters for the forest plot, including the names and
labels of the regression models to be used.
regression_results : dict[str, RegressionResults]
A dictionary mapping model names to their corresponding fitted regression models.
Returns
-------
dict
A dictionary mapping the labels (as specified in the analysis configuration)
to the corresponding regression models.
"""
mapping_regression_model_names_to_labels: dict = {
name: label
for name, label in zip(
analysis_config.regression_model_names,
analysis_config.regression_model_labels,
)
if name in regression_results.keys()
}
selected_models: dict = {
name: regression_results[name]
for name in mapping_regression_model_names_to_labels.keys()
}
labeled_models: dict = {
mapping_regression_model_names_to_labels[name]: model
for name, model in selected_models.items()
}
return labeled_models
def _get_labeled_ttests_for_forest_plot(
analysis_config: ForestPlotPairedTTestParameters,
ttest_results: dict[str, tuple[float, float, float]],
) -> dict:
"""
Maps paired t-test names to their labels for forest plot visualization.
This function takes an analysis configuration for a forest plot that includes
paired t-tests and a dictionary of t-test results. It maps the specified t-test
names to their corresponding labels as defined in the analysis configuration.
This mapping is used for labeling the t-tests in the forest plot visualization.
Parameters
----------
analysis_config : ForestPlotPairedTTestParameters
The configuration parameters for the forest plot, including the names and
labels of the paired t-tests to be used.
ttest_results : dict[str, tuple[float, float, float]]
A dictionary mapping t-test names to their results (t-statistic, p-value, and
degrees of freedom).
Returns
-------
dict
A dictionary mapping the labels (as specified in the analysis configuration)
to the corresponding t-test results.
"""
mapping_ttest_names_to_labels: dict = {
name: label
for name, label in zip(
analysis_config.paired_ttest_names, analysis_config.paired_ttest_labels
)
if name in ttest_results.keys()
}
selected_ttests: dict = {
name: ttest_results[name] for name in mapping_ttest_names_to_labels.keys()
}
labeled_ttests: dict = {
mapping_ttest_names_to_labels[name]: ttest
for name, ttest in selected_ttests.items()
}
return labeled_ttests

View File

View File

@ -0,0 +1,10 @@
from attrs import field, define
from attrs.validators import instance_of
from src.data_classes.parameters_general import GeneralParameters
@define
class ComparisonVarianceInAndBetweenGroupParameters(GeneralParameters):
variable: str = field(validator=instance_of(str))
group: str = field(validator=instance_of(str))

View File

@ -0,0 +1,9 @@
from attrs import field, define
from attrs.validators import instance_of
from src.data_classes.parameters_general import GeneralParameters
@define
class GetFunctionInverseBayesTransformedRegressionParameters(GeneralParameters):
model_name: str = field(validator=instance_of(str))

View File

@ -0,0 +1,21 @@
from typing import Iterable, Union
from attrs import field, define
from attrs.validators import instance_of, deep_iterable
from src.data_classes.parameters_general import GeneralParameters
@define
class InfluenceOfVotesParameters(GeneralParameters):
weight_as_distribution_quantile: bool = field(validator=instance_of(bool))
weight_m: Union[int, float] = field(validator=instance_of((int, float)))
model_name: str = field(validator=instance_of(str))
step: list[int] = field(
validator=deep_iterable(
member_validator=instance_of(int), iterable_validator=instance_of(Iterable)
),
)
startpoint: Union[str, list[Union[int, float]]] = field(
validator=instance_of((str, list))
)

View File

@ -0,0 +1,10 @@
from attrs import field, define
from attrs.validators import instance_of
from src.data_classes.parameters_general import GeneralParameters
@define
class PearsonCorrelationParameters(GeneralParameters):
variable_1: str = field(validator=instance_of(str))
variable_2: str = field(validator=instance_of(str))

View File

@ -0,0 +1,61 @@
from typing import Iterable
from pathlib import Path
from attrs import field, define
from attrs.validators import instance_of, deep_iterable, optional
from attr import attrib
from src.data_classes.parameters_general import GeneralParameters
from src.utils.helper_conversion import create_dictionary_of_aggregation_methods
@define
class RegressionParameters(GeneralParameters):
dependent_variable: str = field(validator=instance_of(str))
independent_variables: list[str] = field(
validator=deep_iterable(
member_validator=instance_of(str), iterable_validator=instance_of(Iterable)
),
)
@define
class BayesianRegressionParameters(RegressionParameters):
pass
@define
class LinearRegressionParameters(RegressionParameters):
standardize: bool = field(default=False, validator=instance_of(bool))
report_effect_size: bool = field(
default=False, validator=optional(instance_of(bool))
)
@define
class GroupedLinearRegressionParameters(RegressionParameters):
aggregation_functions: list[str] = field(
default=[],
validator=deep_iterable(
member_validator=instance_of(str), iterable_validator=instance_of(list)
),
)
group_by: str = field(default="sum", validator=instance_of(str))
standardize: bool = field(default=False, validator=instance_of(bool))
report_effect_size: bool = field(
default=False, validator=optional(instance_of(bool))
)
print_detailed_coefficients: bool = field(
default=False, validator=optional(instance_of(bool))
)
dictionary_aggregation_methods = attrib(init=False)
def __attrs_post_init__(self):
self.name_save_file = Path(f"{self.name}")
self.dictionary_aggregation_methods: dict = (
create_dictionary_of_aggregation_methods(
self.independent_variables,
self.dependent_variable,
self.aggregation_functions,
)
)

View File

@ -0,0 +1,14 @@
from attrs import field, define
from attrs.validators import instance_of
from src.data_classes.parameters_general import GeneralParameters
@define
class TTestParameters(GeneralParameters):
variable_1: str = field(validator=instance_of(str))
variable_2: str = field(validator=instance_of(str))
class PairedTTestParameters(TTestParameters):
pass

View File

@ -0,0 +1,15 @@
from attr import attrib
from attrs import field, define
from attrs.validators import instance_of, deep_iterable
from src.data_classes.parameters_general import GeneralParameters
@define
class DescriptiveAggregatedParameters(GeneralParameters):
variables: list[str] = field(
validator=deep_iterable(
member_validator=instance_of(str), iterable_validator=instance_of(list)
)
)
aggregation_function: str = field(validator=instance_of(str))
group_by: str = attrib(validator=instance_of(str))

View File

@ -0,0 +1,26 @@
from pathlib import Path
from typing import Union, Any
from attr import attrib
from attrs import field, define
from attrs.validators import instance_of, optional, deep_iterable
from src.data_classes.parameters_general import GeneralParameters
@define
class Metric:
operation: str = field(validator=instance_of(str))
column: str = field(validator=optional(instance_of(str)))
@define
class DescriptiveOverviewParameters(GeneralParameters):
metrics: list[Union[Any, Metric]] = field(validator=instance_of(list))
group_by: str = attrib(validator=instance_of(str))
def __attrs_post_init__(self):
self.metrics = [
Metric(**metric) if isinstance(metric, dict) else metric
for metric in self.metrics
]
self.name_save_file: Path = Path(f"{self.name}")

View File

@ -0,0 +1,12 @@
from typing import Union
from attrs import field, define
from attrs.validators import instance_of
from src.data_classes.parameters_general import GeneralParameters
@define
class DescriptivePercentageOfDatasetUnderConditionParameters(GeneralParameters):
variable: str = field(validator=instance_of(str))
comparison: str = field(validator=instance_of(str))
condition: Union[int, float] = field(validator=instance_of((int, float)))

View File

@ -0,0 +1,17 @@
import pandas as pd
from attr import attrib
from attrs import field, define
from attrs.validators import instance_of
from pathlib import Path
@define
class GeneralParameters:
name: str = field(validator=instance_of(str))
dataset: str = field(validator=instance_of(str))
data: pd.DataFrame = attrib(init=False)
name_save_file: Path = attrib(init=False)
def __attrs_post_init__(self):
self.name_save_file: Path = Path(f"{self.name}")

View File

@ -0,0 +1,21 @@
from typing import Optional
from attrs import field, define
from attrs.validators import instance_of, optional, deep_iterable
from src.data_classes.parameters_visualization import PlotParameters
@define
class BarChartPlotParameters(PlotParameters):
variable_x_axis: str = field(validator=instance_of(str))
variable_y_axis: Optional[str] = field(validator=optional(instance_of(str)))
chart_orientation: str = field(validator=instance_of(str))
sort_order: str = field(validator=instance_of(str))
custom_order: Optional[list[str]] = field(
default=None,
validator=optional(
deep_iterable(
member_validator=instance_of(str), iterable_validator=instance_of(list)
)
),
)

View File

@ -0,0 +1,9 @@
from attrs import field, define
from attrs.validators import instance_of, deep_iterable
from src.data_classes.parameters_visualization import PlotParameters
@define
class BoxPlotParameters(PlotParameters):
variable_1: str = field(validator=instance_of(str))
variable_2: str = field(validator=instance_of(str))

View File

@ -0,0 +1,13 @@
from typing import Union
from attrs import field, define
from attrs.validators import instance_of
from src.data_classes.parameters_visualization import PlotParameters
@define
class ContourPlotParameters(PlotParameters):
function_name: str = field(validator=instance_of(str))
x_axis_maximum: Union[int, float] = field(validator=instance_of((int, float)))
y_axis_maximum: Union[int, float] = field(validator=instance_of((int, float)))
dataset: str = "data"

View File

@ -0,0 +1,22 @@
from typing import Union, Optional
from attrs import field, define
from attrs.validators import instance_of, deep_iterable, optional
from src.data_classes.parameters_visualization import PlotParameters
@define
class CountDistributionPlotParameters(PlotParameters):
variable: str = field(validator=instance_of(str))
x_axis_limits: Optional[list[Union[int, float]]] = field(
default=None,
validator=optional(
deep_iterable(
member_validator=instance_of((int, float)),
iterable_validator=instance_of(list),
)
),
kw_only=True,
)
x_axis_logarithmic_scaling: bool = field(validator=instance_of(bool))
y_axis_logarithmic_scaling: bool = field(validator=instance_of(bool))

View File

@ -0,0 +1,17 @@
from typing import Union
from attrs import field, define
from attrs.validators import instance_of, deep_iterable
from src.data_classes.parameters_visualization import PlotParameters
@define
class DensityPlotParameters(PlotParameters):
variable_x_axis: str = field(validator=instance_of(str))
variable_y_axis: str = field(validator=instance_of(str))
data_breakpoints: list[Union[int, float]] = field(
validator=deep_iterable(
member_validator=instance_of((int, float)),
iterable_validator=instance_of(list),
)
)

View File

@ -0,0 +1,41 @@
from typing import Union, Optional
from attrs import field, define
from attrs.validators import instance_of, deep_iterable, optional
from src.data_classes.parameters_visualization import PlotParameters
@define
class ForestPlotParameters(PlotParameters):
regression_model_names: list[str] = field(
validator=deep_iterable(
member_validator=instance_of(str), iterable_validator=instance_of(list)
)
)
regression_model_labels: list[str] = field(
validator=[
deep_iterable(
member_validator=instance_of(str),
iterable_validator=instance_of(list),
),
],
)
coefficient_names: list[str] = field(
validator=deep_iterable(
member_validator=instance_of(str), iterable_validator=instance_of(list)
)
)
sort_by_size: Optional[bool] = field(
default=False, validator=optional(instance_of(bool))
)
x_axis_minimum: Optional[Union[int, float]] = field(
default=None, validator=optional(instance_of((int, float)))
)
x_axis_maximum: Optional[Union[int, float]] = field(
default=None, validator=optional(instance_of((int, float)))
)
dotsize: Optional[int] = field(default=5, validator=optional(instance_of(int)))
colors: Optional[list[str]] = field(
default=["orange", "royalblue", "forestgreen", "firebrick"], validator=optional(instance_of(list))
)
dataset: str = "data"

View File

@ -0,0 +1,30 @@
from typing import Union, Optional
from attrs import field, define
from attrs.validators import instance_of, deep_iterable, optional
from src.data_classes.parameters_visualization import PlotParameters
@define
class ForestPlotPairedTTestParameters(PlotParameters):
paired_ttest_names: list[str] = field(
validator=deep_iterable(
member_validator=instance_of(str), iterable_validator=instance_of(list)
)
)
paired_ttest_labels: list[str] = field(
validator=[
deep_iterable(
member_validator=instance_of(str),
iterable_validator=instance_of(list),
),
],
)
x_axis_minimum: Optional[Union[int, float]] = field(
default=None, validator=optional(instance_of((int, float)))
)
x_axis_maximum: Optional[Union[int, float]] = field(
default=None, validator=optional(instance_of((int, float)))
)
dotsize: Optional[int] = field(default=5, validator=optional(instance_of(int)))
dataset: str = "data"

View File

@ -0,0 +1,10 @@
from attrs import field, define
from attrs.validators import instance_of
from src.data_classes.parameters_visualization import PlotParameters
@define
class GroupedHistogramParameters(PlotParameters):
group_by: str = field(validator=instance_of(str))
aggregation_variable: str = field(validator=instance_of(str))
aggregation_function: str = field(validator=instance_of(str))

View File

@ -0,0 +1,28 @@
from typing import Iterable, Union
from attrs import field, define
from attrs.validators import instance_of, deep_iterable
from src.data_classes.parameters_visualization import PlotParameters
@define
class HeatmapParameters(PlotParameters):
axis_variables: list[str] = field(
validator=deep_iterable(
member_validator=instance_of(str), iterable_validator=instance_of(Iterable)
),
)
heat_variable: str = field(validator=instance_of(str))
axis_maxima: list[Union[int, float]] = field(
validator=deep_iterable(
member_validator=instance_of((int, float)),
iterable_validator=instance_of(Iterable),
),
)
axis_minima: list[Union[int, float]] = field(
validator=deep_iterable(
member_validator=instance_of((int, float)),
iterable_validator=instance_of(Iterable),
),
)
logarithmic_heat_scaling: str = field(validator=instance_of(str))

View File

@ -0,0 +1,19 @@
from typing import Union, Optional
from attrs import field, define
from attrs.validators import instance_of, optional
from src.data_classes.parameters_visualization import PlotParameters
@define
class HexbinPlotParameters(PlotParameters):
variable_x_axis: str = field(validator=instance_of(str))
variable_y_axis: str = field(validator=instance_of(str))
x_axis_maximum: Optional[Union[int, float]] = field(
default=None, validator=optional(instance_of((int, float))), kw_only=True
)
y_axis_maximum: Optional[Union[int, float]] = field(
default=None, validator=optional(instance_of((int, float))), kw_only=True
)
trendline: bool = field(validator=instance_of(bool))
logarithmic_hex_scaling: bool = field(validator=instance_of(bool))

View File

@ -0,0 +1,22 @@
from typing import Union, Optional
from attrs import field, define
from attrs.validators import instance_of, deep_iterable, optional
from src.data_classes.parameters_visualization import PlotParameters
@define
class HistogramPlotParameters(PlotParameters):
variable: str = field(validator=instance_of(str))
x_axis_limits: Optional[list[Union[int, float]]] = field(
default=None,
validator=optional(
deep_iterable(
member_validator=instance_of((int, float)),
iterable_validator=instance_of(list),
)
),
kw_only=True,
)
x_axis_logarithmic_scaling: bool = field(validator=instance_of(bool))
y_axis_logarithmic_scaling: bool = field(validator=instance_of(bool))

View File

@ -0,0 +1,17 @@
from typing import Optional
from attrs import field, define
from attrs.validators import instance_of, optional, deep_iterable
from src.data_classes.parameters_visualization import PlotParameters
@define
class PercentageStackedBarChartPlotParameters(PlotParameters):
variable_x_axis: str = field(validator=instance_of(str))
variables_to_compare: list[str] = field(
validator=deep_iterable(
member_validator=instance_of(str), iterable_validator=instance_of(list)
)
)
chart_orientation: str = field(validator=instance_of(str))
sort_order: str = field(validator=instance_of(str))

View File

@ -0,0 +1,17 @@
from typing import Iterable, Union
from attrs import field, define
from attrs.validators import instance_of, deep_iterable
from src.data_classes.parameters_visualization import PlotParameters
@define
class RidgelineParameters(PlotParameters):
variable_x_axis: str = field(validator=instance_of(str))
variable_y_axis: str = field(validator=instance_of(str))
data_breakpoints: list[Union[int, float]] = field(
validator=deep_iterable(
member_validator=instance_of((int, float)),
iterable_validator=instance_of(list),
)
)

View File

@ -0,0 +1,9 @@
from attrs import field, define
from attrs.validators import instance_of, deep_iterable
from src.data_classes.parameters_visualization import PlotParameters
@define
class SimpleScatterPlotParameters(PlotParameters):
variable_x_axis: str = field(validator=instance_of(str))
variable_y_axis: str = field(validator=instance_of(str))

View File

@ -0,0 +1,22 @@
from typing import Optional
from attrs import field, define
from attrs.validators import instance_of, optional, deep_iterable
from src.data_classes.parameters_visualization import PlotParameters
@define
class StackedBarChartPlotParameters(PlotParameters):
variable_x_axis: str = field(validator=instance_of(str))
variable_y_axis: Optional[str] = field(validator=optional(instance_of(str)))
hue: str = field(validator=instance_of(str))
chart_orientation: str = field(validator=instance_of(str))
sort_order: str = field(validator=instance_of(str))
custom_order: Optional[list[str]] = field(
default=None,
validator=optional(
deep_iterable(
member_validator=instance_of(str), iterable_validator=instance_of(list)
)
),
)

View File

@ -0,0 +1,16 @@
from typing import Union
from attrs import field, define
from attrs.validators import instance_of
from src.data_classes.parameters_visualization import PlotParameters
@define
class SurfacePlotParameters(PlotParameters):
function_name: str = field(validator=instance_of(str))
x_axis_maximum: Union[int, float] = field(validator=instance_of((int, float)))
y_axis_maximum: Union[int, float] = field(validator=instance_of((int, float)))
z_axis_label: str = field(validator=instance_of(str))
elevation_angle: Union[int, float] = field(validator=instance_of((int, float)))
azimuth_angle: Union[int, float] = field(validator=instance_of((int, float)))
dataset: str = "data"

View File

@ -0,0 +1,9 @@
from attrs import field, define
from attrs.validators import instance_of, deep_iterable
from src.data_classes.parameters_visualization import PlotParameters
@define
class ViolinPlotParameters(PlotParameters):
variable_x_axis: str = field(validator=instance_of(str))
variable_y_axis: str = field(validator=instance_of(str))

View File

@ -0,0 +1,19 @@
from typing import Optional
from attr import define, field
from attr.validators import instance_of, optional
from src.data_classes.parameters_general import GeneralParameters
@define
class PlotParameters(GeneralParameters):
x_axis_label: Optional[str] = field(
default=None, validator=optional(instance_of(str)), kw_only=True
)
y_axis_label: Optional[str] = field(
default=None, validator=optional(instance_of(str)), kw_only=True
)
title: Optional[str] = field(
default=None, validator=optional(instance_of(str)), kw_only=True
)

View File

View File

@ -0,0 +1,143 @@
import yaml
from src.data_classes.parameters_analysis_comparison_variance_in_and_between_group import (
ComparisonVarianceInAndBetweenGroupParameters,
)
from src.data_classes.parameters_analysis_get_function_inverse_bayes_transformed_regression import (
GetFunctionInverseBayesTransformedRegressionParameters,
)
from src.data_classes.parameters_analysis_influence_of_up_and_downvotes import (
InfluenceOfVotesParameters,
)
from src.data_classes.parameters_analysis_regression import (
BayesianRegressionParameters,
LinearRegressionParameters,
GroupedLinearRegressionParameters,
)
from src.data_classes.parameters_analysis_ttest import (
TTestParameters,
PairedTTestParameters,
)
from src.data_classes.parameters_analysis_pearson_correlation import (
PearsonCorrelationParameters,
)
from src.data_classes.parameters_descriptive_aggregated import (
DescriptiveAggregatedParameters,
)
from src.data_classes.parameters_descriptive_overview import (
DescriptiveOverviewParameters,
)
from src.data_classes.parameters_descriptive_percentage_of_dataset_under_condition import (
DescriptivePercentageOfDatasetUnderConditionParameters,
)
from src.data_classes.parameters_plot_barchart import BarChartPlotParameters
from src.data_classes.parameters_plot_boxplot import BoxPlotParameters
from src.data_classes.parameters_plot_contourplot import ContourPlotParameters
from src.data_classes.parameters_plot_count_distribution import (
CountDistributionPlotParameters,
)
from src.data_classes.parameters_plot_densityplot import DensityPlotParameters
from src.data_classes.parameters_plot_forestplot import ForestPlotParameters
from src.data_classes.parameters_plot_forestplot_paired_ttest import ForestPlotPairedTTestParameters
from src.data_classes.parameters_plot_grouped_histogram import (
GroupedHistogramParameters,
)
from src.data_classes.parameters_plot_heatmap import HeatmapParameters
from src.data_classes.parameters_plot_hexbinplot import HexbinPlotParameters
from src.data_classes.parameters_plot_histogram import HistogramPlotParameters
from src.data_classes.parameters_plot_percentage_stacked_barchart import (
PercentageStackedBarChartPlotParameters,
)
from src.data_classes.parameters_plot_ridgelineplot import RidgelineParameters
from src.data_classes.parameters_plot_simple_scatterplot import (
SimpleScatterPlotParameters,
)
from src.data_classes.parameters_plot_stacked_barchart import (
StackedBarChartPlotParameters,
)
from src.data_classes.parameters_plot_surfaceplot import SurfacePlotParameters
from src.data_classes.parameters_plot_violinplot import ViolinPlotParameters
def custom_constructor(loader: yaml.Loader, tag_suffix: str, node: yaml.Node):
"""
This function handles custom YAML tags and creates an instance of the appropriate class based on the tag suffix.
Parameters:
loader (yaml.Loader): The YAML loader instance.
tag_suffix (str): The suffix of the YAML tag. This determines the class to be instantiated.
node (yaml.Node): The YAML node to be transformed into a Python dictionary.
Returns:
_class: An instance of either LinearRegressionParameters or BayesianRegressionParameters class,
depending on the tag suffix.
Raises:
ValueError: If the tag suffix is not a supported type of analysis or visualization.
"""
if tag_suffix == "descriptive_aggregated":
_class = DescriptiveAggregatedParameters
elif tag_suffix == "descriptive_overview":
_class = DescriptiveOverviewParameters
elif tag_suffix == "percentage_of_dataset_under_condition":
_class = DescriptivePercentageOfDatasetUnderConditionParameters
elif tag_suffix == "comparison_variance_in_and_between_group":
_class = ComparisonVarianceInAndBetweenGroupParameters
elif tag_suffix == "linear_regression":
_class = LinearRegressionParameters
elif tag_suffix == "bayesian_regression":
_class = BayesianRegressionParameters
elif tag_suffix == "linear_regression_grouped":
_class = GroupedLinearRegressionParameters
elif tag_suffix == "increase_per_up_and_downvote_from_totalvotes_and_valence":
_class = InfluenceOfVotesParameters
elif tag_suffix == "function_inverse_bayes_transformed_regression":
_class = GetFunctionInverseBayesTransformedRegressionParameters
elif tag_suffix == "ttest":
_class = TTestParameters
elif tag_suffix == "paired_ttest":
_class = PairedTTestParameters
elif tag_suffix == "pearson_correlation":
_class = PearsonCorrelationParameters
elif tag_suffix == "barchart":
_class = BarChartPlotParameters
elif tag_suffix == "boxplot":
_class = BoxPlotParameters
elif tag_suffix == "contourplot":
_class = ContourPlotParameters
elif tag_suffix == "histogram":
_class = HistogramPlotParameters
elif tag_suffix == "count_distribution":
_class = CountDistributionPlotParameters
elif tag_suffix == "densityplot":
_class = DensityPlotParameters
elif tag_suffix == "forestplot":
_class = ForestPlotParameters
elif tag_suffix == "forestplot_paired_ttest":
_class = ForestPlotPairedTTestParameters
elif tag_suffix == "grouped_histogram":
_class = GroupedHistogramParameters
elif tag_suffix == "heatmap":
_class = HeatmapParameters
elif tag_suffix == "hexbinplot":
_class = HexbinPlotParameters
elif tag_suffix == "percentage_stacked_barchart":
_class = PercentageStackedBarChartPlotParameters
elif tag_suffix == "ridgelineplot":
_class = RidgelineParameters
elif tag_suffix == "simple_scatterplot":
_class = SimpleScatterPlotParameters
elif tag_suffix == "stacked_barchart":
_class = StackedBarChartPlotParameters
elif tag_suffix == "surfaceplot":
_class = SurfacePlotParameters
elif tag_suffix == "violinplot":
_class = ViolinPlotParameters
else:
raise ValueError(
f"Unexpected tag suffix: {tag_suffix}. Please check for typos or if the analysis is not supported"
)
instance_data = loader.construct_mapping(node, deep=True)
return _class(**instance_data)

View File

@ -0,0 +1,202 @@
import datetime
import os
import re
from pathlib import Path
import pypandoc
def create_markdown_report(log_filename: Path, output_name: Path, output_dir: Path):
"""
Generates a markdown report from a specified log file.
This function reads a log file, processes the content by adding markdown image syntax for any detected plot paths,
and then writes the processed content into a markdown file named after the `output_name` parameter in the specified
`output_dir`. The report includes a header with the current date and the processed log content.
Parameters
----------
log_filename : Path
The path to the log file to be processed.
output_name : Path
The base name for the output markdown file (without extension).
output_dir : Path
The directory where the markdown file will be saved.
"""
with open(log_filename, "r") as log_file:
log_content: str = log_file.read()
log_lines: list[str] = log_content.split("\n")
processed_log_content: str = ""
for line in log_lines:
if "Plot saved at" in line:
image_path: str = re.search("Plot saved at (.*)", line).group(1)
line += f"\n\n![](../{image_path})\n"
processed_log_content += line + "\n"
todays_date: str = datetime.date.today().strftime("%B %d, %Y")
markdown_content: str = f"""# Analysis Results for {todays_date}
{processed_log_content}
"""
with open(f"{output_dir}/{output_name}.md", "w") as md_file:
md_file.write(markdown_content)
def create_pdf_report(markdown_filename: Path, output_dir: Path, font_size: str = "8pt"):
"""
Generates a PDF report from a markdown file.
This function converts a markdown file into a PDF file directly using pypandoc,
preserving all formatting including code blocks and embedded images.
The PDF file is saved in the specified `output_dir` with the same base name as the `markdown_filename`.
Parameters
----------
markdown_filename : Path
The path to the markdown file to be converted into PDF.
output_dir : Path
The directory where the PDF file will be saved.
font_size : str, optional
The font size for the PDF (default is '8pt').
"""
os.chdir(output_dir)
markdown_path: Path = Path(f"{markdown_filename}.md")
new_md_file = split_tables_in_markdown(markdown_path)
new_md_file = split_regression_long_vars(new_md_file)
output_pdf_path: Path = Path(f"{markdown_filename}.pdf")
fontsize_number = font_size[:-2]
header_includes = f"""
\\usepackage[utf8]{{inputenc}}
\\usepackage{{lmodern}}
\\usepackage{{adjustbox}}
\\usepackage{{anyfontsize}}
\\usepackage{{geometry}}
\\usepackage{{listings}}
\\lstset{{basicstyle=\\fontsize{{{fontsize_number}}}{{{int(fontsize_number) * 0.9}}}\selectfont}}
\\fontsize{{{fontsize_number}}}{{{int(fontsize_number) * 1.2}}}\\selectfont
"""
table_settings = f"""
\\usepackage{{etoolbox}}
\\BeforeBeginEnvironment{{tabular}}{{\\begin{{adjustbox}}{{max width=\\textwidth}}}}
\\AfterEndEnvironment{{tabular}}{{\\end{{adjustbox}}}}
"""
extra_args = [
'--pdf-engine=xelatex',
'--variable', f'geometry:top=1in, bottom=1in, left=1in, right=1in',
'--variable', f'header-includes:{header_includes}',
'--variable', f'header-includes:{table_settings}',
'-s'
]
pypandoc.convert_file(new_md_file, 'pdf', outputfile=output_pdf_path, extra_args=extra_args)
os.remove(Path(f"{markdown_filename}_split_tables.md"))
os.remove(Path(f"{markdown_filename}_split_tables_split_regression.md"))
def split_tables_in_markdown(file_path: str, max_width=100) -> Path:
"""
Process a markdown file and split tables that are wider than `max_width` into smaller tables.
"""
with open(file_path, 'r') as f:
lines = f.readlines()
new_lines: list = []
table_buffer: list = []
for line in lines:
if line.startswith('|'):
table_buffer.append(line.rstrip('\n'))
else:
if table_buffer:
new_lines.extend(split_table_into_smaller_ones(table_buffer, max_width))
table_buffer: list = []
new_lines.append(line.rstrip('\n'))
if table_buffer:
new_lines.extend(split_table_into_smaller_ones(table_buffer, max_width))
new_file_path = str(file_path).replace('.md', '_split_tables.md')
with open(new_file_path, 'w') as f:
f.write('\n'.join(new_lines))
return Path(new_file_path)
def split_table_into_smaller_ones(table_lines, max_width: int) -> list[str]:
"""
Given the lines of a table and a maximum width, split the table into multiple smaller tables
"""
new_lines: list = []
headers: str = table_lines[0].split('|')[1:-1]
rows: list = [row.split('|')[1:-1] for row in table_lines[1:]]
current_width: int = 0
start_col: int = 0
for end_col, header in enumerate(headers, start=1):
current_width += len(header) + 3
if current_width > max_width or end_col == len(headers):
new_headers: str = headers[start_col:end_col]
new_lines.append('|' + '|'.join(new_headers) + '|')
for row in rows:
new_cells: str = row[start_col:end_col]
new_lines.append('|' + '|'.join(new_cells) + '|')
new_lines.append('\n')
current_width: int = 0
start_col: str = end_col
return new_lines
def split_regression_long_vars(file_path: Path, max_width: int=105) -> Path:
""" Process a regression result file and split variables that have too long lines
(length > `max_width`) into smaller strings. """
with open(file_path, 'r') as f:
lines = f.readlines()
new_lines: list = []
is_ols_block, is_const_met = False, False
for line in lines:
if 'OLS Regression Results' in line:
is_ols_block = True
if line.strip() == '```':
is_ols_block = False
if is_ols_block:
if 'const' in line:
is_const_met = True
if line.strip().startswith('==='):
is_const_met = False
if is_const_met:
if set(line.strip()) not in [{'-', '+', '='}, {' '}, {''}]:
split_line = line.split(' ')
temp_line = ''
new_line = []
for word in split_line:
if (len(temp_line + word) <= max_width or '[' in word or ']' in word) and not word.startswith('----'):
temp_line += ' ' + word
else:
new_line.append(temp_line.strip())
temp_line = word
if temp_line:
new_line.append(temp_line.strip())
new_lines.extend(new_line)
else:
new_lines.append(line.strip()[:max_width])
else:
new_lines.append(line.rstrip('\n'))
else:
new_lines.append(line.rstrip('\n'))
new_file_path = Path(str(file_path).replace('.md', '_split_regression.md'))
with open(new_file_path, 'w') as f:
f.write('\n'.join(new_lines))
return new_file_path

View File

@ -0,0 +1,63 @@
from typing import Union
from pathlib import Path
import logging
import pandas as pd
from statsmodels.iolib.summary import Summary
from statsmodels.regression.linear_model import RegressionResults
def print_and_save_result(
print_result: bool,
save_result: bool,
filepath: str,
result: Union[str, Summary, RegressionResults, pd.DataFrame],
name_save_file: Path,
) -> None:
"""
Prints and/or saves the analysis result based on the specified conditions.
This function is designed to handle the output of statistical analysis results, allowing for both printing to the
console and saving to a file. The type of the result (e.g., string, DataFrame) determines the format of the saved file.
Logging is used to record the result in a consistent format, facilitating debugging and record-keeping.
Parameters
----------
print_result : bool
A flag indicating whether to print the result to the console.
save_result : bool
A flag indicating whether to save the result to a file.
filepath : str
The base path where the result file will be saved. It is used in conjunction with `name_save_file`
to construct the full file path.
result : Union[str, Summary, RegressionResults, pd.DataFrame]
The result of the analysis. Can be a string, a Summary object, a RegressionResults object, or a pandas DataFrame
name_save_file : Path
The name of the file (without extension) to which the result will be saved.
The extension is determined by the type of `result`.
Returns
-------
None
"""
pd.set_option('display.max_columns', None)
pd.set_option('display.width', 1000)
if isinstance(result, pd.DataFrame):
result_str = result.to_markdown()
logging.info(result_str)
else:
result_str = str(result)
logging.info("```")
logging.info(result_str)
logging.info("```")
if print_result:
print(result_str)
if save_result:
if type(result) == pd.DataFrame:
result.to_csv(f"{filepath}{name_save_file}.csv", index=True)
else:
with open(f"{filepath}{name_save_file}.txt", "w") as f:
f.write(result_str)

View File

@ -0,0 +1,36 @@
import logging
from typing import Optional
from matplotlib import pyplot as plt
def save_plot(save_plots: bool, filepath: str, plot: plt, name: Optional[str], file_format: str = "png"):
"""
This method saves the generated plot to a file.
Parameters
----------
save_plots: bool
A boolean flag to determine whether to save the plot or not.
filepath: str
The path to the directory where the plot will be saved.
plot: plt
The matplotlib.pyplot instance.
name: str
The name of the file to which the plot will be saved (if self.save_plots is True).
file_format: str
The file format in which plot will be saved. By default, it is 'png'.
Returns
-------
None
"""
if save_plots:
output_path = f"{filepath}{name}.{file_format}"
plot.savefig(output_path, bbox_inches="tight", dpi=300)
plot.show()
plot.close()
logging.info(f"Plot saved at {output_path}")
else:
plot.show()

121
src/preprocessor.py Normal file
View File

@ -0,0 +1,121 @@
from typing import Any
import pandas as pd
class Preprocessing:
"""
A class for preprocessing datasets loaded from a parquet file.
This class provides methods to preprocess datasets according to a given configuration. It supports operations such as
filtering data by order, section, popular sections, users with more comments, and excluding data based on specific values.
Attributes
----------
data : pd.DataFrame
The dataset loaded from the specified parquet file.
Methods
-------
preprocess_datasets(preprocessing_config):
Applies a series of preprocessing steps to the dataset based on the provided configuration and returns the modified datasets.
_apply_chain(data, chain):
Applies a chain of preprocessing steps to the given data.
full_data():
Returns the full dataset without any preprocessing.
data_order(data, order):
Filters the dataset to include only the data with the specified order.
data_section(data, section):
Filters the dataset to include only the data from the specified section.
popular_sections(data, threshold):
Filters the dataset to include only the data from sections with more than a specified number of entries.
users_with_more_comments(data, num_comments):
Filters the dataset to include only the data from users with more than a specified number of comments.
exclude_data_with_value(data, param):
Excludes data from the dataset based on a specified column value.
"""
def __init__(self, path_to_file: str, name_data: str):
"""
Initializes the Preprocessing class with data loaded from a specified parquet file.
Parameters
----------
path_to_file : str
The path to the directory containing the parquet file.
name_data : str
The name of the parquet file from which to load the data.
"""
self.data = pd.read_parquet(path_to_file + name_data)
def preprocess_datasets(self, preprocessing_config) -> dict[str, pd.DataFrame]:
"""
Applies a series of preprocessing steps to the dataset based on the provided configuration.
Parameters
----------
preprocessing_config : dict
A dictionary where keys are dataset names and values are lists of preprocessing steps (as dictionaries) to be applied.
Returns
-------
dict[str, pd.DataFrame]
A dictionary of preprocessed datasets.
"""
datasets = {}
for dataset_name, config in preprocessing_config.items():
datasets[dataset_name]: pd.DataFrame = self._apply_chain(self.data.copy(), config)
datasets["data"] = self.full_data()
return datasets
def _apply_chain(self, data: pd.DataFrame, chain: list) -> pd.DataFrame:
"""
Applies a chain of preprocessing steps to the given data.
Parameters
----------
data : pd.DataFrame
The dataset to preprocess.
chain : list
A list of dictionaries, each representing a preprocessing step with a method name and optional parameters.
Returns
-------
pd.DataFrame
The preprocessed dataset.
"""
for step in chain:
method_name = step["method"]
param = step.get("param")
method = getattr(self, method_name)
data = method(data, param)
return data
def full_data(self):
return self.data
@staticmethod
def data_order(data: pd.DataFrame, order: int) -> pd.DataFrame:
return data.loc[data["order"] == order]
@staticmethod
def data_section(data: pd.DataFrame, section: str) -> pd.DataFrame:
return data.loc[data["section"] == section]
@staticmethod
def popular_sections(data: pd.DataFrame, threshold: int = 1000) -> pd.DataFrame:
counts = data["section"].value_counts()
popular_sections = counts[counts > threshold].index.tolist()
return data[data["section"].isin(popular_sections)]
@staticmethod
def users_with_more_comments(data: pd.DataFrame, num_comments: int = 10) -> pd.DataFrame:
counts_user = data["user_id"].value_counts()
users_with_10_comments = counts_user[counts_user > num_comments].index.tolist()
return data[data["user_id"].isin(users_with_10_comments)]
@staticmethod
def exclude_data_with_value(data: pd.DataFrame, param: dict) -> pd.DataFrame:
column: str = param['column']
value: Any = param['value']
return data[data[column] != value]

0
src/utils/__init__.py Normal file
View File

View File

@ -0,0 +1,40 @@
from rpy2.robjects import packages as rpackages
def is_r_package_installed(package_name: str) -> bool:
"""
Checks if a given R package is installed.
Parameters
----------
package_name : str
The name of the R package to check.
Returns
-------
bool
True if the package is installed, False otherwise.
"""
return rpackages.isinstalled(package_name)
def install_r_package(package_name: str):
"""
Installs a given R package using CRAN mirror.
This function selects the first CRAN mirror and installs the specified R package.
Parameters
----------
package_name : str
The name of the R package to install.
"""
utils = rpackages.importr("utils")
utils.chooseCRANmirror(ind=1)
utils.install_packages(package_name)
if not is_r_package_installed("BAS"):
install_r_package("BAS")
BAS = rpackages.importr("BAS")

View File

@ -0,0 +1,87 @@
import inspect
from typing import Any
def create_dictionary_of_aggregation_methods(
dependent_variables: list[str],
independent_variable: str,
aggregation_functions: list[str],
) -> dict[str, str]:
"""
Creates a dictionary mapping each variable (dependent and independent) to its specified aggregation function.
This function is designed to facilitate the aggregation of data by dynamically creating a mapping of variables
to their corresponding aggregation functions. This is particularly useful in data analysis and preprocessing
where different variables may require different methods of aggregation.
Parameters
----------
dependent_variables : list[str]
A list of strings representing the names of the dependent variables.
independent_variable : str
A string representing the name of the independent variable.
aggregation_functions : list[str]
A list of strings representing the aggregation functions to be applied to each variable. The order of functions
in this list should correspond to the order of variables in `dependent_variables`
followed by the `independent_variable`.
Returns
-------
dict[str, str]
A dictionary where keys are variable names (both dependent and independent) and values are the corresponding
aggregation functions as strings.
Raises
------
ValueError
If the total number of variables (dependent + independent)
does not match the number of provided aggregation functions.
Example
-------
>>> create_dictionary_of_aggregation_methods(['var1', 'var2'], 'var3', ['sum', 'mean', 'count'])
{'var1': 'sum', 'var2': 'mean', 'var3': 'count'}
"""
variables: list[str] = dependent_variables + [independent_variable]
if len(variables) != len(aggregation_functions):
raise ValueError(
"The number of variables must match the number of aggregation functions."
)
return {
variable: aggregation_function
for variable, aggregation_function in zip(variables, aggregation_functions)
}
def get_data_name(data: Any) -> str or None:
"""
Retrieves the variable name of the input data as it appears in the caller's scope.
This function uses introspection to look back into the caller's local variables and find the name of the variable
that references the data passed to this function. This can be useful for debugging or when dynamically generating
output based on variable names.
Parameters
----------
data : any
The data object whose variable name is to be found.
Returns
-------
str or None
The name of the variable as a string if found; otherwise, None.
Example
-------
>>> my_data = [1, 2, 3]
>>> get_data_name(my_data)
'my_data'
"""
callers_local_vars = inspect.currentframe().f_back.f_locals.items()
data_name = [
variable_name for variable_name, variable_value in callers_local_vars if variable_value is data
]
if data_name:
return data_name[0]

View File

@ -0,0 +1,102 @@
"""Minor helper functions"""
class FunctionData:
def __init__(self, func, params):
self.func = func
self.params = params
def __call__(self, x, y):
return self.func(x, y, self.params)
def transform_to_bayes_corrected_valence(
upvotes: int, downvotes: int, average_valence: float, weight_factor_m: float
) -> float:
"""
Transforms the upvotes and downvotes to its bayesian corrected value.
Parameters
----------
upvotes: int
The number of upvotes.
downvotes: int
The number of downvotes.
weight_factor_m: float
The weight factor m.
average_valence: float
The average valence.
Returns
-------
bayes_corrected_value: float
The bayes_corrected_value between 0 and 1.
"""
valence = -(downvotes / (downvotes + upvotes)) + 0.5
totalvotes = upvotes + downvotes
bayes_corrected_value = caluculate_bayes_correction(
valence, totalvotes, weight_factor_m, average_valence
)
return bayes_corrected_value
def caluculate_bayes_correction(
measure: float, volume: float, weight: float, average_measure: float
) -> float:
"""
Calculates the bayes_corrected_value between 0 and 1 weighing in the volume.
Parameters
----------
measure: float
The measure.
volume: float
The volume.
weight: float
The weight factor m. Weighting how strongly the volume is considered
average_measure: float
The average_measure.
Returns
-------
bayes_corrected_measure: float
The bayes_corrected_value between 0 and 1
"""
bayes_corrected_measure = (
volume / (volume + weight) * measure
+ weight / (volume + weight) * average_measure
)
return bayes_corrected_measure
def calculate_inverse_bayes_correction(
bayes_corrected_value: float,
volume: float,
weight_factor_m: float,
average_measure: float,
) -> float:
"""
Calculates the inverse bayes_corrected_value between 0 and 1.
Parameters
----------
bayes_corrected_value: float
The bayes_corrected_value between 0 and 1.
volume: float
The average_totalvotes.
weight_factor_m: float
The weight_factor.
average_measure: float
The average_measure.
Returns
-------
downvotes: float
The downvotes corresponding to the bayes_corrected_value for a given number of total votes.
"""
inverse_bayes_corrected_value = (
((volume + weight_factor_m)/volume) * (bayes_corrected_value - weight_factor_m/(volume + weight_factor_m) * average_measure)
)
return inverse_bayes_corrected_value

260
src/utils/helper_logging.py Normal file
View File

@ -0,0 +1,260 @@
import logging
from src.data_classes.parameters_analysis_regression import (
LinearRegressionParameters,
BayesianRegressionParameters,
GroupedLinearRegressionParameters,
)
from src.data_classes.parameters_descriptive_aggregated import (
DescriptiveAggregatedParameters,
)
from src.data_classes.parameters_descriptive_overview import (
DescriptiveOverviewParameters,
)
from src.data_classes.parameters_descriptive_percentage_of_dataset_under_condition import (
DescriptivePercentageOfDatasetUnderConditionParameters,
)
from src.data_classes.parameters_plot_barchart import BarChartPlotParameters
from src.data_classes.parameters_plot_boxplot import BoxPlotParameters
from src.data_classes.parameters_plot_contourplot import ContourPlotParameters
from src.data_classes.parameters_plot_count_distribution import (
CountDistributionPlotParameters,
)
from src.data_classes.parameters_plot_densityplot import DensityPlotParameters
from src.data_classes.parameters_plot_forestplot import ForestPlotParameters
from src.data_classes.parameters_plot_forestplot_paired_ttest import (
ForestPlotPairedTTestParameters,
)
from src.data_classes.parameters_plot_grouped_histogram import (
GroupedHistogramParameters,
)
from src.data_classes.parameters_plot_heatmap import HeatmapParameters
from src.data_classes.parameters_plot_hexbinplot import HexbinPlotParameters
from src.data_classes.parameters_plot_histogram import HistogramPlotParameters
from src.data_classes.parameters_plot_percentage_stacked_barchart import (
PercentageStackedBarChartPlotParameters,
)
from src.data_classes.parameters_plot_ridgelineplot import RidgelineParameters
from src.data_classes.parameters_plot_simple_scatterplot import (
SimpleScatterPlotParameters,
)
from src.data_classes.parameters_plot_stacked_barchart import (
StackedBarChartPlotParameters,
)
from src.data_classes.parameters_plot_surfaceplot import SurfacePlotParameters
from src.data_classes.parameters_plot_violinplot import ViolinPlotParameters
def log_descriptive_analysis_details(config):
logging.info(f"Descriptive Analysis: {config.name_save_file}")
logging.info("```")
logging.info(f"Data: {config.dataset}")
if isinstance(config, DescriptiveAggregatedParameters):
logging.info(f"Variables: {config.variables}")
logging.info(f"Aggregation Function: {config.aggregation_function}")
logging.info(f"Group By: {config.group_by}")
elif isinstance(config, DescriptiveOverviewParameters):
logging.info(f"Metrics: {config.metrics}")
logging.info(f"Group By: {config.group_by}")
elif isinstance(config, DescriptivePercentageOfDatasetUnderConditionParameters):
logging.info(f"Variable: {config.variable}")
logging.info(f"Comparison: {config.comparison}")
logging.info(f"Condition: {config.condition}")
else:
raise ValueError(
f"Invalid type of descriptive analysis requested {type(config)}"
)
logging.info("```")
def log_regression_details(config, regression_type: str):
logging.info(f"{regression_type} Regression Analysis: {config.name_save_file}")
logging.info("```")
logging.info(f"Independent Variables: {config.independent_variables}")
logging.info(f"Dependent Variable: {config.dependent_variable}")
logging.info(f"Data: {config.dataset}")
if isinstance(config, LinearRegressionParameters):
logging.info(f"Standardize: {config.standardize}")
logging.info(f"Report effect size: {config.report_effect_size}")
elif isinstance(config, BayesianRegressionParameters):
pass
elif isinstance(config, GroupedLinearRegressionParameters):
logging.info(f"Independent Variables: {config.independent_variables}")
logging.info(f"Grouped by: {config.group_by}")
logging.info(f"Aggregation methods: {config.dictionary_aggregation_methods}")
logging.info(f"Standardize: {config.standardize}")
logging.info(f"Report effect size: {config.report_effect_size}")
logging.info(
f"Print detailed coefficients: {config.print_detailed_coefficients}"
)
else:
raise ValueError(f"Unknown parameter type: {type(config)}")
logging.info("```")
def log_get_function_inverse_bayes_transformed_regression(config):
logging.info(
f"Get Function Inverse Bayes Transformed Regression: {config.name_save_file}"
)
logging.info("```")
logging.info(f"Data: {config.data}")
logging.info(f"Model Name: {config.model_name}")
logging.info("```")
def log_influence_of_up_and_downvotes_on_replies(config):
logging.info(f"Influence of Up and Downvotes on Replies: {config.name_save_file}")
logging.info("```")
logging.info(
f"Weight as Distribution Quantile: {config.weight_as_distribution_quantile}"
)
logging.info(f"Weight m: {config.weight_m}")
logging.info(f"Model Name: {config.model_name}")
logging.info(f"Step: {config.step}")
logging.info(f"Startpoint: {config.startpoint}")
logging.info("```")
def log_comparison_variance_details(config):
logging.info(f"Comparison Variance Analysis: {config.name_save_file}")
logging.info("```")
logging.info(f"Variable: {config.variable}")
logging.info(f"Group: {config.group}")
logging.info(f"Data: {config.data}")
logging.info("```")
def log_pearson_correlation_details(config):
logging.info(f"Pearson Correlation Analysis: {config.name_save_file}")
logging.info("```")
logging.info(f"Variable 1: {config.variable_1}")
logging.info(f"Variable 2: {config.variable_2}")
logging.info(f"Data: {config.dataset}")
logging.info("```")
def log_ttest_details(config, ttest_type: str):
logging.info(f"{ttest_type} TTest Analysis: {config.name_save_file}")
logging.info("```")
logging.info(f"Variable 1: {config.variable_1}")
logging.info(f"Variable 2: {config.variable_2}")
logging.info(f"Data: {config.dataset}")
logging.info("```")
def log_visualization_details(config):
logging.info(f"Visualization: {config.name_save_file}")
logging.info("```")
logging.info(f"Data: {config.dataset}")
logging.info(f"Title: {config.title}")
if isinstance(config, BarChartPlotParameters):
logging.info("Creating Bar Chart")
logging.info(f"Variable X: {config.variable_x_axis}")
logging.info(f"Variable Y: {config.variable_y_axis}")
logging.info(f"Chart Orientation: {config.chart_orientation}")
logging.info(f"Sort Order: {config.sort_order}")
elif isinstance(config, BoxPlotParameters):
logging.info("Creating Box Plot")
logging.info(f"Variable 1: {config.variable_1}")
logging.info(f"Variable 2: {config.variable_2}")
logging.info(f"X-Axis Label: {config.x_axis_label}")
logging.info(f"Y-Axis Label: {config.y_axis_label}")
elif isinstance(config, ContourPlotParameters):
logging.info("Creating Contour Plot")
logging.info(f"Function Name: {config.function_name}")
logging.info(f"X-Axis Maximum: {config.x_axis_maximum}")
logging.info(f"Y-Axis Maximum: {config.y_axis_maximum}")
elif isinstance(config, HistogramPlotParameters):
logging.info("Creating Histogram Plot")
logging.info(f"Variable: {config.variable}")
logging.info(f"X-Axis Limits: {config.x_axis_limits}")
logging.info(f"X-Axis Logarithmic Scaling: {config.x_axis_logarithmic_scaling}")
logging.info(f"Y-Axis Logarithmic Scaling: {config.y_axis_logarithmic_scaling}")
elif isinstance(config, CountDistributionPlotParameters):
logging.info("Creating Count Distribution Plot")
logging.info(f"Variable: {config.variable}")
logging.info(f"X-Axis Limits: {config.x_axis_limits}")
logging.info(f"X-Axis Logarithmic Scaling: {config.x_axis_logarithmic_scaling}")
logging.info(f"Y-Axis Logarithmic Scaling: {config.y_axis_logarithmic_scaling}")
elif isinstance(config, DensityPlotParameters):
logging.info("Creating Density Plot")
logging.info(f"Variable X: {config.variable_x_axis}")
logging.info(f"Variable Y: {config.variable_y_axis}")
logging.info(f"Data Breakpoints: {config.data_breakpoints}")
elif isinstance(config, ForestPlotParameters):
logging.info("Creating Forest Plot")
logging.info(f"Regression Model Names: {config.regression_model_names}")
logging.info(f"Coefficient Names: {config.coefficient_names}")
logging.info(f"X-Axis Minimum: {config.x_axis_minimum}")
logging.info(f"X-Axis Maximum: {config.x_axis_maximum}")
logging.info(f"Dotsize: {config.dotsize}")
elif isinstance(config, ForestPlotPairedTTestParameters):
logging.info("Creating Forest Plot Paired TTest")
logging.info(f"Paired TTest Names: {config.paired_ttest_names}")
logging.info(f"X-Axis Minimum: {config.x_axis_minimum}")
logging.info(f"X-Axis Maximum: {config.x_axis_maximum}")
logging.info(f"Dotsize: {config.dotsize}")
elif isinstance(config, GroupedHistogramParameters):
logging.info("Creating Grouped Histogram")
logging.info(f"Group By: {config.group_by}")
logging.info(f"Aggregation Variable: {config.aggregation_variable}")
logging.info(f"Aggregation Function: {config.aggregation_function}")
logging.info(f"X-Axis Label: {config.x_axis_label}")
logging.info(f"Y-Axis Label: {config.y_axis_label}")
elif isinstance(config, HeatmapParameters):
logging.info("Creating Heatmap")
logging.info(f"Axis Variables: {config.axis_variables}")
logging.info(f"Heat Variable: {config.heat_variable}")
logging.info(f"Max Axis Values: {config.axis_maxima}")
logging.info(f"Min Axis Values: {config.axis_minima}")
logging.info(f"Log Scaling: {config.logarithmic_heat_scaling}")
elif isinstance(config, HexbinPlotParameters):
logging.info("Creating Hexbin Plot")
logging.info(f"Variable X: {config.variable_x_axis}")
logging.info(f"Variable Y: {config.variable_y_axis}")
logging.info(f"X Axis Maximum: {config.x_axis_maximum}")
logging.info(f"Y Axis Maximum: {config.y_axis_maximum}")
logging.info(f"Trendline: {config.trendline}")
logging.info(f"Log Scaling: {config.logarithmic_hex_scaling}")
elif isinstance(config, PercentageStackedBarChartPlotParameters):
logging.info("Creating Percentage Stacked Bar Chart")
logging.info(f"Variable X: {config.variable_x_axis}")
logging.info(f"Variables to compare: {config.variables_to_compare}")
logging.info(f"Chart Orientation: {config.chart_orientation}")
logging.info(f"Sort Order: {config.sort_order}")
elif isinstance(config, RidgelineParameters):
logging.info("Creating Ridgeline Plot")
logging.info(f"Variable X: {config.variable_x_axis}")
logging.info(f"Variable Y: {config.variable_y_axis}")
logging.info(f"Data Breakpoints: {config.data_breakpoints}")
elif isinstance(config, SimpleScatterPlotParameters):
logging.info("Creating Simple Scatter Plot")
logging.info(f"Variable X: {config.variable_x_axis}")
logging.info(f"Variable Y: {config.variable_y_axis}")
elif isinstance(config, StackedBarChartPlotParameters):
logging.info("Creating Bar Chart")
logging.info(f"Variable X: {config.variable_x_axis}")
logging.info(f"Variable Y: {config.variable_y_axis}")
logging.info(f"Hue: {config.hue}")
logging.info(f"Chart Orientation: {config.chart_orientation}")
logging.info(f"Sort Order: {config.sort_order}")
elif isinstance(config, SurfacePlotParameters):
logging.info("Creating Surface Plot")
logging.info(f"Function Name: {config.function_name}")
logging.info(f"X-Axis Maximum: {config.x_axis_maximum}")
logging.info(f"Y-Axis Maximum: {config.y_axis_maximum}")
logging.info(f"X-Axis Label: {config.x_axis_label}")
logging.info(f"Y-Axis Label: {config.y_axis_label}")
logging.info(f"Z-Axis Label: {config.z_axis_label}")
logging.info(f"Elevation Angle: {config.elevation_angle}")
logging.info(f"Azimuth Angle: {config.azimuth_angle}")
elif isinstance(config, ViolinPlotParameters):
logging.info("Creating Violin Plot")
logging.info(f"Variable X: {config.variable_x_axis}")
logging.info(f"Variable Y: {config.variable_y_axis}")
logging.info(f"X-Axis Label: {config.x_axis_label}")
logging.info(f"Y-Axis Label: {config.y_axis_label}")
else:
raise ValueError(f"Invalid type of visualization requested {type(config)}")
logging.info("```")