diff --git a/101/paper.pdf b/101/paper.pdf new file mode 100644 index 0000000000000000000000000000000000000000..4b021eec46fb355f2ccd0cf73f9a0a9c58d96232 --- /dev/null +++ b/101/paper.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0288699f0b4a67532df6cb1a3dd6391f46688831a3b092bea21f0fb35e1889d8 +size 3262536 diff --git a/101/replication_package/.gitignore b/101/replication_package/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..b5c0a7affc1fd03d029add7a8e9f4393e55d4eb5 --- /dev/null +++ b/101/replication_package/.gitignore @@ -0,0 +1,30 @@ +.Rproj.user +.Rhistory +.RData +.Ruserdata +.DS_Store +*.Rproj + +*.RData +Table_of_Languages.tab +ethnologue_pop_full.tsv +pop.tsv +pop_full.tsv +GB_wide_strict.tsv +*.png +.xlsx +*.jpg +*.svg +*.tiff +*.emf +*.eps +*.ps +*.wmf +*.pptx +*.docx +*.pdf +*.jpeg +*.qs + +#folders +*grambank-analysed* diff --git a/101/replication_package/.gitmodules b/101/replication_package/.gitmodules new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/101/replication_package/LICENSE.md b/101/replication_package/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..2f244ac814036ecd9ba9f69782e89ce6b1dca9eb --- /dev/null +++ b/101/replication_package/LICENSE.md @@ -0,0 +1,395 @@ +Attribution 4.0 International + +======================================================================= + +Creative Commons Corporation ("Creative Commons") is not a law firm and +does not provide legal services or legal advice. Distribution of +Creative Commons public licenses does not create a lawyer-client or +other relationship. Creative Commons makes its licenses and related +information available on an "as-is" basis. Creative Commons gives no +warranties regarding its licenses, any material licensed under their +terms and conditions, or any related information. Creative Commons +disclaims all liability for damages resulting from their use to the +fullest extent possible. + +Using Creative Commons Public Licenses + +Creative Commons public licenses provide a standard set of terms and +conditions that creators and other rights holders may use to share +original works of authorship and other material subject to copyright +and certain other rights specified in the public license below. The +following considerations are for informational purposes only, are not +exhaustive, and do not form part of our licenses. + + Considerations for licensors: Our public licenses are + intended for use by those authorized to give the public + permission to use material in ways otherwise restricted by + copyright and certain other rights. Our licenses are + irrevocable. Licensors should read and understand the terms + and conditions of the license they choose before applying it. + Licensors should also secure all rights necessary before + applying our licenses so that the public can reuse the + material as expected. Licensors should clearly mark any + material not subject to the license. This includes other CC- + licensed material, or material used under an exception or + limitation to copyright. More considerations for licensors: + wiki.creativecommons.org/Considerations_for_licensors + + Considerations for the public: By using one of our public + licenses, a licensor grants the public permission to use the + licensed material under specified terms and conditions. If + the licensor's permission is not necessary for any reason--for + example, because of any applicable exception or limitation to + copyright--then that use is not regulated by the license. Our + licenses grant only permissions under copyright and certain + other rights that a licensor has authority to grant. Use of + the licensed material may still be restricted for other + reasons, including because others have copyright or other + rights in the material. A licensor may make special requests, + such as asking that all changes be marked or described. + Although not required by our licenses, you are encouraged to + respect those requests where reasonable. More_considerations + for the public: + wiki.creativecommons.org/Considerations_for_licensees + +======================================================================= + +Creative Commons Attribution 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 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. + + a. 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. + + b. 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. + + c. 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. + + d. 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. + + e. 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. + + f. Licensed Material means the artistic or literary work, database, + or other material to which the Licensor applied this Public + License. + + g. 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. + + h. Licensor means the individual(s) or entity(ies) granting rights + under this Public License. + + i. 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. + + j. 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. + + k. You means the individual or entity exercising the Licensed Rights + under this Public License. Your has a corresponding meaning. + + +Section 2 -- Scope. + + a. License grant. + + 1. 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: + + a. reproduce and Share the Licensed Material, in whole or + in part; and + + b. produce, reproduce, and Share Adapted Material. + + 2. 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. + + 3. Term. The term of this Public License is specified in Section + 6(a). + + 4. 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. + + 5. Downstream recipients. + + a. 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. + + b. 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. + + 6. 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). + + b. Other rights. + + 1. 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. + + 2. Patent and trademark rights are not licensed under this + Public License. + + 3. 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. + + +Section 3 -- License Conditions. + +Your exercise of the Licensed Rights is expressly made subject to the +following conditions. + + a. Attribution. + + 1. If You Share the Licensed Material (including in modified + form), You must: + + a. retain the following if it is supplied by the Licensor + with the Licensed Material: + + i. 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); + + ii. a copyright notice; + + iii. a notice that refers to this Public License; + + iv. a notice that refers to the disclaimer of + warranties; + + v. a URI or hyperlink to the Licensed Material to the + extent reasonably practicable; + + b. indicate if You modified the Licensed Material and + retain an indication of any previous modifications; and + + c. indicate the Licensed Material is licensed under this + Public License, and include the text of, or the URI or + hyperlink to, this Public License. + + 2. 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. + + 3. If requested by the Licensor, You must remove any of the + information required by Section 3(a)(1)(A) to the extent + reasonably practicable. + + 4. 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: + + a. 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; + + b. 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 + + c. 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. + + a. 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. + + b. 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. + + c. 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. + + a. 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. + + b. Where Your right to use the Licensed Material has terminated under + Section 6(a), it reinstates: + + 1. automatically as of the date the violation is cured, provided + it is cured within 30 days of Your discovery of the + violation; or + + 2. 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. + + c. 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. + + d. Sections 1, 5, 6, 7, and 8 survive termination of this Public + License. + + +Section 7 -- Other Terms and Conditions. + + a. The Licensor shall not be bound by any additional or different + terms or conditions communicated by You unless expressly agreed. + + b. 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. + + a. 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. + + b. 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. + + c. 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. + + d. 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. + + +======================================================================= + +Creative Commons is not a party to its public +licenses. Notwithstanding, Creative Commons may elect to apply one of +its public licenses to material it publishes and in those instances +will be considered the “Licensor.” The text of the Creative Commons +public licenses is dedicated to the public domain under the CC0 Public +Domain Dedication. Except for the limited purpose of indicating that +material is shared under a Creative Commons public license or as +otherwise permitted by the Creative Commons policies published at +creativecommons.org/policies, Creative Commons does not authorize the +use of the trademark "Creative Commons" or any other trademark or logo +of Creative Commons without its prior written consent including, +without limitation, in connection with any unauthorized modifications +to any of its public licenses or any other arrangements, +understandings, or agreements concerning use of licensed material. For +the avoidance of doubt, this paragraph does not form part of the +public licenses. + +Creative Commons may be contacted at creativecommons.org. diff --git a/101/replication_package/README.md b/101/replication_package/README.md new file mode 100644 index 0000000000000000000000000000000000000000..fd7ff4e022cda610d8922776281bfaec6f818800 --- /dev/null +++ b/101/replication_package/README.md @@ -0,0 +1,105 @@ +# Code accompanying the paper *Societies of strangers do not speak grammatically simpler languages* by Olena Shcherbakova, Susanne Maria Michaelis, Hannah J. Haynie, Sam Passmore, Volker Gast, Russell D. Gray, Simon J. Greenhill, Damián E. Blasi, and Hedvig Skirgård + +# Overview of structure +This project contains all data and all scripts for data-wrangling, analysis and plotting. + +## Data sources + +The data that serves as the input for the analysis comes from Grambank, +(v1.0, Skirgård et al (in prep)), AUTOTYP (v1.01, Bickel et al (2022)), Glottolog (v4.5), EDGE-tree (v1.0.0, Bouckaert et al (2023)), Ethnologue (Eberhard et al 2020)), and WALS (Dryer & Haspelmath 2013). + +With the exception of the Ethnologue data, all the data is available +openly via the science archive Zenodo and/or public GitHub repositories. A +modified version of the Ethnologue data is available in this repository, it contains +transformed population numbers that cannot be transformed back into the +raw numbers. The MCCT EDGE-tree is found in a file inside grambank-analysed. + +Zenodo locations: + +* Grambank (v.1.0) +* Grambank-analysed (v1.0) +* Glottolog-cldf (v4.5) +* AUTOTYP (v1.0.1) + +GitHub locations: + +* EDGE-tree (v1.0.0) +* Grambank (v1.0) +* Grambank-analysed (v1.0) +* Glottolog-cldf (v4.5) +* AUTOTYP (v1.01) + +In this project, we fetch the data from the Zenodo locations by downloading a zip file and expanding it. We have also made tables and files available derived from these sources in this repos so that users may run the analysis without engaging with fetching from Zenodo. The scripts that generate these files are also found in this repository and can be run by users if they would like. + +## Running data-wrangling, analysis and plotting scripts +All scripts are written in R. The necessary scripts can be called +one-by-one in order or executed by running the script `all_scripts.R`. + +Running `all_scripts.R` involves the following: + +- downloading, installing and loading necessary packages and create + folders for output (see `requirements.R` & `install_and_load_INLA.R` + for specific packages) +- generating a table of languoids from Glottolog v.4.5 +- calculating metric scores from Grambank v.1.0: fusion metric and + informativity metric; both metrics designed by Hedvig Skirgård and + Hannah J. Haynie. +- generating population table (all sociodemographic variables in one + dataframe): data from Ethnologue e24 (Eberhard et al. 2020) and + Supplementary Materials in `data\lang_endangerment_predictors.xlsx` + from Bromham et al. (2022). Based on data availability, within + `set_up_inla.R`, it is necessary to specify whether `sample` is + `"full"` (full access to both Ethnologue variables in transformed + and non-transformed form and running all models; possible only for + users with their own access to Ethnologue) and `"reduced"` (access + to both Ethnologue variables - the number of L1 speakers and the + proportion of L2 speakers - in transformed form (logged and + standardized number of L1 speakers and the proportion of L2 speakers + than than raw numbers) and running all models except for one + including the interaction between the number of L1 speakers and L2 + proportion; the dataset is already provided within the repository). +- wrangling global phylogeny - EDGE-tree (v1.0.0, Bouckaert et al 2023) +- generating AUTOTYP-areas table (v.1.0.1, Bickel et al. 2020) +- prepare everything for and run INLA analysis, including sensitivity + analyses +- measuring phylogenetic signal in fusion and informativity +- generating tables from INLA analyses, including sensitivity analyses +- make plots +- running additional analyses on WALS-based morphological complexity scores used in Lupyan & Dale's (2010) study (`data/complexity_data_WALS.csv`) (obtained from Gary Lupyan, personal communication 02.06.2023) + +Please note: the necessary files, such as metrics scores obtained from the +Grambank dataset and parameters of metrics (these determine the +inclusion of Grambank into the metrics), are already made available. The +script that generates these `generating_GB_input_file.R` relies on the +folder `grambank_analysed` which incorporates data from +Grambank v.1.0, AUTOTYP (v1.0.1) and Glottolog v.4.5. To run this script, one needs to +first clone the repository and then run the R-script `get_external_data.R`. + +# References + +R. Bouckaert, D. Redding, O. Sheehan, T. Kyritsis, R. Gray, K. E. Jones, Q. Atkinson, Global language diversification is linked to socio-ecology and threat status (2022), , doi:10.31235/osf.io/f8tr6. + +Bickel, Balthasar, Johanna Nichols, Taras Zakharko, Alena +Witzlack-Makarevich, Kristine Hildebrandt, Michael Rießler, Lennart +Bierkandt, Fernando Zúñiga & John B Lowe. 2022. The AUTOTYP database +(v1.1.0). . + +Bromham, Lindell, Russell Dinnage, Hedvig Skirgård, Andrew Ritchie, +Marcel Cardillo, Felicity Meakins, Simon Greenhill & Xia Hua. 2022. +Global predictors of language endangerment and the future of linguistic +diversity. Nature ecology & evolution 6(2). 163--173. + +Dryer, Matthew & Martin Haspelmath (eds.). 2013. The World Atlas of Language Structures Online. Leipzig: Max Planck Institute for Evolutionary Anthropology. http://wals.info. + +Eberhard, David M., Gary F. Simons & Charles D. Fennig (eds.). 2020. +Ethnologue: Languages of the World. Dallas, Texas: SIL International. +www.ethnologue.com. + +Hammarström, Harald & Forkel, Robert & Haspelmath, Martin & Bank, Sebastian. 2021. Glottolog 4.5. Leipzig: Max Planck Institute for Evolutionary Anthropology. (Available online at https://glottolog.org) + +Skirgård, H., Haynie, H. J., Blasi, D. E., Hammarström, H., Collins, J., Latarche, J., Lesage, J., Weber, T., Witzlack-Makarevich, A., Passmore, S., Chira, A., Dinnage, R., Maurits, L., Dinnage, R., Dunn, M., Reesink, G., Singer, R., Bowern, C., Epps, P., Hill, J., Vesakoski, O., Robbeets, M., Abbas, K., Auer, D., Bakker, N., Barbos, G., Borges, R., Danielsen, S., Dorenbusch, L., Dorn, E., Elliott, J., Falcone, G., Fischer, J., Ghanggo Ate, Y., Gibson, H., Göbel, H., Goodall, J., Gruner, V., Harvey, A., Hayes, R., Heer, L., Herrera Miranda, R., Hübler, N., Huntington-Rainey, B., Ivani, J., Johns, M., Just, E., Kashima, E., Kipf, C., Klingenberg, J., König, N., Koti, K., Kowalik, R., Krasnoukhova, O., Lindvall, N., Lorenzen, M., Lutzenberger, H., Martins, T., Mata German, C., Meer, S., Montoya Samamé, J., Müller, M., Muradoglu, S., Neely, K., Nickel, J., Norvik, M., Oluoch, C. A., Peacock, J., Pearey , I., Peck, N., Petit, S., Pieper, S., Poblete, M., Prestipino, D., Raabe, L., Raja, A., Reimringer, J., Rey, S., Rizaew, J., Ruppert, E., Salmon, K., Sammet, J., Schembri, R., Schlabbach, L., Schmidt, F., Skilton, A., Smith, W. D., Sousa, H., Sverredal, K., Valle, D., Vera, J., Voß, J., Witte, T., Wu, H., Yam, S., Ye 葉婧婷, J., Yong, M., Yuditha, T., Zariquiey, R., Forkel, R., Evans, N., Levinson, S. C., Haspelmath, M., Greenhill, S. J., Atkinson, Q. D. and Gray, R. D. (in prep) "Grambank reveals the importance of genealogical constraints on linguistic diversity and highlights the impact of language loss". Science Advances + +Hedvig Skirgård; Hannah J. Haynie; Harald Hammarström; Damián E. Blasi; Jeremy Collins; Jay Latarche; Jakob Lesage; Tobias Weber; Alena Witzlack-Makarevich; Michael Dunn; Ger Reesink; Ruth Singer; Claire Bowern; Patience Epps; Jane Hill; Outi Vesakoski; Noor Karolin Abbas; Sunny Ananth; Daniel Auer; Nancy A. Bakker; Giulia Barbos; Anina Bolls; Robert D. Borges; Mitchell Browen; Lennart Chevallier; Swintha Danielsen; Sinoël Dohlen; Luise Dorenbusch; Ella Dorn; Marie Duhamel; Farah El Haj Ali; John Elliott; Giada Falcone; Anna-Maria Fehn; Jana Fischer; Yustinus Ghanggo Ate; Hannah Gibson; Hans-Philipp Göbel; Jemima A. Goodall; Victoria Gruner; Andrew Harvey; Rebekah Hayes; Leonard Heer; Roberto E. Herrera Miranda; Nataliia Hübler; Biu H. Huntington-Rainey; Guglielmo Inglese; Jessica K. Ivani; Marilen Johns; Erika Just; Ivan Kapitonov; Eri Kashima; Carolina Kipf; Janina V. Klingenberg; Nikita König; Aikaterina Koti; Richard G. A. Kowalik; Olga Krasnoukhova; Kate Lynn Lindsey; Nora L. M. Lindvall; Mandy Lorenzen; Hannah Lutzenberger; Alexandra Marley; Tânia R. A. Martins; Celia Mata German; Suzanne van der Meer; Jaime Montoya; Michael Müller; Saliha Muradoglu; HunterGatherer; David Nash; Kelsey Neely; Johanna Nickel; Miina Norvik; Bruno Olsson; Cheryl Akinyi Oluoch; David Osgarby; Jesse Peacock; India O.C. Pearey; Naomi Peck; Jana Peter; Stephanie Petit; Sören Pieper; Mariana Poblete; Daniel Prestipino; Linda Raabe; Amna Raja; Janis Reimringer; Sydney C. Rey; Julia Rizaew; Eloisa Ruppert; Kim K. Salmon; Jill Sammet; Rhiannon Schembri; Lars Schlabbach; Frederick W. P. Schmidt; Dineke Schokkin; Jeff Siegel; Amalia Skilton; Hilário de Sousa; Kristin Sverredal; Daniel Valle; Javier Vera; Judith Voß; Daniel Wikalier Smith; Tim Witte; Henry Wu; Stephanie Yam; Jingting Ye 葉婧婷; Maisie Yong; Tessa Yuditha; Roberto Zariquiey; Robert Forkel; Nicholas Evans; Stephen C. Levinson; Martin Haspelmath; Simon J. Greenhill; Quentin D. Atkinson; Russell D. Gray (2023) Grambank v1.0 https://doi.org/10.5281/zenodo.7740140 + +The Grambank Consortium (eds.). 2022. Grambank 1.0. Leipzig: Max Planck +Institute for Evolutionary Anthropology. . diff --git a/101/replication_package/WALS_reanalysis_controlled_setup.R b/101/replication_package/WALS_reanalysis_controlled_setup.R new file mode 100644 index 0000000000000000000000000000000000000000..99292f1fde5ca17bcdf39788a896526a0ec39083 --- /dev/null +++ b/101/replication_package/WALS_reanalysis_controlled_setup.R @@ -0,0 +1,140 @@ +source("install_and_load_INLA.R") + +#parameters +kappa = 1 +phi_1 = c(1, 1.25) # "Local" version: (sigma, phi) First value is not used + +WALS <- read_csv("data/complexity_data_WALS.csv") %>% + dplyr::select("Name" = lang, roundComp, logpop2, "ISO_639" = silCode) %>% + dplyr::mutate(ISO_639 = str_to_lower(ISO_639)) + +min_val <- min(WALS$roundComp) +max_val <- max(WALS$roundComp) + +# Perform the rescaling +WALS$roundComp <- (WALS$roundComp - min_val) / (max_val - min_val) + +pop_file_fn <- + "data_wrangling/ethnologue_pop_SM_morph_compl_reanalysis.tsv" +L1 <- + read_tsv(pop_file_fn, show_col_types = F) %>% dplyr::select(ISO_639, L1_log10_scaled) + +glottolog_df <- + read_tsv("data_wrangling/glottolog_cldf_wide_df.tsv", col_types = cols()) %>% + dplyr::select( + Glottocode, + Language_ID, + "ISO_639" = ISO639P3code, + Language_level_ID, + level, + Family_ID, + Longitude, + Latitude + ) %>% + mutate(Language_level_ID = if_else(is.na(Language_level_ID), Glottocode, Language_level_ID)) %>% + mutate(Family_ID = ifelse(is.na(Family_ID), Language_level_ID, Family_ID)) %>% + dplyr::select( + Glottocode, + Language_ID, + ISO_639, + Language_level_ID, + level, + Family_ID, + Longitude, + Latitude + ) + +WALS_df <- WALS %>% + inner_join(L1, + by = c("ISO_639")) %>% + inner_join(glottolog_df, by = "ISO_639") %>% + filter(!is.na(Latitude), !is.na(Longitude)) %>% + dplyr::select(Language_ID = Glottocode, + Name, + roundComp, + ISO_639, + L1_log10_scaled, + Longitude, + Latitude) + + + +tree <- read.tree(file.path("data_wrangling/wrangled.tree")) + +#dropping tips not in Grambank +WALS_df <- WALS_df[WALS_df$Language_ID %in% tree$tip.label,] +tree <- keep.tip(tree, WALS_df$Language_ID) + +x <- + assert_that(all(tree$tip.label %in% WALS_df$Language_ID), msg = "The data and phylogeny taxa do not match") + +## Building standardized phylogenetic precision matrix +tree_scaled <- tree + +tree_vcv = vcv.phylo(tree_scaled) +typical_phylogenetic_variance = exp(mean(log(diag(tree_vcv)))) + +#We opt for a sparse phylogenetic precision matrix (i.e. it is quantified using all nodes and tips), since sparse matrices make the analysis in INLA less time-intensive +tree_scaled$edge.length <- + tree_scaled$edge.length / typical_phylogenetic_variance +phylo_prec_mat <- MCMCglmm::inverseA(tree_scaled, + nodes = "ALL", + scale = FALSE)$Ainv + +WALS_df = WALS_df[order(match(WALS_df$Language_ID, rownames(phylo_prec_mat))), ] + +#"local" set of parameters +## Create spatial covariance matrix using the matern covariance function +spatial_covar_mat_1 = varcov.spatial(WALS_df[, c("Longitude", "Latitude")], + cov.pars = phi_1, kappa = kappa)$varcov +# Calculate and standardize by the typical variance +typical_variance_spatial_1 = exp(mean(log(diag( + spatial_covar_mat_1 +)))) +spatial_cov_std_1 = spatial_covar_mat_1 / typical_variance_spatial_1 +spatial_prec_mat_1 = solve(spatial_cov_std_1) +dimnames(spatial_prec_mat_1) = list(WALS_df$Language_ID, WALS_df$Language_ID) + +## Since we are using a sparse phylogenetic matrix, we are matching taxa to rows in the matrix +phy_id = match(tree$tip.label, rownames(phylo_prec_mat)) +WALS_df$phy_id = phy_id + +## Other effects are in the same order they appear in the dataset +WALS_df$sp_id = 1:nrow(spatial_prec_mat_1) + + +formula <- as.formula( + paste( + "roundComp ~", + "L1_log10_scaled +", + "f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, + constr = TRUE, hyper = pcprior_hyper) + +f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, +constr = TRUE, hyper = pcprior_hyper)" + ) +) + +result <- inla( + formula, + family = "gaussian", + data = WALS_df, + control.compute = list(waic = TRUE) +) +summary(result) + +save(result, file = "output_models/model_WALS_controlled.RData") + +social_effects_controlled <- + c("morphological complexity ~ L1 + phylogenetic effect + spatial effect", + round( + c( + result$summary.fixed[2,]$`0.025quant`, + result$summary.fixed[2,]$`0.5quant`, + result$summary.fixed[2,]$`0.975quant`, + nrow(WALS_df) + ), + 2 + ), "default (~10%)") + +save(social_effects_controlled, file = "output_models/social_effects_controlled.RData") + diff --git a/101/replication_package/WALS_reanalysis_controlled_setup_high_coverage.R b/101/replication_package/WALS_reanalysis_controlled_setup_high_coverage.R new file mode 100644 index 0000000000000000000000000000000000000000..ddb246555c18be12e5e0a6eea812e39deac30610 --- /dev/null +++ b/101/replication_package/WALS_reanalysis_controlled_setup_high_coverage.R @@ -0,0 +1,181 @@ +source("install_and_load_INLA.R") + +#parameters +kappa = 1 +phi_1 = c(1, 1.25) # "Local" version: (sigma, phi) First value is not used + +WALS <- read_csv("data/complexity_data_WALS.csv") %>% + dplyr::select("Name" = lang, roundComp, logpop2, "ISO_639" = silCode) %>% + dplyr::mutate(ISO_639 = str_to_lower(ISO_639)) %>% + inner_join(read_csv("output_tables/WALS_high_coverage.csv"), + by = c("ISO_639")) + +min_val <- min(WALS$roundComp) +max_val <- max(WALS$roundComp) + +# Perform the rescaling +WALS$roundComp <- (WALS$roundComp - min_val) / (max_val - min_val) + +pop_file_fn <- + "data_wrangling/ethnologue_pop_SM_morph_compl_reanalysis.tsv" +L1 <- + read_tsv(pop_file_fn, show_col_types = F) %>% dplyr::select(ISO_639, L1_log10_scaled) + +glottolog_df <- + read_tsv("data_wrangling/glottolog_cldf_wide_df.tsv", col_types = cols()) %>% + dplyr::select( + Glottocode, + Name, + Language_ID, + "ISO_639" = ISO639P3code, + Language_level_ID, + level, + Family_ID, + Longitude, + Latitude + ) %>% + mutate(Language_level_ID = if_else(is.na(Language_level_ID), Glottocode, Language_level_ID)) %>% + mutate(Family_ID = ifelse(is.na(Family_ID), Language_level_ID, Family_ID)) %>% + dplyr::select( + Glottocode, + Name, + Language_ID, + ISO_639, + Language_level_ID, + level, + Family_ID, + Longitude, + Latitude + ) + +WALS_df <- WALS %>% + inner_join(L1, + by = c("ISO_639")) %>% + inner_join(glottolog_df, by = "ISO_639") %>% + filter(!is.na(Latitude),!is.na(Longitude)) %>% + dplyr::select(Language_ID = Glottocode, + Name, + roundComp, + ISO_639, + L1_log10_scaled, + Longitude, + Latitude) + +# jitter points locations +WALS_df$Latitude <- jitter(WALS_df$Latitude, amount = 0.001) +WALS_df$Longitude <- jitter(WALS_df$Longitude, amount = 0.001) + +tree <- read.tree(file.path("data_wrangling/wrangled.tree")) + +#dropping tips not in Grambank +WALS_df <- WALS_df[WALS_df$Language_ID %in% tree$tip.label, ] +WALS_df <- WALS_df[!duplicated(WALS_df$Language_ID),] +tree <- keep.tip(tree, WALS_df$Language_ID) + +x <- + assert_that(all(tree$tip.label %in% WALS_df$Language_ID), msg = "The data and phylogeny taxa do not match") + +## Building standardized phylogenetic precision matrix +tree_scaled <- tree + +tree_vcv = vcv.phylo(tree_scaled) +typical_phylogenetic_variance = exp(mean(log(diag(tree_vcv)))) + +#We opt for a sparse phylogenetic precision matrix (i.e. it is quantified using all nodes and tips), since sparse matrices make the analysis in INLA less time-intensive +tree_scaled$edge.length <- + tree_scaled$edge.length / typical_phylogenetic_variance +phylo_prec_mat <- MCMCglmm::inverseA(tree_scaled, + nodes = "ALL", + scale = FALSE)$Ainv + +WALS_df = WALS_df[order(match(WALS_df$Language_ID, rownames(phylo_prec_mat))),] + +#"local" set of parameters +## Create spatial covariance matrix using the matern covariance function +spatial_covar_mat_1 = varcov.spatial(WALS_df[, c("Longitude", "Latitude")], + cov.pars = phi_1, kappa = kappa)$varcov +# Calculate and standardize by the typical variance +typical_variance_spatial_1 = exp(mean(log(diag( + spatial_covar_mat_1 +)))) +spatial_cov_std_1 = spatial_covar_mat_1 / typical_variance_spatial_1 +spatial_prec_mat_1 = solve(spatial_cov_std_1) +dimnames(spatial_prec_mat_1) = list(WALS_df$Language_ID, WALS_df$Language_ID) + +## Since we are using a sparse phylogenetic matrix, we are matching taxa to rows in the matrix +phy_id <- match(tree$tip.label, rownames(phylo_prec_mat)) +if (length(phy_id) != nrow(WALS_df)) { + stop("The number of phylogenetic IDs does not match the number of rows in WALS_df.") +} + +WALS_df$phy_id <- phy_id + +## Other effects are in the same order they appear in the dataset +WALS_df$sp_id = 1:nrow(spatial_prec_mat_1) + + +formula <- as.formula( + paste( + "roundComp ~", + "L1_log10_scaled +", + "f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, + constr = TRUE, hyper = pcprior_hyper) + +f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, +constr = TRUE, hyper = pcprior_hyper)" + ) +) + +result <- inla( + formula, + family = "gaussian", + control.family = list(hyper = pcprior_hyper), + data = WALS_df, + control.compute = list(waic = TRUE) +) +summary(result) + +save(result, file = "output_models/model_WALS_high_coverage.RData") + +#mean estimate of L1_Users: with credible intervals not crossing zero () + +social_effects_controlled_coverage <- + c( + "morphological complexity ~ L1 + phylogenetic effect + spatial effect", + round( + c( + result$summary.fixed[2, ]$`0.025quant`, + result$summary.fixed[2, ]$`0.5quant`, + result$summary.fixed[2, ]$`0.975quant`, + nrow(WALS_df) + ), + 2 + ), + "35%" + ) + +save(social_effects_controlled_coverage, file = "output_models/social_effects_controlled.RData") + +load("output_models/social_effects_uncontrolled.RData") +load("output_models/social_effects_controlled.RData") +load("output_models/social_effects_controlled_coverage.RData") + +effects_morph_comp <- + as.data.frame( + rbind( + social_effects_uncontrolled, + social_effects_controlled, + social_effects_controlled_coverage + ) + ) +colnames(effects_morph_comp) <- + c("model", + "2.5%", + "50%", + "97.5%", + "sample size", + "feature coverage threshold") + +rownames(effects_morph_comp) <- NULL + +effects_morph_comp %>% + write_csv("output_tables/WALS_morph_compl_effects.csv") diff --git a/101/replication_package/WALS_reanalysis_setup.R b/101/replication_package/WALS_reanalysis_setup.R new file mode 100644 index 0000000000000000000000000000000000000000..3b50542eb5ab565fd183c15b060580b9363a3844 --- /dev/null +++ b/101/replication_package/WALS_reanalysis_setup.R @@ -0,0 +1,40 @@ +source("install_and_load_INLA.R") + +#parameters +kappa = 1 +phi_1 = c(1, 1.25) # "Local" version: (sigma, phi) First value is not used + +WALS <- read_csv("data/complexity_data_WALS.csv") %>% + dplyr::select("Name"=lang, roundComp, logpop2, "ISO_639"=silCode) %>% + dplyr::mutate(ISO_639 = str_to_lower(ISO_639)) + +min_val <- min(WALS$roundComp) +max_val <- max(WALS$roundComp) + +# Perform the rescaling +WALS$roundComp <- (WALS$roundComp - min_val) / (max_val - min_val) + +pop_file_fn <- "data_wrangling/ethnologue_pop_SM_morph_compl_reanalysis.tsv" +L1 <- + read_tsv(pop_file_fn, show_col_types = F) %>% dplyr::select(ISO_639, L1_log10_scaled) + +WALS_df <- WALS %>% + inner_join(L1, + by = c("ISO_639")) + +formula <- as.formula(paste("roundComp ~", "L1_log10_scaled")) +result <- inla(formula, family = "gaussian", + data = WALS_df, control.compute = list(waic = TRUE)) +summary(result) + +save(result, file = "output_models/models_WALS_uncontrolled.RData") + +social_effects_uncontrolled <- c("morphological complexity ~ L1", + round(c( + result$summary.fixed[2,]$`0.025quant`, + result$summary.fixed[2,]$`0.5quant`, + result$summary.fixed[2,]$`0.975quant`, nrow(WALS_df)), 2), "default (~10%)") + +save(social_effects_uncontrolled, file = "output_models/social_effects_uncontrolled.RData") + + diff --git a/101/replication_package/WALS_sparseness.R b/101/replication_package/WALS_sparseness.R new file mode 100644 index 0000000000000000000000000000000000000000..44a69439aa42b03992d007a9d8a7ce9c10f257df --- /dev/null +++ b/101/replication_package/WALS_sparseness.R @@ -0,0 +1,70 @@ +source("requirements.R") + +library(INLA) +inla.setOption(inla.mode = "experimental") + +wals <- read.delim( + "https://raw.githubusercontent.com/cldf-datasets/wals/master/cldf/languages.csv", + sep = "," +) %>% + dplyr::select(ID, ISO_639 = ISO_codes, Name, Glottocode) %>% + rename(Language_ID = ID) %>% #renaming the column to avoid problems + left_join( + read.delim( + "https://raw.githubusercontent.com/cldf-datasets/wals/master/cldf/values.csv", + sep = "," + ) %>% dplyr::select(Language_ID, Parameter_ID, Value) + ) %>% + dplyr::select(-Language_ID) %>% + rename(Language_ID = Glottocode) + +wals_selected <- wals %>% + filter( + Parameter_ID == "20A" | + Parameter_ID == "26A" | + Parameter_ID == "49A" | + Parameter_ID == "28A" | + Parameter_ID == "98A" | + Parameter_ID == "22A" | + Parameter_ID == "100A" | + Parameter_ID == "102A" | + Parameter_ID == "48A" | + Parameter_ID == "29A" | + Parameter_ID == "74A" | + Parameter_ID == "75A" | + Parameter_ID == "76A" | + Parameter_ID == "77A" | + Parameter_ID == "112A" | + Parameter_ID == "34A" | + Parameter_ID == "36A" | + Parameter_ID == "92A" | + Parameter_ID == "66A" | + Parameter_ID == "67A" | + Parameter_ID == "65A" | + Parameter_ID == "70A" | + Parameter_ID == "57A" | + Parameter_ID == "59A" | + Parameter_ID == "73A" | + Parameter_ID == "38A" | + Parameter_ID == "39A" | + Parameter_ID == "41A" | + Parameter_ID == "101A" + ) %>% + pivot_wider( + names_from = Parameter_ID, + values_from = Value + ) + +# Specify the range of columns +start_column <- "92A" +end_column <- "76A" + +# Filter and gather the selected columns +wals_selected_na <- wals_selected %>% + rowwise() %>% + mutate(na_proportion = mean(is.na(c_across(starts_with(start_column):starts_with(end_column))))) %>% + filter(na_proportion <= 0.35) + +wals_selected_na %>% + write_csv("output_tables/WALS_high_coverage.csv") + diff --git a/101/replication_package/all_scripts.R b/101/replication_package/all_scripts.R new file mode 100644 index 0000000000000000000000000000000000000000..9703c0b84dbc2988e92c419a87400471599b0030 --- /dev/null +++ b/101/replication_package/all_scripts.R @@ -0,0 +1,91 @@ +#Running all scripts + +#download packages and create folders +#generate Glottolog table (based on Glottolog 4.4) +#calculate metric scores (based on Grambank 1.0) +#generate population table (all sociodemographic variables in one dataframe) +#wrangling EDGE tree +#generating AUTOTYP areas table +source("get_external_data.R") +source("generating_GB_input_file.R") +source("set_up_general.R") + +#setup for INLA analysis +source("install_and_load_INLA.R") +#choosing whether to use the full dataset (possible only for reviewers and if one has own access to Ethnologue and saved the dataset in the data folder on their own) or to only to the subset of Ethnologue with transformed variables made available in this repostiory after running create_pop_table.R + +#sample <- "full" +sample <- "reduced" #default + +source("make_ethnologue_SM_and_merging_tables.R") +source("create_pop_table.R") +source("set_up_inla.R") + +#run all INLA models + extract main results tables +#Note that previously "fusion" was called "boundness", and this is how it is referenced in all scripts + +#predictors: random effects - phylogenetic and spatial (same scripts for "full" and "reduced" versions) +source("models_Boundness_phylogenetic_spatial.R") +source("models_Informativity_phylogenetic_spatial.R") + +if(sample == "full"){ + + #predictors: phylogenetic and spatial random effects + sociodemograhic variables as fixed effects + source("models_Boundness_social.R") + source("models_Informativity_social.R") + + #predictors: sociodemographic variables as fixed effects + source("models_Boundness_social_only.R") + source("models_Informativity_social_only.R") + + #conduct sensitivity testing + extract the corresponding table + source("runs_sensitivity.R") + + #extract tables from INLA analyses + source("table_INLA_summary_all_models_SI.R") + source("variance_top_ranking_models.R") + + #plotting main results + source("plot_social_effects_combined.R") +} + +if(sample == "reduced"){ + + #predictors: phylogenetic and spatial random effects + sociodemograhic variables as fixed effects + #(on reduced set of social variables: without log10 transformed L1 speakers) + source("models_Boundness_reduced_social.R") + source("models_Informativity_reduced_social.R") + + #predictors: sociodemographic variables as fixed effects + source("models_Boundness_reduced_social_only.R") + source("models_Informativity_reduced_social_only.R") + + #conduct sensitivity testing + extract the corresponding table + source("runs_sensitivity_on_reduced.R") + + #extract tables from INLA analyses + source("table_INLA_summary_all_models_SI_reduced.R") + source("variance_top_ranking_models_reduced.R") + + #plotting main results + source("plots_social_effects_combined_on_reduced.R") +} + +#measure phylogenetic signal in two fusion and informativity +source("measuring_phylosignal.R") + + +#plotting +source("plot_maps_main.R") #maps of scores +source("plot_heatmap_B_I.R") #phylogenetic tree with a heatmap +source("plot_map_Africa.R") +source("plot_map_Eurasia.R") +source("plot_heatmap_informativity_Uralic.R") #Uralic tree (informativity) + combined plot with two maps from above +source("plot_spatial_parameters_linear_distances.R") #SI figure for visualizing how covariance under different kappa and phi parameters corresponds to spatial distances + +#additional analyses on WALS data +source("make_ethnologue_SM_for_morphological_complexity_reanalysis.R") +source("WALS_sparseness.R") +source("WALS_reanalysis_setup.R") +source("WALS_reanalysis_controlled_setup.R") +source("WALS_reanalysis_controlled_setup_high_coverage.R") #analysis + summary table diff --git a/101/replication_package/assigning_AUTOTYP_areas.R b/101/replication_package/assigning_AUTOTYP_areas.R new file mode 100644 index 0000000000000000000000000000000000000000..fdcd674d5b5887b2f92c7796dc671f6f76e00387 --- /dev/null +++ b/101/replication_package/assigning_AUTOTYP_areas.R @@ -0,0 +1,85 @@ +#This script assigns all languages in glottolog_df to their nearest AUTOTYP area + +#Script was written by Hedvig Skirgård + +source("requirements.R") + +OUTPUTDIR_data_wrangling <- here("data_wrangling") +# create output dir if it does not exist. +if (!dir.exists(OUTPUTDIR_data_wrangling)) { + dir.create(OUTPUTDIR_data_wrangling) +} + +if (!file.exists(here(OUTPUTDIR_data_wrangling, "glottolog_AUTOTYPE_areas.tsv"))) { + #GB langs for subsettting + GB_langs <- + read_tsv("data/GB_wide/GB_wide_strict.tsv", col_types = WIDE_COLSPEC) %>% + dplyr::select(Language_ID) + + #combining the tables languages and values from glottolog_df-cldf into one wide dataframe. + #this can be replaced with any list of Language_IDs, long and lat + + glottolog_fn <- "data_wrangling/glottolog_cldf_wide_df.tsv" + if (!file.exists(glottolog_fn)) { + source("generating_GB_input_file.R") + } + + glottolog_df <- read.delim(glottolog_fn , sep = "\t") %>% + dplyr::select(Language_ID, Longitude, Latitude) %>% + inner_join(GB_langs, by = "Language_ID") + + ##Adding in areas of linguistic contact from AUTOTYP + + AUTOTYP <- + read.delim( + "https://raw.githubusercontent.com/autotyp/autotyp-data/master/data/csv/Register.csv", + sep = "," + ) %>% + dplyr::select(Language_ID = Glottocode, Area, Longitude, Latitude) %>% + group_by(Language_ID, Area) %>% #some lgs are assigned to more than one area, we level that out. + sample_n(1) + + #This next bit where we find the autotyp areas of languages was written by Seán Roberts + # We know the autotyp-area of langauges in autotyp and their long lat. We don't know the autotyp area of languages in Glottolog. We also can't be sure that the long lat of languoids with the same glottoids in autotyp and glottolog_df have the exact identical long lat. First let's make two datasets, one for autotyp languages (hence lgs where we know the area) and those that we wish to know about, the Glottolog ones. + + lgs_with_known_area <- + as.matrix(AUTOTYP[!is.na(AUTOTYP$Area), c("Longitude", "Latitude")]) + rownames(lgs_with_known_area) <- + AUTOTYP[!is.na(AUTOTYP$Area), ]$Language_ID + + known_areas <- AUTOTYP %>% + dplyr::filter(!is.na(Area)) %>% + dplyr::select(Language_ID, Area) %>% + distinct() %>% + dplyr::select(AUTOTYP_Language_ID = Language_ID, everything()) + + rm(AUTOTYP) + + lgs_with_unknown_area <- + as.matrix(glottolog_df[, c("Longitude", "Latitude")]) + rownames(lgs_with_unknown_area) <- glottolog_df$Language_ID + + # For missing, find area of closest langauge + atDist <- + rdist.earth(lgs_with_known_area, lgs_with_unknown_area, miles = F) + + rm(lgs_with_known_area, lgs_with_unknown_area) + + df_matched_up <- + as.data.frame(unlist(apply(atDist, 2, function(x) { + names(which.min(x)) + })), stringsAsFactors = F) %>% + rename(AUTOTYP_Language_ID = `unlist(apply(atDist, 2, function(x) { names(which.min(x)) }))`) + + glottolog_df_with_AUTOTYP <- df_matched_up %>% + tibble::rownames_to_column("Language_ID") %>% + full_join(known_areas, by = "AUTOTYP_Language_ID") %>% + right_join(glottolog_df, by = "Language_ID") %>% + dplyr::select(-AUTOTYP_Language_ID) %>% + group_by(Language_ID) %>% #some lgs are assigned to more than one area, we level that out. + sample_n(1) %>% + rename(AUTOTYP_area = Area) + + glottolog_df_with_AUTOTYP %>% + write_tsv(here(OUTPUTDIR_data_wrangling, "glottolog_AUTOTYPE_areas.tsv")) +} diff --git a/101/replication_package/create_pop_table.R b/101/replication_package/create_pop_table.R new file mode 100644 index 0000000000000000000000000000000000000000..fe7d2f9188a726716d61682516ea4270afbc0e0b --- /dev/null +++ b/101/replication_package/create_pop_table.R @@ -0,0 +1,117 @@ +#create_pop_table + +OUTPUTDIR_data_wrangling <- here("data_wrangling") +# create output dir if it does not exist. +if (!dir.exists(OUTPUTDIR_data_wrangling)) { + dir.create(OUTPUTDIR_data_wrangling) +} + + +#Glottolog df for ISO_639 merging +glottolog_df <- + read_tsv("data_wrangling/glottolog_cldf_wide_df.tsv", col_types = cols()) %>% + dplyr::select( + Glottocode, + Language_ID, + "ISO_639" = ISO639P3code, + Language_level_ID, + level, + Family_ID, + Longitude, + Latitude + ) %>% + mutate(Language_level_ID = if_else(is.na(Language_level_ID), Glottocode, Language_level_ID)) %>% + mutate(Family_ID = ifelse(is.na(Family_ID), Language_level_ID, Family_ID)) %>% + dplyr::select( + Glottocode, + Language_ID, + ISO_639, + Language_level_ID, + level, + Family_ID, + Longitude, + Latitude + ) + + +if (sample == "full") { + data_ethnologue <- + read_tsv("data_wrangling/ethnologue_pop_full.tsv") +} + +if (sample == "reduced") { + #double check if the file below needs to be changed + data_ethnologue <- + read_tsv("data_wrangling/ethnologue_pop_SM.tsv", show_col_types = F) %>% + rename(L1_log10_st = L1_log10_scaled) %>% + dplyr::select(ISO_639, Language_ID, L1_log10_st, L2_prop) +} + +social_vars <- + readxl::read_xlsx( + "data/lang_endangerment_predictors.xlsx", + sheet = "Supplementary data 1", + skip = 1, + col_types = "text", + na = "NA" + ) %>% + left_join(glottolog_df, by = c("ISO" = "ISO_639")) %>% + rename("ISO_639" = "ISO") %>% + dplyr::select( + Language_ID = Glottocode, + ISO_639, + official_status, + language_of_education, + bordering_language_richness + ) %>% + rename(Official = official_status) %>% + # naniar::replace_with_na(replace = list(L1_log10 = -Inf, L2_log10 = -Inf)) #removing for now + dplyr::mutate(neighboring_languages = bordering_language_richness, Education = + language_of_education) %>% + dplyr::mutate(neighboring_languages = as.numeric(neighboring_languages)) %>% + #dplyr::mutate(neighboring_languages_log10 = log10(neighboring_languages+1)) %>% + dplyr::mutate(neighboring_languages_st = scale(neighboring_languages)[, 1]) %>% + #dplyr::mutate(neighboring_languages_log10_st = scale(neighboring_languages_log10)[,1]) %>% + dplyr::select(Language_ID, Education, Official, neighboring_languages_st) + +if (sample == "full") { + social_vars %>% + left_join(data_ethnologue, by = c("Language_ID")) %>% + dplyr::select( + Language_ID, + L1_log10_st, + L1_log10, + L2_prop, + Education, + Official, + neighboring_languages_st + ) %>% + write_tsv(here(OUTPUTDIR_data_wrangling, "pop_full.tsv")) +} else{ + social_vars %>% + left_join(data_ethnologue, by = c("Language_ID")) %>% + dplyr::select(Language_ID, + L1_log10_st, + L2_prop, + Education, + Official, + neighboring_languages_st) %>% + write_tsv(here(OUTPUTDIR_data_wrangling, "pop_reduced.tsv")) +} + +glottolog_df_ISO <- glottolog_df %>% +dplyr::select("Language_ID", "ISO_639") + +if (sample == "reduced") { + social_vars %>% + left_join(data_ethnologue, by = c("Language_ID")) %>% + dplyr::select(Language_ID, + L1_log10_st, + L2_prop, + Education, + Official, + neighboring_languages_st) %>% + left_join(glottolog_df_ISO, + by = c("Language_ID")) %>% + write_tsv(here(OUTPUTDIR_data_wrangling, "pop_reduced_with_ISO.tsv")) +} diff --git a/101/replication_package/creating_boundness_metric.R b/101/replication_package/creating_boundness_metric.R new file mode 100644 index 0000000000000000000000000000000000000000..2b1a7d38f77fe1f5ad36332ef9df1a57ef3e4dfd --- /dev/null +++ b/101/replication_package/creating_boundness_metric.R @@ -0,0 +1,48 @@ +#boundness/fusion + +#Script was written by Hedvig Skirgård + +source("requirements.R") + +OUTPUTDIR1 <- file.path('.', "output", "Bound_morph") +# create output dir if it does not exist. +if (!dir.exists(OUTPUTDIR1)) { + dir.create(OUTPUTDIR1) +} + +if (!file.exists(here(OUTPUTDIR1, "bound_morph_score.tsv"))) { + GB_wide <- + read_tsv(file.path("data", "GB_wide", "GB_wide_strict.tsv"), + col_types = WIDE_COLSPEC) + + #read in sheet with scores for whether a feature denotes fusion + GB_fusion_points <- + data.table::fread( + file.path("data", "GB_wide", "parameters.csv"), + encoding = 'UTF-8', + quote = "\"", + header = TRUE, + sep = "," + ) %>% + dplyr::select(Parameter_ID = ID, Fusion = boundness, informativity) %>% + mutate(Fusion = as.numeric(Fusion)) + + df_morph_count <- GB_wide %>% + filter(na_prop <= 0.25) %>% #exclude languages with more than 25% missing data + dplyr::select(-na_prop) %>% + reshape2::melt(id.vars = "Language_ID") %>% + dplyr::rename(Parameter_ID = variable) %>% + inner_join(GB_fusion_points, by = "Parameter_ID") %>% + filter(Fusion == 1) %>% + filter(!is.na(value)) %>% + group_by(Language_ID) %>% + dplyr::summarise(mean_morph = mean(value)) %>% + dplyr::select(Language_ID, boundness = mean_morph) + + boundness_st = scale(df_morph_count$boundness) + df_morph_count <- cbind(df_morph_count, boundness_st) + + df_morph_count %>% + write_tsv(file.path(OUTPUTDIR1, "bound_morph_score.tsv")) + +} \ No newline at end of file diff --git a/101/replication_package/creating_informativity_score.R b/101/replication_package/creating_informativity_score.R new file mode 100644 index 0000000000000000000000000000000000000000..42439324955d9973bd6d579315a00e04b6c8531b --- /dev/null +++ b/101/replication_package/creating_informativity_score.R @@ -0,0 +1,51 @@ +#informativity +source("requirements.R") + +#Script was written by Hedvig Skirgård + +OUTPUTDIR2 <- file.path('.', "output", "Informativity") +# create output dir if it does not exist. +if (!dir.exists(OUTPUTDIR2)) { dir.create(OUTPUTDIR2) } + +if (!file.exists(here(OUTPUTDIR2, "informativity_score.tsv"))) { + +GB_wide <- + read_tsv(file.path("data", "GB_wide", "GB_wide_strict.tsv"), + show_col_types = F) %>% + filter(na_prop <= 0.25) %>% + dplyr::select(-na_prop) + +#read in sheet with scores for whether a feature denotes informativity +GB_informativity_points <- read_csv(file.path("data", "GB_wide", "parameters.csv"), + show_col_types = F) %>% + dplyr::select(Parameter_ID = ID, informativity) %>% + mutate(informativity = replace(informativity, Parameter_ID == "GB177", "argumentanimacy")) %>% #manually adding another parameter: assigning the parameter of GB177 ("Can the verb carry a marker of animacy of argument, unrelated to any gender/noun class of the argument visible in the NP domain?") feature to be informative + filter(!is.na(informativity)) + +GB_long_for_calc <- GB_wide %>% + reshape2::melt(id.vars = "Language_ID") %>% + rename(Parameter_ID = variable) %>% + inner_join(GB_informativity_points , by = "Parameter_ID") + +##informativity score +lg_df_informativity_score <- GB_long_for_calc %>% + mutate(value = if_else(Parameter_ID == "GB140", abs(value - 1), value)) %>% # reversing GB140 because 0 is the informative state + group_by(Language_ID, informativity) %>% #grouping per language and per informativity category + summarise(sum_informativity = sum(value, na.rm = T), + #for each informativity cateogry for each langauge, how many are answered 1 ("yes") + sum_na = sum(is.na(value))) %>% #how many of the values per informativity category are missing + mutate(sum_informativity = ifelse(sum_na >= 1 & + sum_informativity == 0, NA, sum_informativity)) %>% #if there is at least one NA and the sum of values for the entire category is 0, the informativity score should be NA because there could be a 1 hiding under the NA value + mutate(informativity_score = ifelse(sum_informativity >= 1, 1, sum_informativity)) %>% + ungroup() %>% + group_by(Language_ID) %>% + summarise(`Informativity` = mean(informativity_score, na.rm = T, .groups = "drop")) %>% + dplyr::select(Language_ID, `Informativity`) + +informativity_st = scale(lg_df_informativity_score$Informativity) +lg_df_informativity_score <- + cbind(lg_df_informativity_score, informativity_st) + +lg_df_informativity_score %>% + write_tsv(here(OUTPUTDIR2, "informativity_score.tsv")) +} \ No newline at end of file diff --git a/101/replication_package/data/GB_wide/parameters.csv b/101/replication_package/data/GB_wide/parameters.csv new file mode 100644 index 0000000000000000000000000000000000000000..d311021d77044058e30ba5cfc57f3f5ef7b51008 --- /dev/null +++ b/101/replication_package/data/GB_wide/parameters.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:effcb8e4ae1ef49e5558a828a2efba5b446c9c289e564fabd822e4b3d1739083 +size 955498 diff --git a/101/replication_package/data/complexity_data_WALS.csv b/101/replication_package/data/complexity_data_WALS.csv new file mode 100644 index 0000000000000000000000000000000000000000..146e175d9b2543d2c6873f2049291e2fe0a64015 --- /dev/null +++ b/101/replication_package/data/complexity_data_WALS.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:05af559ebdfd0fb8a4a84f0ab525fbce3f2609eb43301fb0edeb310a12b9805a +size 49149 diff --git a/101/replication_package/data/glottolog-cldf_wide_df.tsv b/101/replication_package/data/glottolog-cldf_wide_df.tsv new file mode 100644 index 0000000000000000000000000000000000000000..22b4ee5a25f5e6f9a5d9a0eb3d478fc7a5d04af8 --- /dev/null +++ b/101/replication_package/data/glottolog-cldf_wide_df.tsv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fa70feae51fe695ae91d4ec29e5f78fb90bc26e507ede909dd3c10d45e14852b +size 10892168 diff --git a/101/replication_package/data/lang_endangerment_predictors.xlsx b/101/replication_package/data/lang_endangerment_predictors.xlsx new file mode 100644 index 0000000000000000000000000000000000000000..fa75b983916cae66d4c1d09b609b9143781a1083 --- /dev/null +++ b/101/replication_package/data/lang_endangerment_predictors.xlsx @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:65ba3f53b2eb30352d758c326b4889910022adb64b45bdead1d0fbfa00df6e69 +size 5040478 diff --git a/101/replication_package/data/phylogenies/EDGE6635-merged-relabelled.tree b/101/replication_package/data/phylogenies/EDGE6635-merged-relabelled.tree new file mode 100644 index 0000000000000000000000000000000000000000..2a9581f561e2fdee8433dd4487661aa16a2ac966 --- /dev/null +++ b/101/replication_package/data/phylogenies/EDGE6635-merged-relabelled.tree @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a99c4b3cda474be6091ed433fa3fc5ba50f55082e599319b6a6677b5baacbc7f +size 20461790 diff --git a/101/replication_package/data_wrangling/ethnologue_pop_SM.tsv b/101/replication_package/data_wrangling/ethnologue_pop_SM.tsv new file mode 100644 index 0000000000000000000000000000000000000000..1b623510a75101b48164ebbc0bca54ced77ceadb --- /dev/null +++ b/101/replication_package/data_wrangling/ethnologue_pop_SM.tsv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:42cde751f7f3555c3b9fa4b7bf70a5f0e9c5927c9524286834759370e5c82d90 +size 228185 diff --git a/101/replication_package/data_wrangling/ethnologue_pop_SM_morph_compl_reanalysis.tsv b/101/replication_package/data_wrangling/ethnologue_pop_SM_morph_compl_reanalysis.tsv new file mode 100644 index 0000000000000000000000000000000000000000..6f0871f4ee07d7a07aaa4dd11b126ffa16c13984 --- /dev/null +++ b/101/replication_package/data_wrangling/ethnologue_pop_SM_morph_compl_reanalysis.tsv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bf9d6ae875e98a5bb4cecfcfee4dd69f0f70949205ff6e3b3f3a6df0430d6e25 +size 639778 diff --git a/101/replication_package/data_wrangling/glottolog_AUTOTYPE_areas.tsv b/101/replication_package/data_wrangling/glottolog_AUTOTYPE_areas.tsv new file mode 100644 index 0000000000000000000000000000000000000000..0974800d8cd011e709fe3db0d610a5bba809bae6 --- /dev/null +++ b/101/replication_package/data_wrangling/glottolog_AUTOTYPE_areas.tsv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7365af670f13ad1fee3af423a7fb2c1a508c8dcf90ddd086e43571893ee77818 +size 93225 diff --git a/101/replication_package/data_wrangling/glottolog_cldf_wide_df.tsv b/101/replication_package/data_wrangling/glottolog_cldf_wide_df.tsv new file mode 100644 index 0000000000000000000000000000000000000000..40b0bd16565c739da52d695d997068f183e026d8 --- /dev/null +++ b/101/replication_package/data_wrangling/glottolog_cldf_wide_df.tsv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4171fe67d3786919c87dae3a64b85524d6b5c636311d8845e1137e84878f76bc +size 10906052 diff --git a/101/replication_package/data_wrangling/pop_reduced.tsv b/101/replication_package/data_wrangling/pop_reduced.tsv new file mode 100644 index 0000000000000000000000000000000000000000..b02e31b944a6553c46b7f23bfa70266594ddcdb7 --- /dev/null +++ b/101/replication_package/data_wrangling/pop_reduced.tsv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8ef392e4f37b4afafe44312bd52cbfdb5d182ce23bcdac0d8d036d419b839a29 +size 289960 diff --git a/101/replication_package/data_wrangling/pop_reduced_with_ISO.tsv b/101/replication_package/data_wrangling/pop_reduced_with_ISO.tsv new file mode 100644 index 0000000000000000000000000000000000000000..0f4357f11ff1cf62b08a513c5ae66bee6a34fcb4 --- /dev/null +++ b/101/replication_package/data_wrangling/pop_reduced_with_ISO.tsv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bbd2c0fbc91a2b9bd7b6ae38f259840b0a27173af6d86ac8d163e84adc0ab5ae +size 316008 diff --git a/101/replication_package/data_wrangling/wrangled.tree b/101/replication_package/data_wrangling/wrangled.tree new file mode 100644 index 0000000000000000000000000000000000000000..e61593148fba0266b2e3c0630c737545db24ad27 --- /dev/null +++ b/101/replication_package/data_wrangling/wrangled.tree @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f50cb6ea90d4e3edd5aa26127e19ea1f97dc97a4a809994bcd4cece8720bc522 +size 80074 diff --git a/101/replication_package/generating_GB_input_file.R b/101/replication_package/generating_GB_input_file.R new file mode 100644 index 0000000000000000000000000000000000000000..7398cb99ae8eedc378cb13703bd993762980b1fa --- /dev/null +++ b/101/replication_package/generating_GB_input_file.R @@ -0,0 +1,42 @@ +source("requirements.R") + +if (!dir.exists("./grambank-analysed/R_grambank/output")) { + dir.create("./grambank-analysed/R_grambank/output") +} + +#creating a full Grambank file: first, within the submodule itself, and next placing it in the data folder within the repository + +setwd("grambank-analysed/R_grambank") + +if (!(file.exists("./../../data/GB_wide/GB_wide_strict.tsv"))) { + cat("Generating GB_wide_strict.\n") + + source("make_wide.R") + + read_tsv("output/GB_wide/GB_wide_strict.tsv", show_col_types = F) %>% + write_tsv(file = "../../data/GB_wide/GB_wide_strict.tsv") + +} + +#extracting glottolog: first, within the submodule itself, and next placing it in the data folder within the repository + +if (!(file.exists("../../../data_wrangling/glottolog_cldf_wide_df.tsv"))) { + cat("Generating glottolog table.\n") + + source("make_glottolog-cldf_table.R") + + read_tsv("output/non_GB_datasets/glottolog-cldf_wide_df.tsv", + show_col_types = F) %>% + write_tsv(file = "./../../data_wrangling/glottolog_cldf_wide_df.tsv") +} + +if (!(file.exists("./../data/GB_wide/parameters.csv"))) { + cat("Generating parameters table.\n") + + read_csv("../grambank/cldf/parameters.csv", show_col_types = F) %>% + dplyr::select(ID, Name, Description, boundness = Boundness, informativity = Informativity) %>% + write_csv(file = "../../data/GB_wide/parameters.csv") +} + + +setwd("../../") diff --git a/101/replication_package/get_external_data.R b/101/replication_package/get_external_data.R new file mode 100644 index 0000000000000000000000000000000000000000..48a5823c06320aa05662bca0791b70d31e3637df --- /dev/null +++ b/101/replication_package/get_external_data.R @@ -0,0 +1,46 @@ +#Script was written by Hedvig Skirgård + +source("requirements.R") + +#setting up a tempfile path where we can put the zipped files before unzipped to a specific location +filepath <- file.path(tempfile()) + +##grambank-analysed: downloading, zipping and moving +grambank_analysed_fn <- c("https://zenodo.org/record/7740822/files/grambank/grambank-analysed-v1.0.zip") + +utils::download.file(file.path(grambank_analysed_fn), destfile = filepath) +utils::unzip(zipfile = filepath, exdir = "grambank-analysed") + +#Zenodo locations contain a dir with the name of the repos and the commit in the release. This is not convenient for later scripts, so we move the contents up one level +old_fn <- "grambank-analysed/grambank-grambank-analysed-fcf971a/" +old_fn_files <- list.files(old_fn) +new_fn <- "grambank-analysed/" + +file.copy(from = paste0(old_fn, old_fn_files),to = new_fn, recursive = T, overwrite = T) +#remove old dir +unlink(old_fn, recursive = T) + +## dirs within grambank-analysed +# for the dirs within grambank-analysed we can fetch them with a for loop + +fns_within_grambank_analysed_zip<- c("https://zenodo.org/record/7740140/files/grambank/grambank-v1.0.zip", "https://zenodo.org/record/5772649/files/glottolog/glottolog-cldf-v4.5.zip", "https://zenodo.org/record/6255206/files/autotyp-data-v1.0.1.zip") +exdir_names <- c("grambank-analysed/grambank", "grambank-analysed/glottolog-cldf", "grambank-analysed/autotyp-data") + +commit_dir_names <- c("grambank-analysed/grambank/grambank-grambank-9e0f341/", "grambank-analysed/glottolog-cldf/glottolog-glottolog-cldf-6f1558e/", "grambank-analysed/autotyp-data/autotyp-data-1.0.1/") + + +for(n in 1:3){ + utils::download.file(file.path(fns_within_grambank_analysed_zip[n]), destfile = filepath) + utils::unzip(zipfile = filepath, exdir = exdir_names[n]) + + old_fn <- commit_dir_names[n] + old_fn_files <- list.files(old_fn) + new_fn <- exdir_names[n] + + file.copy(from = paste0(old_fn, old_fn_files),to = new_fn, recursive = T, overwrite = T) + #remove old dir + unlink(old_fn, recursive = T) + +} + + diff --git a/101/replication_package/install_and_load_INLA.R b/101/replication_package/install_and_load_INLA.R new file mode 100644 index 0000000000000000000000000000000000000000..d1efd81eb2deb0f803203bd04e889e7bcd0c980e --- /dev/null +++ b/101/replication_package/install_and_load_INLA.R @@ -0,0 +1,22 @@ +#installing and loading INLA + +# script was written by Hedvig Skirgård and Sam Passmore + +# 1. Install/update and load BiocManager and other necessary packages +source("requirements.R") + +if (!is_installed("INLA")) {message("INLA wasn't installed, it is now being installed.") + +# 2. Install INLA dependencies with BiocManager using: +BiocManager::install(c("grap","Rgraphviz","sf","rgdal","rgl","spdep"), force=TRUE)#, version = '3.15') #version indication is relevant only for R version 4.2.0 +#grap package is not available for Bioconductor 3.16 (latest version) + +# 3. Install INLA using: +# NOTE: This is a big download +install.packages("INLA", repos=c(getOption("repos"), + INLA="https://inla.r-inla-download.org/R/testing"), dep=TRUE) + +} + +library(INLA) +inla.setOption(inla.mode="experimental") diff --git a/101/replication_package/make_ethnologue_SM_and_merging_tables.R b/101/replication_package/make_ethnologue_SM_and_merging_tables.R new file mode 100644 index 0000000000000000000000000000000000000000..ff5ef8f42d98ec31f5c667bf5415381fd1e6fb1a --- /dev/null +++ b/101/replication_package/make_ethnologue_SM_and_merging_tables.R @@ -0,0 +1,54 @@ +source("requirements.R") + +#Script was written by Hedvig Skirgård + +#this script necessitates that grambank and glottolog files exist. if they do not, run generate_GB_input_file.R +#this script generates the Ethnologue file that can be published based on the raw ethnologue file from SIL. The raw file CANNOT be shared publicly, but derived information that cannot be transformed back to the original values can, such as scaled and log-transformed values + +glottolog_df <- read_tsv("data_wrangling/glottolog_cldf_wide_df.tsv", show_col_types = F) %>% + dplyr::select(ISO_639 = ISO639P3code, Glottocode, Language_level_ID) %>% + mutate(Language_level_ID = ifelse(is.na(Language_level_ID), Glottocode, Language_level_ID)) + +GB <- read_tsv("data/GB_wide/GB_wide_strict.tsv", show_col_types = F) %>% + dplyr::select(Glottocode = "Language_ID") + +#this script needs the Table_of_languages.tab file to exists, which is only available to people with an SIL lisence +data_ethnologue <- read_tsv("data/Table_of_Languages.tab", show_col_types = F) %>% + filter(!is.na("All_Users")) %>% #remove rows with missing data for pop of all users + filter(!is.na("L1_Users")) %>% + left_join(glottolog_df, by = "ISO_639" ) %>% + dplyr::select(-Glottocode) %>% #removing old Glottocode column + rename(Glottocode = Language_level_ID) %>% + group_by(Glottocode) %>% + summarise(All_Users = sum(All_Users, na.rm = T), + L1_Users = sum(L1_Users, na.rm = T), + ISO_639 = paste0(ISO_639, collapse = "; ")) + +#do some the subsettting to GB and log10 and L2 prop +data_ethnologue <- data_ethnologue %>% + inner_join(GB, by = "Glottocode" ) %>% + dplyr::mutate(L2 = All_Users - L1_Users, + #calculating the number of L2 users by subtracting the number of L1 from All users + L2_prop = L2/ All_Users, + #calculating the proportion of L2 users out of the entire population + L1_log10 = log10(L1_Users+1), + All_Users_log10 = log10(All_Users+1)) %>% #adding a 1 for cases where pop is 0 + mutate(L2_prop = ifelse(All_Users == 0, 0, L2_prop)) %>% #if All users is 0, L2_prop would be NA if we didn't do this (can't divide by 0). It should be 0 + dplyr::select(Glottocode, ISO_639, L1_log10, L2_prop, L1_Users, All_Users_log10, All_Users) + +#do the scaling +data_ethnologue$L1_scaled <- scale(data_ethnologue$L1_Users)[,1] +data_ethnologue$L1_log10_scaled <- scale(data_ethnologue$L1_log10)[,1] + +data_ethnologue$All_Users_scaled <- scale(data_ethnologue$All_Users)[,1] +data_ethnologue$All_Users_log10_scaled <- scale(data_ethnologue$All_Users_log10)[,1] + +#write to file: Ethnologue data for supplementary materials and merging into "reduced" version of the final dataset with social variables (excluding L1_log10) +data_ethnologue %>% + dplyr::select(ISO_639, Language_ID=Glottocode, L2_prop, L1_scaled, L1_log10_scaled, All_Users_scaled, All_Users_log10_scaled) %>% + write_tsv("data_wrangling/ethnologue_pop_SM.tsv") + +#write to file: Ethnologue data for merging into "full" version of the final dataset with social variables (including L1_log10) - won't be available to public +data_ethnologue %>% + dplyr::select(ISO_639, Language_ID=Glottocode, L2_prop, L1_st = L1_scaled, L1_log10_st=L1_log10_scaled, L1_log10 ) %>% + write_tsv("data_wrangling/ethnologue_pop_full.tsv") diff --git a/101/replication_package/make_ethnologue_SM_for_morphological_complexity_reanalysis.R b/101/replication_package/make_ethnologue_SM_for_morphological_complexity_reanalysis.R new file mode 100644 index 0000000000000000000000000000000000000000..bca87b76061488ab8c3a9410d7f3d349a2645f34 --- /dev/null +++ b/101/replication_package/make_ethnologue_SM_for_morphological_complexity_reanalysis.R @@ -0,0 +1,37 @@ +source("requirements.R") + +#Script was written by Hedvig Skirgård and modified by Olena Shcherbakova + +#this script generates the Ethnologue file that can be published based on the raw ethnologue file from SIL. The raw file CANNOT be shared publicly, but derived information that cannot be transformed back to the original values can, such as scaled and log-transformed values + +#this script needs the Table_of_languages.tab file to exists, which is only available to people with an SIL lisence +data_ethnologue <- read_tsv("data/Table_of_Languages.tab", show_col_types = F) %>% + filter(!is.na("All_Users")) %>% #remove rows with missing data for pop of all users + filter(!is.na("L1_Users")) %>% + dplyr::select(ISO_639, L1_Users, All_Users) + + +#do some the subsettting to GB and log10 and L2 prop +data_ethnologue <- data_ethnologue %>% + dplyr::mutate(L2 = All_Users - L1_Users, + #calculating the number of L2 users by subtracting the number of L1 from All users + L2_prop = L2/ All_Users, + #calculating the proportion of L2 users out of the entire population + L1_log10 = log10(L1_Users+1), + All_Users_log10 = log10(All_Users+1)) %>% #adding a 1 for cases where pop is 0 + mutate(L2_prop = ifelse(All_Users == 0, 0, L2_prop)) %>% #if All users is 0, L2_prop would be NA if we didn't do this (can't divide by 0). It should be 0 + dplyr::select(ISO_639, L1_log10, L2_prop, L1_Users, All_Users_log10, All_Users) + +#do the scaling +data_ethnologue$L1_scaled <- scale(data_ethnologue$L1_Users)[,1] +data_ethnologue$L1_log10_scaled <- scale(data_ethnologue$L1_log10)[,1] + +data_ethnologue$All_Users_scaled <- scale(data_ethnologue$All_Users)[,1] +data_ethnologue$All_Users_log10_scaled <- scale(data_ethnologue$All_Users_log10)[,1] + +#write to file: Ethnologue data for supplementary materials and merging into "reduced" version of the final dataset with social variables (excluding L1_log10) +data_ethnologue_file <- data_ethnologue %>% + dplyr::select(ISO_639, L2_prop, L1_scaled, L1_log10_scaled, All_Users_scaled, All_Users_log10_scaled) + +data_ethnologue_file <- data_ethnologue_file %>% + write_tsv("data_wrangling/ethnologue_pop_SM_morph_compl_reanalysis.tsv") diff --git a/101/replication_package/measuring_phylosignal.R b/101/replication_package/measuring_phylosignal.R new file mode 100644 index 0000000000000000000000000000000000000000..cb26078e5b6453a283167e844818289c18549b19 --- /dev/null +++ b/101/replication_package/measuring_phylosignal.R @@ -0,0 +1,48 @@ +#global tree +source("set_up_inla.R") + +metrics_joined <- metrics_joined %>% + filter(!is.na(L1_log10_st)) %>% + rename(L1_log_st = L1_log10_st) %>% + mutate(L1_copy = L1_log_st) %>% + filter(!is.na(L2_prop)) %>% + mutate(L2_copy = L2_prop) %>% + filter(!is.na(neighboring_languages_st)) %>% + filter(!is.na(Official)) %>% + filter(!is.na(Education)) %>% + filter(!is.na(boundness_st)) %>% + filter(!is.na(informativity_st)) + +#dropping tips not in Grambank +metrics_joined <- metrics_joined[metrics_joined$Language_ID %in% tree$tip.label, ] +tree <- keep.tip(tree, metrics_joined$Language_ID) + +x <- assert_that(all(tree$tip.label %in% metrics_joined$Language_ID), msg = "The data and phylogeny taxa do not match") + +#measuring phylogenetic signal of boundness/fusion +boundness<-setNames(metrics_joined$boundness_st, metrics_joined$Language_ID) +physig_boundness_l <- phytools::phylosig(tree, boundness, method="lambda", test=TRUE) +lambda_boundness_l <- physig_boundness_l[1][["lambda"]] +LR_boundness_l <- 2*(physig_boundness_l$logL-physig_boundness_l$logL0) #performing likelihood ratio test +P_lambda_boundness_l <- physig_boundness_l$P + +#measuring phylogenetic signal of informativity +informativity<-setNames(metrics_joined$informativity_st, metrics_joined$Language_ID) +physig_informativity_l <- phytools::phylosig(tree, informativity, method="lambda", test=TRUE) +lambda_informativity_l <- physig_informativity_l[1][["lambda"]] +LR_informativity_l <- 2*(physig_informativity_l$logL-physig_informativity_l$logL0) #performing likelihood ratio test +P_lambda_informativity_l <- physig_informativity_l$P + +boundness_signal <- c(physig_boundness_l$logL, physig_boundness_l$logL0, LR_boundness_l, lambda_boundness_l, P_lambda_boundness_l) +informativity_signal <- c(physig_informativity_l$logL, physig_informativity_l$logL0, LR_informativity_l, lambda_informativity_l, P_lambda_informativity_l) + + +#Making a table out of two measures of phylogenetic signal +physig <- as.data.frame(rbind(boundness_signal, informativity_signal)) +colnames(physig) <- c("logL", "logL0", "LR (lambda)", "lambda", "p-value") +physig <- round(physig, digits=2) +physig$`p-value` <- ifelse(physig$`p-value` < 0.001, "< 0.001", physig$`p-value`) +features <- as.data.frame(c("fusion", "informativity")) +colnames(features) <- "Feature" +physig <- cbind(features, physig) +write.csv(physig, file=here("output_tables", "Table_phylosig.csv"), row.names = FALSE) diff --git a/101/replication_package/models_Boundness_phylogenetic_spatial.R b/101/replication_package/models_Boundness_phylogenetic_spatial.R new file mode 100644 index 0000000000000000000000000000000000000000..67009ba8dd66a1fca898e8656f3e2a99281a4d3a --- /dev/null +++ b/101/replication_package/models_Boundness_phylogenetic_spatial.R @@ -0,0 +1,412 @@ +#model fitting: Boundness predicted by combinations of random phylogenetic and spatial factors + +#Script was written by Sam Passmore and modified by Olena Shcherbakova + +source("requirements.R") + +source("install_and_load_INLA.R") + +source("set_up_inla.R") + +metrics_joined <- metrics_joined %>% + filter(!is.na(L1_log10_st)) %>% + rename(L1_log_st = L1_log10_st) %>% + mutate(L1_copy = L1_log_st) %>% + filter(!is.na(L2_prop)) %>% + mutate(L2_copy = L2_prop) %>% + filter(!is.na(neighboring_languages_st)) %>% + filter(!is.na(Official)) %>% + filter(!is.na(Education)) %>% + filter(!is.na(boundness_st)) %>% + filter(!is.na(informativity_st)) + +#dropping tips not in Grambank +metrics_joined <- metrics_joined[metrics_joined$Language_ID %in% tree$tip.label, ] +tree <- keep.tip(tree, metrics_joined$Language_ID) + +x <- assert_that(all(tree$tip.label %in% metrics_joined$Language_ID), msg = "The data and phylogeny taxa do not match") + +## Building standardized phylogenetic precision matrix +tree_scaled <- tree + +tree_vcv = vcv.phylo(tree_scaled) +typical_phylogenetic_variance = exp(mean(log(diag(tree_vcv)))) + +#We opt for a sparse phylogenetic precision matrix (i.e. it is quantified using all nodes and tips), since sparse matrices make the analysis in INLA less time-intensive +tree_scaled$edge.length <- tree_scaled$edge.length/typical_phylogenetic_variance +phylo_prec_mat <- MCMCglmm::inverseA(tree_scaled, + nodes = "ALL", + scale = FALSE)$Ainv + +metrics_joined = metrics_joined[order(match(metrics_joined$Language_ID, rownames(phylo_prec_mat))),] + +#"local" set of parameters +## Create spatial covariance matrix using the matern covariance function +spatial_covar_mat_1 = varcov.spatial(metrics_joined[,c("Longitude", "Latitude")], + cov.pars = phi_1, kappa = kappa)$varcov +# Calculate and standardize by the typical variance +typical_variance_spatial_1 = exp(mean(log(diag(spatial_covar_mat_1)))) +spatial_cov_std_1 = spatial_covar_mat_1 / typical_variance_spatial_1 +spatial_prec_mat_1 = solve(spatial_cov_std_1) +dimnames(spatial_prec_mat_1) = list(metrics_joined$Language_ID, metrics_joined$Language_ID) + +#"regional" set of parameters +spatial_covar_mat_2 = varcov.spatial(metrics_joined[,c("Longitude", "Latitude")], cov.pars = phi_2, kappa = kappa)$varcov +typical_variance_spatial_2 = exp(mean(log(diag(spatial_covar_mat_2)))) +spatial_cov_std_2 = spatial_covar_mat_2 / typical_variance_spatial_2 +spatial_prec_mat_2 = solve(spatial_cov_std_2) +dimnames(spatial_prec_mat_2) = list(metrics_joined$Language_ID, metrics_joined$Language_ID) + +## Since we are using a sparse phylogenetic matrix, we are matching taxa to rows in the matrix +phy_id = match(tree$tip.label, rownames(phylo_prec_mat)) +metrics_joined$phy_id = phy_id + +## Other effects are in the same order they appear in the dataset +metrics_joined$sp_id = 1:nrow(spatial_prec_mat_1) + +#Preparing the formulas for 7 competing models to be used in inla() call +listcombo <- list(#phylogenetic and spatial effects in isolation + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper)"), + c("f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper)"), + c("f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_2, constr = TRUE, hyper = pcprior_hyper)"), + c("f(AUTOTYP_area, model = 'iid', hyper = pcprior_hyper)"), + #phylogenetic and distinct spatial effects in combination + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper)", + "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper)"), + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper)", + "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_2, constr = TRUE, hyper = pcprior_hyper)"), + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper)", + "f(AUTOTYP_area, model = 'iid', hyper = pcprior_hyper)")) + +predterms <- lapply(listcombo, function(x) paste(x, collapse="+")) + +predterms <- t(as.data.frame(predterms)) + +predterms_short <- predterms +predterms_short <- gsub("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper)", "Phylogenetic", predterms_short, fixed=TRUE) +predterms_short <- gsub("f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper)", "Spatial: local", predterms_short, fixed=TRUE) +predterms_short <- gsub("f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_2, constr = TRUE, hyper = pcprior_hyper)", "Spatial: regional", predterms_short, fixed=TRUE) +predterms_short <- gsub("f(AUTOTYP_area, model = 'iid', hyper = pcprior_hyper)", "Areal", predterms_short, fixed=TRUE) + +phylogenetic_element <- data.frame("judgement" = grepl("Phylogenetic", predterms_short), + number = 1:length(predterms_short)) +phylogenetic_element <- phylogenetic_element[phylogenetic_element$judgement == TRUE,]$number + +spatial_element_local <- data.frame("judgement" = grepl("local", predterms_short), + number = 1:length(predterms_short)) +spatial_element_local <- spatial_element_local[spatial_element_local$judgement == TRUE,]$number + +spatial_element_regional <- data.frame("judgement" = grepl("regional", predterms_short), + number = 1:length(predterms_short)) +spatial_element_regional <- spatial_element_regional[spatial_element_regional$judgement == TRUE,]$number + +spatial_element <- c(spatial_element_local, spatial_element_regional) + +areal_element <- data.frame("judgement" = grepl("Areal", predterms_short), + number = 1:length(predterms_short)) +areal_element <- areal_element[areal_element$judgement == TRUE,]$number + + +#preparing empty matrices to be filled with effect estimates (quantiles), model name, and WAIC value +phy_effects_matrix <- matrix(NA, 7, 5) +colnames(phy_effects_matrix) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +spa_effects_matrix <- matrix(NA, 7, 5) +colnames(spa_effects_matrix) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +area_effects_matrix <- matrix(NA, 7, 5) +colnames(area_effects_matrix) <- c("2.5%", "50%", "97.5%", "model", "WAIC") + +intercept_matrix <- matrix(NA, 7, 5) +colnames(intercept_matrix) <- c("2.5%", "50%", "97.5%", "model", "WAIC") + +#fitted values +fitted_list <- vector("list", 7) +names(fitted_list) <- predterms_short + +#marginals of hyperparameters +marginals_hyperpar_list_gaussian <- vector("list", 7) +names(marginals_hyperpar_list_gaussian) <- predterms_short + +marginals_hyperpar_list_phy <- vector("list", 7) +names(marginals_hyperpar_list_phy) <- predterms_short + +marginals_hyperpar_list_spa <- vector("list", 7) +names(marginals_hyperpar_list_spa) <- predterms_short + +marginals_hyperpar_list_area <- vector("list", 7) +names(marginals_hyperpar_list_area) <- predterms_short + + +#marginals of fixed effects +marginals_fixed_list_Intercept <- vector("list", 7) +names(marginals_fixed_list_Intercept) <- predterms_short + + +#summary statistics of random effects +summary_random_list_phy <- vector("list", 7) +names(summary_random_list_phy) <- predterms_short + +summary_random_list_spa <- vector("list", 7) +names(summary_random_list_spa) <- predterms_short + +summary_random_list_area <- vector("list", 7) +names(summary_random_list_area) <- predterms_short + +coefm <- matrix(NA,7,1) +result <- vector("list",7) + +for(i in 1:7){ + formula <- as.formula(paste("boundness_st ~ ",predterms[[i]])) + result[[i]] <- inla(formula, family="gaussian", + control.family = list(hyper = pcprior_hyper), + #control.inla = list(tolerance = 1e-8, h = 0.0001), + #tolerance: the tolerance for the optimisation of the hyperparameters + #h: the step-length for the gradient calculations for the hyperparameters. + data=metrics_joined, control.compute=list(waic=TRUE)) + + coefm[i,1] <- round(result[[i]]$waic$waic, 2) + + intercept_matrix[i, 1:3] <- c(result[[i]]$summary.fixed[1,]$`0.025quant`, result[[i]]$summary.fixed[1,]$`0.5quant`, result[[i]]$summary.fixed[1,]$`0.975quant`) + intercept_matrix[i, 4] <- predterms_short[[i]] + intercept_matrix[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_Intercept[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["(Intercept)"]])) + colnames(marginals_fixed_list_Intercept[[i]]) <- c("x for Intercept", "y for Intercept") + + if(i %in% phylogenetic_element) { + phy_effects_matrix[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for phy_id`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + phy_effects_matrix[i, 4] <- predterms_short[[i]] + phy_effects_matrix[i, 5] <- result[[i]]$waic$waic + } + + if(i %in% spatial_element) { + spa_effects_matrix[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for sp_id`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + spa_effects_matrix[i, 4] <- predterms_short[[i]] + spa_effects_matrix[i, 5] <- result[[i]]$waic$waic + } + + if(i %in% areal_element){ + area_effects_matrix[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for AUTOTYP_area`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + area_effects_matrix[i, 4] <- predterms_short[[i]] + area_effects_matrix[i, 5] <- result[[i]]$waic$waic + } + + fitted_list[[i]] <- result[[i]]$summary.fitted.values + fitted_list[[i]] <- fitted_list[[i]] %>% + mutate(across(where(is.numeric), round, 2)) + + marginals_hyperpar_list_gaussian[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for the Gaussian observations"]])) + colnames(marginals_hyperpar_list_gaussian[[i]]) <- c("x for the Gaussian observations", "y for the Gaussian observations") + + if(i %in% phylogenetic_element){ + marginals_hyperpar_list_phy[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for phy_id"]])) + colnames(marginals_hyperpar_list_phy[[i]]) <- c("x for phy_id", "y for phy_id") + } + + if(i %in% spatial_element){ + marginals_hyperpar_list_spa[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for sp_id"]])) + colnames(marginals_hyperpar_list_spa[[i]]) <- c("x for sp_id", "y for sp_id") + } + + if(i %in% areal_element){ + marginals_hyperpar_list_area[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for AUTOTYP_area"]])) + colnames(marginals_hyperpar_list_area[[i]]) <- c("x for AUTOTYP_area", "y for AUTOTYP_area") + } + + if(i %in% phylogenetic_element){ + summary_random_list_phy[[i]] <- cbind(result[[i]]$summary.random$phy_id) %>% + rename(phy_id = ID) %>% + as.data.frame() %>% + mutate(across(where(is.numeric), round, 2)) + } + + if(i %in% spatial_element){ + summary_random_list_spa[[i]] <- cbind(result[[i]]$summary.random$sp_id) %>% + rename(sp_id = ID) %>% + as.data.frame() %>% + mutate(across(where(is.numeric), round, 2)) + } + + if(i %in% areal_element){ + summary_random_list_area[[i]] <- cbind(result[[i]]$summary.random$AUTOTYP_area) %>% + rename(AUTOTYP_area = ID) %>% + as.data.frame() %>% + mutate(across(where(is.numeric), round, 2)) + } +} + +#beepr::beep(5) + +save(result, file = "output_models/models_Boundness_phylogenetic_spatial.RData") + +coefm <- as.data.frame(cbind(predterms_short, coefm)) +colnames(coefm) <- c("model", "WAIC") +coefm <- coefm %>% + mutate(across(.cols=2, as.numeric)) %>% + mutate(across(where(is.numeric), round, 2)) %>% + arrange(WAIC) + +coefm$WAIC <- as.numeric(coefm$WAIC) +coefm <- coefm[order(coefm$WAIC),] + +coefm_path <- paste("output_tables/", "waics", "Boundness_phylogenetic_spatial_models", ".csv", collapse = "") +write.csv(coefm, coefm_path, row.names=FALSE) + +for (i in 1:length(fitted_list)) { + fitted_list[[i]]$model <- names(fitted_list)[i] +} +fitted_list <- dplyr::bind_rows(fitted_list) +fitted_list_path <- paste("output_tables/", "fitted_list", "Boundness_phylogenetic_spatial_models", ".csv", collapse = "") +write.csv(fitted_list, fitted_list_path) + +phy_effects<-as.data.frame(phy_effects_matrix) +spa_effects<-as.data.frame(spa_effects_matrix) +area_effects <- as.data.frame(area_effects_matrix) +intercept_effects <- as.data.frame(intercept_matrix) + +phy_effects$effect <- "phylogenetic SD" +spa_effects$effect <- "spatial SD" +area_effects$effect <- "areal SD" +intercept_effects$effect <- "Intercept" + +effs <- as.data.frame(rbind(phy_effects, spa_effects, area_effects, intercept_effects)) +effs <- effs %>% + mutate(across(.cols=c(1:3, 5), as.numeric)) %>% + mutate(across(where(is.numeric), round, 2)) %>% + na.omit() %>% + arrange(WAIC) %>% + relocate(model) + +effs_path <- paste("output_tables/", "effects", "Boundness_phylogenetic_spatial_models", ".csv", collapse = "") +write.csv(effs, effs_path, row.names=FALSE) + +effs <- read.csv("output_tables/ effects Boundness_phylogenetic_spatial_models .csv") + +effs_table_SM <- effs %>% + mutate(effect = + dplyr::recode(effect, + "areal SD" = "spatial SD")) %>% + rename("2.5%"=2, + "50%" = 4, + "97.5%" = 3) %>% + flextable() %>% + autofit() %>% + merge_v(j=c("model", "WAIC")) %>% + fix_border_issues() %>% + border_inner_h() + +save_as_docx( + "Effects in boundess models with random effects" = effs_table_SM, + path = "output_tables/table_SM_effects_Boundness_phylogenetic_spatial_models.docx") + +effs_plot <- effs %>% + #filter(WAIC <= top_9) %>% + rename(lower=2, + upper = 4, + mean = 3) %>% #mean here refers to 0.5 quantile + #filter(!effect == "Intercept") %>% + mutate(effect = + dplyr::recode(effect, + "areal SD" = "spatial SD")) %>% + mutate(effect = factor(effect, levels=c("phylogenetic SD", "spatial SD", "areal SD", "Intercept"))) %>% + mutate(WAIC = round(WAIC, 2)) %>% + unite("model", model, WAIC, sep = ",\nWAIC: ", remove=FALSE) %>% + group_by(WAIC) %>% + arrange(WAIC) %>% + mutate(model = forcats::fct_reorder(as.factor(model), WAIC)) %>% #reordering levels within model based on WAIC values + mutate(model = factor(model, levels=rev(levels(model)))) #reversing the order + + + +#plot modified from function ggregplot::Efxplot +cols = c(brewer.pal(12, "Paired")) +cols = c(cols[c(12, 10)], "gray50") + +show_col(cols) + +plot_1 <- ggplot(effs_plot, + aes(y = as.factor(model), + x = mean, + group = effect, + colour = effect)) + + geom_pointrangeh(aes(xmin = lower, xmax = upper), position = position_dodge(w = 0.9), size = 1.5) + + geom_vline(aes(xintercept = 0),lty = 2) + labs(x = NULL) + #coord_flip() + + scale_color_manual(values=cols) + + ylab("Model of boundness") + xlab("Estimate") + labs(color = "Effect") + theme_classic() + + theme(axis.text=element_text(size=50), + legend.text=element_text(size=50), + axis.title=element_text(size=50), + legend.title=element_text(size=50), + legend.spacing.y = unit(1.5, 'cm')) + + guides(color = guide_legend(reverse = TRUE, byrow = TRUE)) + + +#plot_1 +ggsave(filename = 'output/SP_models_plot_Boundness_phylogenetic_spatial_models.jpg', + plot_1, height = 29, width = 33) + + +#saving hyperparameters: Gaussian observations +for (i in 1:length(marginals_hyperpar_list_gaussian)) { + marginals_hyperpar_list_gaussian[[i]]$model <- names(marginals_hyperpar_list_gaussian)[i] +} +marginals_hyperpar_list_gaussian <- dplyr::bind_rows(marginals_hyperpar_list_gaussian) + +write.csv(marginals_hyperpar_list_gaussian, "output_tables/Boundness_phylogenetic_spatial_models_marginals_hyperpar_gaussian.csv") + +#saving hyperparameters: phylogenetic +for (i in 1:length(marginals_hyperpar_list_phy)) { + marginals_hyperpar_list_phy[[i]]$model <- names(marginals_hyperpar_list_phy)[i] +} +marginals_hyperpar_list_phy <- dplyr::bind_rows(marginals_hyperpar_list_phy) + +write.csv(marginals_hyperpar_list_phy, "output_tables/Boundness_phylogenetic_spatial_models_marginals_hyperpar_phylogenetic.csv") + +#saving hyperparameters: spatial +for (i in 1:length(marginals_hyperpar_list_spa)) { + marginals_hyperpar_list_spa[[i]]$model <- names(marginals_hyperpar_list_spa)[i] +} +marginals_hyperpar_list_spa <- dplyr::bind_rows(marginals_hyperpar_list_spa) + +write.csv(marginals_hyperpar_list_spa, "output_tables/Boundness_phylogenetic_spatial_models_marginals_hyperpar_spatial.csv") + +#saving hyperparameters: areas +for (i in 1:length(marginals_hyperpar_list_area)) { + marginals_hyperpar_list_area[[i]]$model <- names(marginals_hyperpar_list_area)[i] +} +marginals_hyperpar_list_area <- dplyr::bind_rows(marginals_hyperpar_list_area) + +write.csv(marginals_hyperpar_list_area, "output_tables/Boundness_phylogenetic_spatial_models_marginals_hyperpar_areal.csv") + + +#saving summaries of random effects: phylogenetic +for (i in 1:length(summary_random_list_phy)) { + summary_random_list_phy[[i]]$model <- names(summary_random_list_phy)[i] +} +summary_random_list_phy <- dplyr::bind_rows(summary_random_list_phy) + +write.csv(summary_random_list_phy, "output_tables/Boundness_phylogenetic_spatial_models_summary_random_phy.csv") + +#saving summaries of random effects: spatial +for (i in 1:length(summary_random_list_spa)) { + summary_random_list_spa[[i]]$model <- names(summary_random_list_spa)[i] +} +summary_random_list_spa <- dplyr::bind_rows(summary_random_list_spa) + +write.csv(summary_random_list_spa, "output_tables/Boundness_phylogenetic_spatial_models_summary_random_spa.csv") + +#saving summaries of random effects: areas +for (i in 1:length(summary_random_list_area)) { + summary_random_list_area[[i]]$model <- names(summary_random_list_area)[i] +} +summary_random_list_area <- dplyr::bind_rows(summary_random_list_area) + +write.csv(summary_random_list_area, "output_tables/Boundness_phylogenetic_spatial_models_summary_random_areas.csv") diff --git a/101/replication_package/models_Boundness_reduced_social.R b/101/replication_package/models_Boundness_reduced_social.R new file mode 100644 index 0000000000000000000000000000000000000000..f7770413f35614b6beaf7aeb65ae340b9b4c2a26 --- /dev/null +++ b/101/replication_package/models_Boundness_reduced_social.R @@ -0,0 +1,567 @@ +#model fitting: Boundness predicted by social effects on top of random phylogenetic and spatial factors + +#Script was written by Sam Passmore and modified by Olena Shcherbakova + +source("requirements.R") + +source("install_and_load_INLA.R") + +source("set_up_inla.R") + +metrics_joined <- metrics_joined %>% + filter(!is.na(L1_log10_st)) %>% + rename(L1_log_st = L1_log10_st) %>% + mutate(L1_copy = L1_log_st) %>% + filter(!is.na(L2_prop)) %>% + mutate(L2_copy = L2_prop) %>% + filter(!is.na(neighboring_languages_st)) %>% + filter(!is.na(Official)) %>% + filter(!is.na(Education)) %>% + filter(!is.na(boundness_st)) %>% + filter(!is.na(informativity_st)) + +#dropping tips not in Grambank +metrics_joined <- metrics_joined[metrics_joined$Language_ID %in% tree$tip.label, ] +tree <- keep.tip(tree, metrics_joined$Language_ID) + +x <- assert_that(all(tree$tip.label %in% metrics_joined$Language_ID), msg = "The data and phylogeny taxa do not match") + +## Building standardized phylogenetic precision matrix +tree_scaled <- tree + +tree_vcv = vcv.phylo(tree_scaled) +typical_phylogenetic_variance = exp(mean(log(diag(tree_vcv)))) + +#We opt for a sparse phylogenetic precision matrix (i.e. it is quantified using all nodes and tips), since sparse matrices make the analysis in INLA less time-intensive +tree_scaled$edge.length <- tree_scaled$edge.length/typical_phylogenetic_variance +phylo_prec_mat <- MCMCglmm::inverseA(tree_scaled, + nodes = "ALL", + scale = FALSE)$Ainv + +metrics_joined = metrics_joined[order(match(metrics_joined$Language_ID, rownames(phylo_prec_mat))),] + +#"local" set of parameters +## Create spatial covariance matrix using the matern covariance function +spatial_covar_mat_1 = varcov.spatial(metrics_joined[,c("Longitude", "Latitude")], + cov.pars = phi_1, kappa = kappa)$varcov +# Calculate and standardize by the typical variance +typical_variance_spatial_1 = exp(mean(log(diag(spatial_covar_mat_1)))) +spatial_cov_std_1 = spatial_covar_mat_1 / typical_variance_spatial_1 +spatial_prec_mat_1 = solve(spatial_cov_std_1) +dimnames(spatial_prec_mat_1) = list(metrics_joined$Language_ID, metrics_joined$Language_ID) + +## Since we are using a sparse phylogenetic matrix, we are matching taxa to rows in the matrix +phy_id = match(tree$tip.label, rownames(phylo_prec_mat)) +metrics_joined$phy_id = phy_id + +## Other effects are in the same order they appear in the dataset +metrics_joined$sp_id = 1:nrow(spatial_prec_mat_1) + +#Preparing the formulas for 10 competing models to be used in inla() call +listcombo <- list( + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper)", "L1_log_st"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper)", "f(inla.group(L1_copy), model='rw2', scale.model = TRUE)"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper)", "L2_prop"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper)", "f(inla.group(L2_copy), model='rw2', scale.model = TRUE)"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper)", "f(inla.group(L1_copy), model='rw2', scale.model = TRUE)", "f(inla.group(L2_copy), model='rw2', scale.model = TRUE)"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper)", "L1_log_st", "L2_prop"), + + #unavailable + # c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper)", "L1_log10:L2_prop"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper)", "neighboring_languages_st"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper)", "Official"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper)", "Education")) + + +predterms <- lapply(listcombo, function(x) paste(x, collapse="+")) + +predterms <- t(as.data.frame(predterms)) + +predterms_short <- predterms + +predterms_short <- gsub("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper)", "Phylogenetic", predterms_short, fixed=TRUE) +predterms_short <- gsub("f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper)", "Spatial: local", predterms_short, fixed=TRUE) + +predterms_short <- gsub("f(inla.group(L1_copy), model='rw2', scale.model = TRUE)", "L1 speakers (nonlinear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("L1_log_st", "L1 speakers (linear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("f(inla.group(L2_copy), model='rw2', scale.model = TRUE)", "L2 proportion (nonlinear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("L2_prop", "L2 proportion (linear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("neighboring_languages_st", "Neighbours", predterms_short, fixed=TRUE) + + + +phylogenetic_element <- data.frame("judgement" = grepl("Phylogenetic", predterms_short), + number = 1:length(predterms_short)) +phylogenetic_element <- phylogenetic_element[phylogenetic_element$judgement == TRUE,]$number + +spatial_element_local <- data.frame("judgement" = grepl("local", predterms_short), + number = 1:length(predterms_short)) +spatial_element_local <- spatial_element_local[spatial_element_local$judgement == TRUE,]$number + +spatial_element_regional <- data.frame("judgement" = grepl("regional", predterms_short), + number = 1:length(predterms_short)) +spatial_element_regional <- spatial_element_regional[spatial_element_regional$judgement == TRUE,]$number + +spatial_element <- c(spatial_element_local, spatial_element_regional) + +L1_element <- data.frame("judgement" = grepl("L1 speakers (linear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L1_element <- L1_element[L1_element$judgement == TRUE,]$number + + +L1_nl_element <- data.frame("judgement" = grepl("L1 speakers (nonlinear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L1_nl_element <- L1_nl_element[L1_nl_element$judgement == TRUE,]$number + +L2_prop_element <- data.frame("judgement" = grepl("L2 proportion (linear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L2_prop_element <- L2_prop_element[L2_prop_element$judgement == TRUE,]$number +#unnecessary +#L2_prop_element <- L2_prop_element[-length(L2_prop_element)] #making sure that the interaction term (introduced below) is not treated as belonging to this isolated element + +L2_prop_nl_element <- data.frame("judgement" = grepl("L2 proportion (nonlinear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L2_prop_nl_element <- L2_prop_nl_element[L2_prop_nl_element$judgement == TRUE,]$number + +#unnecessary +#can use only part of the interaction term within grepl() function +# interaction_element <- data.frame("judgement" = grepl(":L2 proportion", predterms_short), +# number = 1:length(predterms_short)) +# interaction_element <- interaction_element[interaction_element$judgement == TRUE,]$number + +neighbour_element <- data.frame("judgement" = grepl("Neighbours", predterms_short), + number = 1:length(predterms_short)) +neighbour_element <- neighbour_element[neighbour_element$judgement == TRUE,]$number + +official_element <- data.frame("judgement" = grepl("Official", predterms_short), + number = 1:length(predterms_short)) +official_element <- official_element[official_element$judgement == TRUE,]$number + +education_element <- data.frame("judgement" = grepl("Education", predterms_short), + number = 1:length(predterms_short)) +education_element <- education_element[education_element$judgement == TRUE,]$number + +models_number <- length(predterms_short) + +#preparing empty matrices to be filled with effect estimates (quantiles), model name, and WAIC value +phy_effects_matrix <- matrix(NA, models_number, 5) +colnames(phy_effects_matrix) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +spa_effects_matrix <- matrix(NA, models_number, 5) +colnames(spa_effects_matrix) <- c("2.5%", "50%", "97.5%", "model", "WAIC") + +intercept_matrix <- matrix(NA, models_number, 5) +colnames(intercept_matrix) <- c("2.5%", "50%", "97.5%", "model", "WAIC") + +social_effects_matrix_L1 <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_L1) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L1_nl <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_L1_nl) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L2_prop <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_L2_prop) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L2_prop_nl <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_L2_prop_nl) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_N <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_N) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_O <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_O) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_E <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_E) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L1_L2_prop <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_L1_L2_prop) <- c("2.5%", "50%", "97.5%", "model", "WAIC") + +#fitted values +fitted_list <- vector("list", models_number) +names(fitted_list) <- predterms_short + +#marginals of hyperparameters +marginals_hyperpar_list_gaussian <- vector("list", models_number) +names(marginals_hyperpar_list_gaussian) <- predterms_short + +marginals_hyperpar_list_phy <- vector("list", models_number) +names(marginals_hyperpar_list_phy) <- predterms_short + +marginals_hyperpar_list_spa <- vector("list", models_number) +names(marginals_hyperpar_list_spa) <- predterms_short + +marginals_hyperpar_list_social_L1_nl <- vector("list", models_number) +names(marginals_hyperpar_list_social_L1_nl) <- predterms_short + +marginals_hyperpar_list_social_L2_prop_nl <- vector("list", models_number) +names(marginals_hyperpar_list_social_L2_prop_nl) <- predterms_short + + +#marginals of fixed effects +marginals_fixed_list_Intercept <- vector("list", models_number) +names(marginals_fixed_list_Intercept) <- predterms_short + +marginals_fixed_list_L1 <- vector("list", models_number) +names(marginals_fixed_list_L1) <- predterms_short + +marginals_fixed_list_L2_prop <- vector("list", models_number) +names(marginals_fixed_list_L2_prop) <- predterms_short + +marginals_fixed_list_O <- vector("list", models_number) +names(marginals_fixed_list_O) <- predterms_short + +marginals_fixed_list_N <- vector("list", models_number) +names(marginals_fixed_list_N) <- predterms_short + +marginals_fixed_list_E <- vector("list", models_number) +names(marginals_fixed_list_E) <- predterms_short + +marginals_fixed_list_L1_L2_prop <- vector("list", models_number) +names(marginals_fixed_list_L1_L2_prop) <- predterms_short + + + + +#summary statistics of random effects +summary_random_list_phy <- vector("list", models_number) +names(summary_random_list_phy) <- predterms_short + +summary_random_list_spa <- vector("list", models_number) +names(summary_random_list_spa) <- predterms_short + +summary_random_list_social_L1_nl <- vector("list", models_number) +names(summary_random_list_social_L1_nl) <- predterms_short + +summary_random_list_social_L2_prop_nl <- vector("list", models_number) +names(summary_random_list_social_L2_prop_nl) <- predterms_short + + +coefm <- matrix(NA,models_number,1) +result <- vector("list",models_number) + +for(i in 1:models_number){ + formula <- as.formula(paste("boundness_st ~ ",predterms[[i]])) + result[[i]] <- inla(formula, family="gaussian", + control.family = list(hyper = pcprior_hyper), + #control.inla = list(tolerance = 1e-8, h = 0.0001), + #tolerance: the tolerance for the optimisation of the hyperparameters + #h: the step-length for the gradient calculations for the hyperparameters. + data=metrics_joined, control.compute=list(waic=TRUE)) + + coefm[i,1] <- round(result[[i]]$waic$waic, 2) + + intercept_matrix[i, 1:3] <- c(result[[i]]$summary.fixed[1,]$`0.025quant`, result[[i]]$summary.fixed[1,]$`0.5quant`, result[[i]]$summary.fixed[1,]$`0.975quant`) + intercept_matrix[i, 4] <- predterms_short[[i]] + intercept_matrix[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_Intercept[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["(Intercept)"]])) + colnames(marginals_fixed_list_Intercept[[i]]) <- c("x for Intercept", "y for Intercept") + + if(i %in% phylogenetic_element) { + phy_effects_matrix[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for phy_id`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + phy_effects_matrix[i, 4] <- predterms_short[[i]] + phy_effects_matrix[i, 5] <- result[[i]]$waic$waic + } + + if(i %in% spatial_element) { + spa_effects_matrix[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for sp_id`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + spa_effects_matrix[i, 4] <- predterms_short[[i]] + spa_effects_matrix[i, 5] <- result[[i]]$waic$waic + } + + + if(i %in% L1_nl_element){ + social_effects_matrix_L1_nl[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for inla.group(L1_copy)`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + social_effects_matrix_L1_nl[i, 4] <- predterms_short[[i]] + social_effects_matrix_L1_nl[i, 5] <- result[[i]]$waic$waic + } + + if(i %in% L2_prop_nl_element){ + social_effects_matrix_L2_prop_nl[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for inla.group(L2_copy)`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + social_effects_matrix_L2_prop_nl[i, 4] <- predterms_short[[i]] + social_effects_matrix_L2_prop_nl[i, 5] <- result[[i]]$waic$waic + } + + if(i %in% L1_element) { + social_effects_matrix_L1[i, 1:3] <- c(result[[i]]$summary.fixed["L1_log_st",]$`0.025quant`, result[[i]]$summary.fixed["L1_log_st",]$`0.5quant`, result[[i]]$summary.fixed["L1_log_st",]$`0.975quant`) + social_effects_matrix_L1[i, 4] <- predterms_short[[i]] + social_effects_matrix_L1[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_L1[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["L1_log_st"]])) + colnames(marginals_fixed_list_L1[[i]]) <- c("x for L1", "y for L1") + } + + if(i %in% L2_prop_element) { + social_effects_matrix_L2_prop[i, 1:3] <- c(result[[i]]$summary.fixed["L2_prop",]$`0.025quant`, result[[i]]$summary.fixed["L2_prop",]$`0.5quant`, result[[i]]$summary.fixed["L2_prop",]$`0.975quant`) + social_effects_matrix_L2_prop[i, 4] <- predterms_short[[i]] + social_effects_matrix_L2_prop[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_L2_prop[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["L2_prop"]])) + colnames(marginals_fixed_list_L2_prop[[i]]) <- c("x for L2 proportion", "y for L2 proportion") + } + +#unavailable + # if(i %in% interaction_element) { + # social_effects_matrix_L1_L2_prop[i, 1:3] <- c(result[[i]]$summary.fixed["L1_log10:L2_prop",]$`0.025quant`, result[[i]]$summary.fixed["L1_log10:L2_prop",]$`0.5quant`, result[[i]]$summary.fixed["L1_log10:L2_prop",]$`0.975quant`) + # social_effects_matrix_L1_L2_prop[i, 4] <- predterms_short[[i]] + # social_effects_matrix_L1_L2_prop[i, 5] <- result[[i]]$waic$waic + + # marginals_fixed_list_L1_L2_prop[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["L1_log10:L2_prop"]])) + # colnames(marginals_fixed_list_L1_L2_prop[[i]]) <- c("x for L1*L2 proportion", "y for L1*L2 proportion") + # } + + if(i %in% neighbour_element) { + social_effects_matrix_N[i, 1:3] <- c(result[[i]]$summary.fixed[2,]$`0.025quant`, result[[i]]$summary.fixed[2,]$`0.5quant`, result[[i]]$summary.fixed[2,]$`0.975quant`) + social_effects_matrix_N[i, 4] <- predterms_short[[i]] + social_effects_matrix_N[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_N[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][[2]])) + colnames(marginals_fixed_list_N[[i]]) <- c("x for Neighbours", "y for Neighbours") + } + + if(i %in% official_element) { + social_effects_matrix_O[i, 1:3] <- c(result[[i]]$summary.fixed[2,]$`0.025quant`, result[[i]]$summary.fixed[2,]$`0.5quant`, result[[i]]$summary.fixed[2,]$`0.975quant`) + social_effects_matrix_O[i, 4] <- predterms_short[[i]] + social_effects_matrix_O[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_O[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][[2]])) + colnames(marginals_fixed_list_O[[i]]) <- c("x for Official", "y for Official") + } + + if(i %in% education_element) { + social_effects_matrix_E[i, 1:3] <- c(result[[i]]$summary.fixed[2,]$`0.025quant`, result[[i]]$summary.fixed[2,]$`0.5quant`, result[[i]]$summary.fixed[2,]$`0.975quant`) + social_effects_matrix_E[i, 4] <- predterms_short[[i]] + social_effects_matrix_E[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_E[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][[2]])) + colnames(marginals_fixed_list_E[[i]]) <- c("x for Education", "y for Education") + } + + fitted_list[[i]] <- result[[i]]$summary.fitted.values + fitted_list[[i]] <- fitted_list[[i]] %>% + mutate(across(where(is.numeric), round, 2)) + + marginals_hyperpar_list_gaussian[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for the Gaussian observations"]])) + colnames(marginals_hyperpar_list_gaussian[[i]]) <- c("x for the Gaussian observations", "y for the Gaussian observations") + + if(i %in% phylogenetic_element){ + marginals_hyperpar_list_phy[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for phy_id"]])) + colnames(marginals_hyperpar_list_phy[[i]]) <- c("x for phy_id", "y for phy_id") + } + + if(i %in% spatial_element){ + marginals_hyperpar_list_spa[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for sp_id"]])) + colnames(marginals_hyperpar_list_spa[[i]]) <- c("x for sp_id", "y for sp_id") + } + + if(i %in% L1_nl_element){ + marginals_hyperpar_list_social_L1_nl[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for inla.group(L1_copy)"]])) + colnames(marginals_hyperpar_list_social_L1_nl[[i]]) <- c("x for inla.group(L1_copy)", "y for inla.group(L1_copy)") + } + + if(i %in% L2_prop_nl_element){ + marginals_hyperpar_list_social_L2_prop_nl[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for inla.group(L2_copy)"]])) + colnames(marginals_hyperpar_list_social_L2_prop_nl[[i]]) <- c("x for inla.group(L2_copy)", "y for inla.group(L2_copy)") + } + + if(i %in% phylogenetic_element){ + summary_random_list_phy[[i]] <- cbind(result[[i]]$summary.random$phy_id) %>% + rename(phy_id = ID) %>% + as.data.frame() %>% + mutate(across(where(is.numeric), round, 2)) + } + + if(i %in% spatial_element){ + summary_random_list_spa[[i]] <- cbind(result[[i]]$summary.random$sp_id) %>% + rename(sp_id = ID) %>% + as.data.frame() %>% + mutate(across(where(is.numeric), round, 2)) + } +} + +#beepr::beep(5) + +save(result, file = "output_models_reduced/models_Boundness_social.RData") +load("output_models_reduced/models_Boundness_social.RData") + +coefm_copy <- coefm + +coefm <- as.data.frame(cbind(predterms_short, coefm)) +colnames(coefm) <- c("model", "WAIC") +coefm <- coefm %>% + mutate(across(.cols=2, as.numeric)) %>% + mutate(across(where(is.numeric), round, 2)) %>% + arrange(WAIC) + +coefm$WAIC <- as.numeric(coefm$WAIC) +coefm <- coefm[order(coefm$WAIC),] + +coefm_path <- paste("output_tables_reduced/", "waics", "Boundness_social_models", ".csv", collapse = "") +write.csv(coefm, coefm_path, row.names=FALSE) + +for (i in 1:length(fitted_list)) { + fitted_list[[i]]$model <- names(fitted_list)[i] +} +fitted_list <- dplyr::bind_rows(fitted_list) +fitted_list_path <- paste("output_tables_reduced/", "fitted_list", "Boundness_social_models", ".csv", collapse = "") +write.csv(fitted_list, fitted_list_path) + + +phy_effects<-as.data.frame(phy_effects_matrix) +spa_effects<-as.data.frame(spa_effects_matrix) +intercept_effects <- as.data.frame(intercept_matrix) +L1_effects <- as.data.frame(social_effects_matrix_L1) +L1_nl_effects <- as.data.frame(social_effects_matrix_L1_nl) +L2_prop_effects <- as.data.frame(social_effects_matrix_L2_prop) +L2_prop_nl_effects <- as.data.frame(social_effects_matrix_L2_prop_nl) +N_effects<-as.data.frame(social_effects_matrix_N) +E_effects<-as.data.frame(social_effects_matrix_E) +O_effects<-as.data.frame(social_effects_matrix_O) +#unavailable +#interaction_effects <- as.data.frame(social_effects_matrix_L1_L2_prop) + +phy_effects$effect <- "phylogenetic SD" +spa_effects$effect <- "spatial SD" +intercept_effects$effect <- "Intercept" +L1_effects$effect <- "L1" +L1_nl_effects$effect <- "social SD:\nL1" +L2_prop_effects$effect <- "L2 proportion" +L2_prop_nl_effects$effect <- "social SD:\nL2 proportion" +N_effects$effect <- "Neighbours" +E_effects$effect <- "Education" +O_effects$effect <- "Official status" +#unavailable +#interaction_effects$effect <- "L1*L2 proportion" + +effs <- as.data.frame(rbind(phy_effects, spa_effects, intercept_effects, L1_effects, L1_nl_effects, L2_prop_effects, L2_prop_nl_effects, N_effects, O_effects, E_effects))#unavailable: , interaction_effects)) +effs <- effs %>% + mutate(across(.cols=c(1:3, 5), as.numeric)) %>% + mutate(across(where(is.numeric), round, 2)) %>% + na.omit() %>% + arrange(WAIC) %>% + relocate(model) + +effs_path <- paste("output_tables_reduced/", "effects", "Boundness_social_models", ".csv", collapse = "") +write.csv(effs, effs_path, row.names=FALSE) + +effs <- read.csv("output_tables_reduced/ effects Boundness_social_models .csv") + +effs_table_Main <- effs %>% + rename("2.5%"=2, + "50%" = 3, + "97.5%" = 4) %>% + filter(!grepl("nonlinear", model)) + +effs_table_Main$model <- gsub("(\\s*\\(\\w+\\))", "", effs_table_Main$model) + +effs_table_Main <- effs_table_Main %>% + relocate(effect, .after = model) %>% + flextable() %>% + flextable::bold(~ (`2.5%` > 0 & `97.5%` > 0) | (`2.5%` < 0 & `97.5%` < 0), 2) %>% + autofit() %>% + merge_v(j=c("model", "WAIC")) %>% + fix_border_issues() %>% + border_inner_h() + +save_as_docx( + "Effects in boundness models with fixed and random effects" = effs_table_Main, + path = "output_tables_reduced/table_Main_effects_Boundness_social_models.docx") + + +effs_plot <- effs %>% + #filter(WAIC <= top_9) %>% + rename(lower=2, + upper = 4, + mean = 3) %>% #mean here refers to 0.5 quantile + #filter(!effect == "Intercept") %>% + mutate(effect = factor(effect, levels=c("phylogenetic SD", "spatial SD", "Intercept", "social SD:\nL1", "L1", "social SD:\nL2 proportion", "L2 proportion", "Neighbours", "Education", "Official status"))) %>% #unavailable, "L1*L2 proportion"))) %>% + mutate(WAIC = round(WAIC, 2)) %>% + unite("model", model, WAIC, sep = ",\nWAIC: ", remove=FALSE) %>% + group_by(WAIC) %>% + arrange(WAIC) %>% + mutate(model = forcats::fct_reorder(as.factor(model), WAIC)) %>% #reordering levels within model based on WAIC values + mutate(model = factor(model, levels=rev(levels(model)))) #reversing the order + + + +#plot modified from function ggregplot::Efxplot +cols = c(brewer.pal(12, "Paired")) +cols = c(cols[c(12, 10)], "gray50", cols[c(1:8)]) + +show_col(cols) + +plot_1 <- ggplot(effs_plot, + aes(y = as.factor(model), + x = mean, + group = effect, + colour = effect)) + + geom_pointrangeh(aes(xmin = lower, xmax = upper), position = position_dodge(w = 0.9), size = 1.5) + + geom_vline(aes(xintercept = 0),lty = 2) + labs(x = NULL) + #coord_flip() + + scale_color_manual(values=cols) + + ylab("Model of boundness") + xlab("Estimate") + labs(color = "Effect") + theme_classic() + + theme(axis.text=element_text(size=50), + legend.text=element_text(size=50), + axis.title=element_text(size=50), + legend.title=element_text(size=50), + legend.spacing.y = unit(1.5, 'cm')) + + guides(color = guide_legend(reverse = TRUE, byrow = TRUE)) + + +#plot_1 +ggsave(filename = 'output_reduced/SP_models_plot_Boundness_social_models.jpg', + plot_1, height = 20, width = 45) + + +#saving hyperparameters: Gaussian observations +for (i in 1:length(marginals_hyperpar_list_gaussian)) { + marginals_hyperpar_list_gaussian[[i]]$model <- names(marginals_hyperpar_list_gaussian)[i] +} +marginals_hyperpar_list_gaussian <- dplyr::bind_rows(marginals_hyperpar_list_gaussian) + +write.csv(marginals_hyperpar_list_gaussian, "output_tables_reduced/Boundness_social_models_marginals_hyperpar_gaussian.csv") + +#saving hyperparameters: phylogenetic +for (i in 1:length(marginals_hyperpar_list_phy)) { + marginals_hyperpar_list_phy[[i]]$model <- names(marginals_hyperpar_list_phy)[i] +} +marginals_hyperpar_list_phy <- dplyr::bind_rows(marginals_hyperpar_list_phy) + +write.csv(marginals_hyperpar_list_phy, "output_tables_reduced/Boundness_social_models_marginals_hyperpar_phylogenetic.csv") + +#saving hyperparameters: spatial +for (i in 1:length(marginals_hyperpar_list_spa)) { + marginals_hyperpar_list_spa[[i]]$model <- names(marginals_hyperpar_list_spa)[i] +} +marginals_hyperpar_list_spa <- dplyr::bind_rows(marginals_hyperpar_list_spa) + +write.csv(marginals_hyperpar_list_spa, "output_tables_reduced/Boundness_social_models_marginals_hyperpar_spatial.csv") + + +#saving summaries of random effects: phylogenetic +for (i in 1:length(summary_random_list_phy)) { + summary_random_list_phy[[i]]$model <- names(summary_random_list_phy)[i] +} +summary_random_list_phy <- dplyr::bind_rows(summary_random_list_phy) + +write.csv(summary_random_list_phy, "output_tables_reduced/Boundness_social_models_summary_random_phy.csv") + +#saving summaries of random effects: spatial +for (i in 1:length(summary_random_list_spa)) { + summary_random_list_spa[[i]]$model <- names(summary_random_list_spa)[i] +} +summary_random_list_spa <- dplyr::bind_rows(summary_random_list_spa) + +write.csv(summary_random_list_spa, "output_tables_reduced/Boundness_social_models_summary_random_spa.csv") diff --git a/101/replication_package/models_Boundness_reduced_social_only.R b/101/replication_package/models_Boundness_reduced_social_only.R new file mode 100644 index 0000000000000000000000000000000000000000..27884257189af1f6012a1024a147ab2af6dbffdf --- /dev/null +++ b/101/replication_package/models_Boundness_reduced_social_only.R @@ -0,0 +1,433 @@ +#model fitting: Boundness predicted by social effects on top of random phylogenetic and spatial factors + +#Script was written by Sam Passmore and modified by Olena Shcherbakova + +source("requirements.R") + +source("install_and_load_INLA.R") + +source("set_up_inla.R") + +metrics_joined <- metrics_joined %>% + filter(!is.na(L1_log10_st)) %>% + rename(L1_log_st = L1_log10_st) %>% + mutate(L1_copy = L1_log_st) %>% + filter(!is.na(L2_prop)) %>% + mutate(L2_copy = L2_prop) %>% + filter(!is.na(neighboring_languages_st)) %>% + filter(!is.na(Official)) %>% + filter(!is.na(Education)) %>% + filter(!is.na(boundness_st)) %>% + filter(!is.na(informativity_st)) + +#dropping tips not in Grambank +metrics_joined <- metrics_joined[metrics_joined$Language_ID %in% tree$tip.label, ] +tree <- keep.tip(tree, metrics_joined$Language_ID) + +x <- assert_that(all(tree$tip.label %in% metrics_joined$Language_ID), msg = "The data and phylogeny taxa do not match") + +## Building standardized phylogenetic precision matrix +tree_scaled <- tree + +tree_vcv = vcv.phylo(tree_scaled) +typical_phylogenetic_variance = exp(mean(log(diag(tree_vcv)))) + +#We opt for a sparse phylogenetic precision matrix (i.e. it is quantified using all nodes and tips), since sparse matrices make the analysis in INLA less time-intensive +tree_scaled$edge.length <- tree_scaled$edge.length/typical_phylogenetic_variance +phylo_prec_mat <- MCMCglmm::inverseA(tree_scaled, + nodes = "ALL", + scale = FALSE)$Ainv + +metrics_joined = metrics_joined[order(match(metrics_joined$Language_ID, rownames(phylo_prec_mat))),] + +#"local" set of parameters +## Create spatial covariance matrix using the matern covariance function +spatial_covar_mat_1 = varcov.spatial(metrics_joined[,c("Longitude", "Latitude")], + cov.pars = phi_1, kappa = kappa)$varcov +# Calculate and standardize by the typical variance +typical_variance_spatial_1 = exp(mean(log(diag(spatial_covar_mat_1)))) +spatial_cov_std_1 = spatial_covar_mat_1 / typical_variance_spatial_1 +spatial_prec_mat_1 = solve(spatial_cov_std_1) +dimnames(spatial_prec_mat_1) = list(metrics_joined$Language_ID, metrics_joined$Language_ID) + +## Since we are using a sparse phylogenetic matrix, we are matching taxa to rows in the matrix +phy_id = match(tree$tip.label, rownames(phylo_prec_mat)) +metrics_joined$phy_id = phy_id + +## Other effects are in the same order they appear in the dataset +metrics_joined$sp_id = 1:nrow(spatial_prec_mat_1) + +#Preparing the formulas for 10 competing models to be used in inla() call +listcombo <- list( + c("L1_log_st"), + + c("f(inla.group(L1_copy), model='rw2', scale.model = TRUE)"), + + c("L2_prop"), + + c("f(inla.group(L2_copy), model='rw2', scale.model = TRUE)"), + + c("f(inla.group(L1_copy), model='rw2', scale.model = TRUE)", "f(inla.group(L2_copy), model='rw2', scale.model = TRUE)"), + + c("L1_log_st", "L2_prop"), + + c("neighboring_languages_st"), + + c("Official"), + + c("Education")) + + +predterms <- lapply(listcombo, function(x) paste(x, collapse="+")) + +predterms <- t(as.data.frame(predterms)) + +predterms_short <- predterms + +predterms_short <- gsub("f(inla.group(L1_copy), model='rw2', scale.model = TRUE)", "L1 speakers (nonlinear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("L1_log_st", "L1 speakers (linear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("f(inla.group(L2_copy), model='rw2', scale.model = TRUE)", "L2 proportion (nonlinear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("L2_prop", "L2 proportion (linear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("neighboring_languages_st", "Neighbours", predterms_short, fixed=TRUE) + +L1_element <- data.frame("judgement" = grepl("L1 speakers (linear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L1_element <- L1_element[L1_element$judgement == TRUE,]$number + + +L1_nl_element <- data.frame("judgement" = grepl("L1 speakers (nonlinear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L1_nl_element <- L1_nl_element[L1_nl_element$judgement == TRUE,]$number + +L2_prop_element <- data.frame("judgement" = grepl("L2 proportion (linear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L2_prop_element <- L2_prop_element[L2_prop_element$judgement == TRUE,]$number + +L2_prop_nl_element <- data.frame("judgement" = grepl("L2 proportion (nonlinear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L2_prop_nl_element <- L2_prop_nl_element[L2_prop_nl_element$judgement == TRUE,]$number + +neighbour_element <- data.frame("judgement" = grepl("Neighbours", predterms_short), + number = 1:length(predterms_short)) +neighbour_element <- neighbour_element[neighbour_element$judgement == TRUE,]$number + +official_element <- data.frame("judgement" = grepl("Official", predterms_short), + number = 1:length(predterms_short)) +official_element <- official_element[official_element$judgement == TRUE,]$number + +education_element <- data.frame("judgement" = grepl("Education", predterms_short), + number = 1:length(predterms_short)) +education_element <- education_element[education_element$judgement == TRUE,]$number + +models_number <- length(predterms_short) + +#preparing empty matrices to be filled with effect estimates (quantiles), model name, and WAIC value +intercept_matrix <- matrix(NA, models_number, 5) +colnames(intercept_matrix) <- c("2.5%", "50%", "97.5%", "model", "WAIC") + +social_effects_matrix_L1 <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_L1) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L1_nl <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_L1_nl) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L2_prop <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_L2_prop) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L2_prop_nl <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_L2_prop_nl) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_N <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_N) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_O <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_O) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_E <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_E) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L1_L2_prop <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_L1_L2_prop) <- c("2.5%", "50%", "97.5%", "model", "WAIC") + +#fitted values +fitted_list <- vector("list", models_number) +names(fitted_list) <- predterms_short + +#marginals of hyperparameters +marginals_hyperpar_list_gaussian <- vector("list", models_number) +names(marginals_hyperpar_list_gaussian) <- predterms_short + +marginals_hyperpar_list_social_L1_nl <- vector("list", models_number) +names(marginals_hyperpar_list_social_L1_nl) <- predterms_short + +marginals_hyperpar_list_social_L2_prop_nl <- vector("list", models_number) +names(marginals_hyperpar_list_social_L2_prop_nl) <- predterms_short + + +#marginals of fixed effects +marginals_fixed_list_Intercept <- vector("list", models_number) +names(marginals_fixed_list_Intercept) <- predterms_short + +marginals_fixed_list_L1 <- vector("list", models_number) +names(marginals_fixed_list_L1) <- predterms_short + +marginals_fixed_list_L2_prop <- vector("list", models_number) +names(marginals_fixed_list_L2_prop) <- predterms_short + +marginals_fixed_list_O <- vector("list", models_number) +names(marginals_fixed_list_O) <- predterms_short + +marginals_fixed_list_N <- vector("list", models_number) +names(marginals_fixed_list_N) <- predterms_short + +marginals_fixed_list_E <- vector("list", models_number) +names(marginals_fixed_list_E) <- predterms_short + +marginals_fixed_list_L1_L2_prop <- vector("list", models_number) +names(marginals_fixed_list_L1_L2_prop) <- predterms_short + + +#summary statistics of random effects +summary_random_list_social_L1_nl <- vector("list", models_number) +names(summary_random_list_social_L1_nl) <- predterms_short + +summary_random_list_social_L2_prop_nl <- vector("list", models_number) +names(summary_random_list_social_L2_prop_nl) <- predterms_short + + +coefm <- matrix(NA,models_number,1) +result <- vector("list",models_number) + +for(i in 1:models_number){ + formula <- as.formula(paste("boundness_st ~ ",predterms[[i]])) + result[[i]] <- inla(formula, family="gaussian", + control.family = list(hyper = pcprior_hyper), + #control.inla = list(tolerance = 1e-8, h = 0.0001), + #tolerance: the tolerance for the optimisation of the hyperparameters + #h: the step-length for the gradient calculations for the hyperparameters. + data=metrics_joined, control.compute=list(waic=TRUE)) + + coefm[i,1] <- round(result[[i]]$waic$waic, 2) + + intercept_matrix[i, 1:3] <- c(result[[i]]$summary.fixed[1,]$`0.025quant`, result[[i]]$summary.fixed[1,]$`0.5quant`, result[[i]]$summary.fixed[1,]$`0.975quant`) + intercept_matrix[i, 4] <- predterms_short[[i]] + intercept_matrix[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_Intercept[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["(Intercept)"]])) + colnames(marginals_fixed_list_Intercept[[i]]) <- c("x for Intercept", "y for Intercept") + + if(i %in% L1_nl_element){ + social_effects_matrix_L1_nl[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for inla.group(L1_copy)`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + social_effects_matrix_L1_nl[i, 4] <- predterms_short[[i]] + social_effects_matrix_L1_nl[i, 5] <- result[[i]]$waic$waic + } + + if(i %in% L2_prop_nl_element){ + social_effects_matrix_L2_prop_nl[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for inla.group(L2_copy)`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + social_effects_matrix_L2_prop_nl[i, 4] <- predterms_short[[i]] + social_effects_matrix_L2_prop_nl[i, 5] <- result[[i]]$waic$waic + } + + if(i %in% L1_element) { + social_effects_matrix_L1[i, 1:3] <- c(result[[i]]$summary.fixed["L1_log_st",]$`0.025quant`, result[[i]]$summary.fixed["L1_log_st",]$`0.5quant`, result[[i]]$summary.fixed["L1_log_st",]$`0.975quant`) + social_effects_matrix_L1[i, 4] <- predterms_short[[i]] + social_effects_matrix_L1[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_L1[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["L1_log_st"]])) + colnames(marginals_fixed_list_L1[[i]]) <- c("x for L1", "y for L1") + } + + if(i %in% L2_prop_element) { + social_effects_matrix_L2_prop[i, 1:3] <- c(result[[i]]$summary.fixed["L2_prop",]$`0.025quant`, result[[i]]$summary.fixed["L2_prop",]$`0.5quant`, result[[i]]$summary.fixed["L2_prop",]$`0.975quant`) + social_effects_matrix_L2_prop[i, 4] <- predterms_short[[i]] + social_effects_matrix_L2_prop[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_L2_prop[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["L2_prop"]])) + colnames(marginals_fixed_list_L2_prop[[i]]) <- c("x for L2 proportion", "y for L2 proportion") + } + + if(i %in% neighbour_element) { + social_effects_matrix_N[i, 1:3] <- c(result[[i]]$summary.fixed[2,]$`0.025quant`, result[[i]]$summary.fixed[2,]$`0.5quant`, result[[i]]$summary.fixed[2,]$`0.975quant`) + social_effects_matrix_N[i, 4] <- predterms_short[[i]] + social_effects_matrix_N[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_N[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][[2]])) + colnames(marginals_fixed_list_N[[i]]) <- c("x for Neighbours", "y for Neighbours") + } + + if(i %in% official_element) { + social_effects_matrix_O[i, 1:3] <- c(result[[i]]$summary.fixed[2,]$`0.025quant`, result[[i]]$summary.fixed[2,]$`0.5quant`, result[[i]]$summary.fixed[2,]$`0.975quant`) + social_effects_matrix_O[i, 4] <- predterms_short[[i]] + social_effects_matrix_O[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_O[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][[2]])) + colnames(marginals_fixed_list_O[[i]]) <- c("x for Official", "y for Official") + } + + if(i %in% education_element) { + social_effects_matrix_E[i, 1:3] <- c(result[[i]]$summary.fixed[2,]$`0.025quant`, result[[i]]$summary.fixed[2,]$`0.5quant`, result[[i]]$summary.fixed[2,]$`0.975quant`) + social_effects_matrix_E[i, 4] <- predterms_short[[i]] + social_effects_matrix_E[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_E[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][[2]])) + colnames(marginals_fixed_list_E[[i]]) <- c("x for Education", "y for Education") + } + + fitted_list[[i]] <- result[[i]]$summary.fitted.values + fitted_list[[i]] <- fitted_list[[i]] %>% + mutate(across(where(is.numeric), round, 2)) + + marginals_hyperpar_list_gaussian[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for the Gaussian observations"]])) + colnames(marginals_hyperpar_list_gaussian[[i]]) <- c("x for the Gaussian observations", "y for the Gaussian observations") + + if(i %in% L1_nl_element){ + marginals_hyperpar_list_social_L1_nl[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for inla.group(L1_copy)"]])) + colnames(marginals_hyperpar_list_social_L1_nl[[i]]) <- c("x for inla.group(L1_copy)", "y for inla.group(L1_copy)") + } + + if(i %in% L2_prop_nl_element){ + marginals_hyperpar_list_social_L2_prop_nl[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for inla.group(L2_copy)"]])) + colnames(marginals_hyperpar_list_social_L2_prop_nl[[i]]) <- c("x for inla.group(L2_copy)", "y for inla.group(L2_copy)") + } +} + +#beepr::beep(5) + +save(result, file = "output_models/models_Boundness_social_only.RData") +#load("output_models/models_Boundness_social_only.RData") + +coefm <- as.data.frame(cbind(predterms_short, coefm)) +colnames(coefm) <- c("model", "WAIC") +coefm <- coefm %>% + mutate(across(.cols=2, as.numeric)) %>% + mutate(across(where(is.numeric), round, 2)) %>% + arrange(WAIC) + +coefm$WAIC <- as.numeric(coefm$WAIC) +coefm <- coefm[order(coefm$WAIC),] + +coefm_path <- paste("output_tables_reduced/", "waics", "Boundness_social_only_models", ".csv", collapse = "") +write.csv(coefm, coefm_path, row.names=FALSE) + +for (i in 1:length(fitted_list)) { + fitted_list[[i]]$model <- names(fitted_list)[i] +} +fitted_list <- dplyr::bind_rows(fitted_list) +fitted_list_path <- paste("output_tables_reduced/", "fitted_list", "Boundness_social_only_models", ".csv", collapse = "") +write.csv(fitted_list, fitted_list_path) + +intercept_effects <- as.data.frame(intercept_matrix) +L1_effects <- as.data.frame(social_effects_matrix_L1) +L1_nl_effects <- as.data.frame(social_effects_matrix_L1_nl) +L2_prop_effects <- as.data.frame(social_effects_matrix_L2_prop) +L2_prop_nl_effects <- as.data.frame(social_effects_matrix_L2_prop_nl) +N_effects<-as.data.frame(social_effects_matrix_N) +E_effects<-as.data.frame(social_effects_matrix_E) +O_effects<-as.data.frame(social_effects_matrix_O) + +intercept_effects$effect <- "Intercept" +L1_effects$effect <- "L1" +L1_nl_effects$effect <- "social SD:\nL1" +L2_prop_effects$effect <- "L2 proportion" +L2_prop_nl_effects$effect <- "social SD:\nL2 proportion" +N_effects$effect <- "Neighbours" +E_effects$effect <- "Education" +O_effects$effect <- "Official status" + +effs <- as.data.frame(rbind(intercept_effects, L1_effects, L1_nl_effects, L2_prop_effects, L2_prop_nl_effects, N_effects, O_effects, E_effects)) +effs <- effs %>% + mutate(across(.cols=c(1:3, 5), as.numeric)) %>% + mutate(across(where(is.numeric), round, 2)) %>% + na.omit() %>% + arrange(WAIC) %>% + relocate(model) + +effs_path <- paste("output_tables_reduced/", "effects", "Boundness_social_only_models", ".csv", collapse = "") +write.csv(effs, effs_path, row.names=FALSE) + +effs <- read.csv("output_tables_reduced/ effects Boundness_social_only_models .csv") + +effs_table_SM <- effs %>% + rename("2.5%"=2, + "50%" = 4, + "97.5%" = 3) %>% + flextable() %>% + autofit() %>% + merge_v(j=c("model", "WAIC")) %>% + fix_border_issues() %>% + border_inner_h() + +save_as_docx( + "Effects in boundness models with fixed and random effects (including non-linear implementations of some fixed effects)" = effs_table_SM, + path = "output_tables_reduced/table_SM_effects_Boundness_social_only_models.docx") + +effs_table_Main <- effs %>% + rename("2.5%"=2, + "50%" = 4, + "97.5%" = 3) %>% + filter(!grepl("nonlinear", model)) + +effs_table_Main$model <- gsub("(\\s*\\(\\w+\\))", "", effs_table_Main$model) + +effs_table_Main <- effs_table_Main %>% + flextable() %>% + autofit() %>% + merge_v(j=c("model", "WAIC")) %>% + fix_border_issues() %>% + border_inner_h() + +save_as_docx( + "Effects in boundness models with fixed and random effects" = effs_table_Main, + path = "output_tables_reduced/table_Main_effects_Boundness_social_only_models.docx") + + +effs_plot <- effs %>% + #filter(WAIC <= top_9) %>% + rename(lower=2, + upper = 4, + mean = 3) %>% #mean here refers to 0.5 quantile + #filter(!effect == "Intercept") %>% + mutate(effect = factor(effect, levels=c("Intercept", "social SD:\nL1", "L1", "social SD:\nL2 proportion", "L2 proportion", "Neighbours", "Education", "Official status"))) %>% + mutate(WAIC = round(WAIC, 2)) %>% + unite("model", model, WAIC, sep = ",\nWAIC: ", remove=FALSE) %>% + group_by(WAIC) %>% + arrange(WAIC) %>% + mutate(model = forcats::fct_reorder(as.factor(model), WAIC)) %>% #reordering levels within model based on WAIC values + mutate(model = factor(model, levels=rev(levels(model)))) #reversing the order + + +#plot modified from function ggregplot::Efxplot +cols = c(brewer.pal(12, "Paired")) +cols = c("gray50", cols[c(1:8)]) + +show_col(cols) + +plot_1 <- ggplot(effs_plot, + aes(y = as.factor(model), + x = mean, + group = effect, + colour = effect)) + + geom_pointrangeh(aes(xmin = lower, xmax = upper), position = position_dodge(w = 0.9), size = 1.5) + + geom_vline(aes(xintercept = 0),lty = 2) + labs(x = NULL) + #coord_flip() + + scale_color_manual(values=cols) + + ylab("Model of boundness") + xlab("Estimate") + labs(color = "Effect") + theme_classic() + + theme(axis.text=element_text(size=50), + legend.text=element_text(size=50), + axis.title=element_text(size=50), + legend.title=element_text(size=50), + legend.spacing.y = unit(1.5, 'cm')) + + guides(color = guide_legend(reverse = TRUE, byrow = TRUE)) + + + +#plot_1 +ggsave(filename = 'output_reduced/SP_models_plot_Boundness_social_only_models.jpg', + plot_1, height = 20, width = 45) + + +#saving hyperparameters: Gaussian observations +for (i in 1:length(marginals_hyperpar_list_gaussian)) { + marginals_hyperpar_list_gaussian[[i]]$model <- names(marginals_hyperpar_list_gaussian)[i] +} +marginals_hyperpar_list_gaussian <- dplyr::bind_rows(marginals_hyperpar_list_gaussian) + +write.csv(marginals_hyperpar_list_gaussian, "output_tables_reduced/Boundness_social_only_models_marginals_hyperpar_gaussian.csv") diff --git a/101/replication_package/models_Boundness_social.R b/101/replication_package/models_Boundness_social.R new file mode 100644 index 0000000000000000000000000000000000000000..b8dbb7127e1f80a7b24c5c74e8237c412c5a8cbd --- /dev/null +++ b/101/replication_package/models_Boundness_social.R @@ -0,0 +1,560 @@ +#model fitting: Boundness predicted by social effects on top of random phylogenetic and spatial factors + +#Script was written by Sam Passmore and modified by Olena Shcherbakova + +source("requirements.R") + +source("install_and_load_INLA.R") + +source("set_up_inla.R") + +metrics_joined <- metrics_joined %>% + filter(!is.na(L1_log10_st)) %>% + rename(L1_log_st = L1_log10_st) %>% + mutate(L1_copy = L1_log_st) %>% + filter(!is.na(L2_prop)) %>% + mutate(L2_copy = L2_prop) %>% + filter(!is.na(neighboring_languages_st)) %>% + filter(!is.na(Official)) %>% + filter(!is.na(Education)) %>% + filter(!is.na(boundness_st)) %>% + filter(!is.na(informativity_st)) + +#dropping tips not in Grambank +metrics_joined <- metrics_joined[metrics_joined$Language_ID %in% tree$tip.label, ] +tree <- keep.tip(tree, metrics_joined$Language_ID) + +x <- assert_that(all(tree$tip.label %in% metrics_joined$Language_ID), msg = "The data and phylogeny taxa do not match") + +## Building standardized phylogenetic precision matrix +tree_scaled <- tree + +tree_vcv = vcv.phylo(tree_scaled) +typical_phylogenetic_variance = exp(mean(log(diag(tree_vcv)))) + +#We opt for a sparse phylogenetic precision matrix (i.e. it is quantified using all nodes and tips), since sparse matrices make the analysis in INLA less time-intensive +tree_scaled$edge.length <- tree_scaled$edge.length/typical_phylogenetic_variance +phylo_prec_mat <- MCMCglmm::inverseA(tree_scaled, + nodes = "ALL", + scale = FALSE)$Ainv + +metrics_joined = metrics_joined[order(match(metrics_joined$Language_ID, rownames(phylo_prec_mat))),] + +#"local" set of parameters +## Create spatial covariance matrix using the matern covariance function +spatial_covar_mat_1 = varcov.spatial(metrics_joined[,c("Longitude", "Latitude")], + cov.pars = phi_1, kappa = kappa)$varcov +# Calculate and standardize by the typical variance +typical_variance_spatial_1 = exp(mean(log(diag(spatial_covar_mat_1)))) +spatial_cov_std_1 = spatial_covar_mat_1 / typical_variance_spatial_1 +spatial_prec_mat_1 = solve(spatial_cov_std_1) +dimnames(spatial_prec_mat_1) = list(metrics_joined$Language_ID, metrics_joined$Language_ID) + +## Since we are using a sparse phylogenetic matrix, we are matching taxa to rows in the matrix +phy_id = match(tree$tip.label, rownames(phylo_prec_mat)) +metrics_joined$phy_id = phy_id + +## Other effects are in the same order they appear in the dataset +metrics_joined$sp_id = 1:nrow(spatial_prec_mat_1) + +#Preparing the formulas for 10 competing models to be used in inla() call +listcombo <- list( + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper)", "L1_log_st"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper)", "f(inla.group(L1_copy), model='rw2', scale.model = TRUE)"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper)", "L2_prop"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper)", "f(inla.group(L2_copy), model='rw2', scale.model = TRUE)"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper)", "f(inla.group(L1_copy), model='rw2', scale.model = TRUE)", "f(inla.group(L2_copy), model='rw2', scale.model = TRUE)"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper)", "L1_log_st", "L2_prop"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper)", "L1_log10:L2_prop"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper)", "neighboring_languages_st"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper)", "Official"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper)", "Education")) + + +predterms <- lapply(listcombo, function(x) paste(x, collapse="+")) + +predterms <- t(as.data.frame(predterms)) + +predterms_short <- predterms + +predterms_short <- gsub("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper)", "Phylogenetic", predterms_short, fixed=TRUE) +predterms_short <- gsub("f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper)", "Spatial: local", predterms_short, fixed=TRUE) + +predterms_short <- gsub("f(inla.group(L1_copy), model='rw2', scale.model = TRUE)", "L1 speakers (nonlinear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("L1_log_st", "L1 speakers (linear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("f(inla.group(L2_copy), model='rw2', scale.model = TRUE)", "L2 proportion (nonlinear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("L2_prop", "L2 proportion (linear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("neighboring_languages_st", "Neighbours", predterms_short, fixed=TRUE) + + + +phylogenetic_element <- data.frame("judgement" = grepl("Phylogenetic", predterms_short), + number = 1:length(predterms_short)) +phylogenetic_element <- phylogenetic_element[phylogenetic_element$judgement == TRUE,]$number + +spatial_element_local <- data.frame("judgement" = grepl("local", predterms_short), + number = 1:length(predterms_short)) +spatial_element_local <- spatial_element_local[spatial_element_local$judgement == TRUE,]$number + +spatial_element_regional <- data.frame("judgement" = grepl("regional", predterms_short), + number = 1:length(predterms_short)) +spatial_element_regional <- spatial_element_regional[spatial_element_regional$judgement == TRUE,]$number + +spatial_element <- c(spatial_element_local, spatial_element_regional) + +L1_element <- data.frame("judgement" = grepl("L1 speakers (linear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L1_element <- L1_element[L1_element$judgement == TRUE,]$number + + +L1_nl_element <- data.frame("judgement" = grepl("L1 speakers (nonlinear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L1_nl_element <- L1_nl_element[L1_nl_element$judgement == TRUE,]$number + +L2_prop_element <- data.frame("judgement" = grepl("L2 proportion (linear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L2_prop_element <- L2_prop_element[L2_prop_element$judgement == TRUE,]$number +L2_prop_element <- L2_prop_element[-length(L2_prop_element)] #making sure that the interaction term (introduced below) is not treated as belonging to this isolated element + +L2_prop_nl_element <- data.frame("judgement" = grepl("L2 proportion (nonlinear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L2_prop_nl_element <- L2_prop_nl_element[L2_prop_nl_element$judgement == TRUE,]$number + +#can use only part of the interaction term within grepl() function +interaction_element <- data.frame("judgement" = grepl(":L2 proportion", predterms_short), + number = 1:length(predterms_short)) +interaction_element <- interaction_element[interaction_element$judgement == TRUE,]$number + +neighbour_element <- data.frame("judgement" = grepl("Neighbours", predterms_short), + number = 1:length(predterms_short)) +neighbour_element <- neighbour_element[neighbour_element$judgement == TRUE,]$number + +official_element <- data.frame("judgement" = grepl("Official", predterms_short), + number = 1:length(predterms_short)) +official_element <- official_element[official_element$judgement == TRUE,]$number + +education_element <- data.frame("judgement" = grepl("Education", predterms_short), + number = 1:length(predterms_short)) +education_element <- education_element[education_element$judgement == TRUE,]$number + + + +#preparing empty matrices to be filled with effect estimates (quantiles), model name, and WAIC value +phy_effects_matrix <- matrix(NA, 10, 5) +colnames(phy_effects_matrix) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +spa_effects_matrix <- matrix(NA, 10, 5) +colnames(spa_effects_matrix) <- c("2.5%", "50%", "97.5%", "model", "WAIC") + +intercept_matrix <- matrix(NA, 10, 5) +colnames(intercept_matrix) <- c("2.5%", "50%", "97.5%", "model", "WAIC") + +social_effects_matrix_L1 <- matrix(NA, 10, 5) +colnames(social_effects_matrix_L1) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L1_nl <- matrix(NA, 10, 5) +colnames(social_effects_matrix_L1_nl) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L2_prop <- matrix(NA, 10, 5) +colnames(social_effects_matrix_L2_prop) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L2_prop_nl <- matrix(NA, 10, 5) +colnames(social_effects_matrix_L2_prop_nl) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_N <- matrix(NA, 10, 5) +colnames(social_effects_matrix_N) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_O <- matrix(NA, 10, 5) +colnames(social_effects_matrix_O) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_E <- matrix(NA, 10, 5) +colnames(social_effects_matrix_E) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L1_L2_prop <- matrix(NA, 10, 5) +colnames(social_effects_matrix_L1_L2_prop) <- c("2.5%", "50%", "97.5%", "model", "WAIC") + +#fitted values +fitted_list <- vector("list", 10) +names(fitted_list) <- predterms_short + +#marginals of hyperparameters +marginals_hyperpar_list_gaussian <- vector("list", 10) +names(marginals_hyperpar_list_gaussian) <- predterms_short + +marginals_hyperpar_list_phy <- vector("list", 10) +names(marginals_hyperpar_list_phy) <- predterms_short + +marginals_hyperpar_list_spa <- vector("list", 10) +names(marginals_hyperpar_list_spa) <- predterms_short + +marginals_hyperpar_list_social_L1_nl <- vector("list", 10) +names(marginals_hyperpar_list_social_L1_nl) <- predterms_short + +marginals_hyperpar_list_social_L2_prop_nl <- vector("list", 10) +names(marginals_hyperpar_list_social_L2_prop_nl) <- predterms_short + + +#marginals of fixed effects +marginals_fixed_list_Intercept <- vector("list", 10) +names(marginals_fixed_list_Intercept) <- predterms_short + +marginals_fixed_list_L1 <- vector("list", 10) +names(marginals_fixed_list_L1) <- predterms_short + +marginals_fixed_list_L2_prop <- vector("list", 10) +names(marginals_fixed_list_L2_prop) <- predterms_short + +marginals_fixed_list_O <- vector("list", 10) +names(marginals_fixed_list_O) <- predterms_short + +marginals_fixed_list_N <- vector("list", 10) +names(marginals_fixed_list_N) <- predterms_short + +marginals_fixed_list_E <- vector("list", 10) +names(marginals_fixed_list_E) <- predterms_short + +marginals_fixed_list_L1_L2_prop <- vector("list", 10) +names(marginals_fixed_list_L1_L2_prop) <- predterms_short + + + + +#summary statistics of random effects +summary_random_list_phy <- vector("list", 10) +names(summary_random_list_phy) <- predterms_short + +summary_random_list_spa <- vector("list", 10) +names(summary_random_list_spa) <- predterms_short + +summary_random_list_social_L1_nl <- vector("list", 10) +names(summary_random_list_social_L1_nl) <- predterms_short + +summary_random_list_social_L2_prop_nl <- vector("list", 10) +names(summary_random_list_social_L2_prop_nl) <- predterms_short + + +coefm <- matrix(NA,10,1) +result <- vector("list",10) + +for(i in 1:10){ + formula <- as.formula(paste("boundness_st ~ ",predterms[[i]])) + result[[i]] <- inla(formula, family="gaussian", + control.family = list(hyper = pcprior_hyper), + #control.inla = list(tolerance = 1e-8, h = 0.0001), + #tolerance: the tolerance for the optimisation of the hyperparameters + #h: the step-length for the gradient calculations for the hyperparameters. + data=metrics_joined, control.compute=list(waic=TRUE)) + + coefm[i,1] <- round(result[[i]]$waic$waic, 2) + + intercept_matrix[i, 1:3] <- c(result[[i]]$summary.fixed[1,]$`0.025quant`, result[[i]]$summary.fixed[1,]$`0.5quant`, result[[i]]$summary.fixed[1,]$`0.975quant`) + intercept_matrix[i, 4] <- predterms_short[[i]] + intercept_matrix[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_Intercept[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["(Intercept)"]])) + colnames(marginals_fixed_list_Intercept[[i]]) <- c("x for Intercept", "y for Intercept") + + if(i %in% phylogenetic_element) { + phy_effects_matrix[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for phy_id`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + phy_effects_matrix[i, 4] <- predterms_short[[i]] + phy_effects_matrix[i, 5] <- result[[i]]$waic$waic + } + + if(i %in% spatial_element) { + spa_effects_matrix[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for sp_id`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + spa_effects_matrix[i, 4] <- predterms_short[[i]] + spa_effects_matrix[i, 5] <- result[[i]]$waic$waic + } + + + if(i %in% L1_nl_element){ + social_effects_matrix_L1_nl[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for inla.group(L1_copy)`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + social_effects_matrix_L1_nl[i, 4] <- predterms_short[[i]] + social_effects_matrix_L1_nl[i, 5] <- result[[i]]$waic$waic + } + + if(i %in% L2_prop_nl_element){ + social_effects_matrix_L2_prop_nl[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for inla.group(L2_copy)`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + social_effects_matrix_L2_prop_nl[i, 4] <- predterms_short[[i]] + social_effects_matrix_L2_prop_nl[i, 5] <- result[[i]]$waic$waic + } + + if(i %in% L1_element) { + social_effects_matrix_L1[i, 1:3] <- c(result[[i]]$summary.fixed["L1_log_st",]$`0.025quant`, result[[i]]$summary.fixed["L1_log_st",]$`0.5quant`, result[[i]]$summary.fixed["L1_log_st",]$`0.975quant`) + social_effects_matrix_L1[i, 4] <- predterms_short[[i]] + social_effects_matrix_L1[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_L1[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["L1_log_st"]])) + colnames(marginals_fixed_list_L1[[i]]) <- c("x for L1", "y for L1") + } + + if(i %in% L2_prop_element) { + social_effects_matrix_L2_prop[i, 1:3] <- c(result[[i]]$summary.fixed["L2_prop",]$`0.025quant`, result[[i]]$summary.fixed["L2_prop",]$`0.5quant`, result[[i]]$summary.fixed["L2_prop",]$`0.975quant`) + social_effects_matrix_L2_prop[i, 4] <- predterms_short[[i]] + social_effects_matrix_L2_prop[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_L2_prop[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["L2_prop"]])) + colnames(marginals_fixed_list_L2_prop[[i]]) <- c("x for L2 proportion", "y for L2 proportion") + } + + if(i %in% interaction_element) { + social_effects_matrix_L1_L2_prop[i, 1:3] <- c(result[[i]]$summary.fixed["L1_log10:L2_prop",]$`0.025quant`, result[[i]]$summary.fixed["L1_log10:L2_prop",]$`0.5quant`, result[[i]]$summary.fixed["L1_log10:L2_prop",]$`0.975quant`) + social_effects_matrix_L1_L2_prop[i, 4] <- predterms_short[[i]] + social_effects_matrix_L1_L2_prop[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_L1_L2_prop[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["L1_log10:L2_prop"]])) + colnames(marginals_fixed_list_L1_L2_prop[[i]]) <- c("x for L1*L2 proportion", "y for L1*L2 proportion") + } + + if(i %in% neighbour_element) { + social_effects_matrix_N[i, 1:3] <- c(result[[i]]$summary.fixed[2,]$`0.025quant`, result[[i]]$summary.fixed[2,]$`0.5quant`, result[[i]]$summary.fixed[2,]$`0.975quant`) + social_effects_matrix_N[i, 4] <- predterms_short[[i]] + social_effects_matrix_N[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_N[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][[2]])) + colnames(marginals_fixed_list_N[[i]]) <- c("x for Neighbours", "y for Neighbours") + } + + if(i %in% official_element) { + social_effects_matrix_O[i, 1:3] <- c(result[[i]]$summary.fixed[2,]$`0.025quant`, result[[i]]$summary.fixed[2,]$`0.5quant`, result[[i]]$summary.fixed[2,]$`0.975quant`) + social_effects_matrix_O[i, 4] <- predterms_short[[i]] + social_effects_matrix_O[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_O[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][[2]])) + colnames(marginals_fixed_list_O[[i]]) <- c("x for Official", "y for Official") + } + + if(i %in% education_element) { + social_effects_matrix_E[i, 1:3] <- c(result[[i]]$summary.fixed[2,]$`0.025quant`, result[[i]]$summary.fixed[2,]$`0.5quant`, result[[i]]$summary.fixed[2,]$`0.975quant`) + social_effects_matrix_E[i, 4] <- predterms_short[[i]] + social_effects_matrix_E[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_E[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][[2]])) + colnames(marginals_fixed_list_E[[i]]) <- c("x for Education", "y for Education") + } + + fitted_list[[i]] <- result[[i]]$summary.fitted.values + fitted_list[[i]] <- fitted_list[[i]] %>% + mutate(across(where(is.numeric), round, 2)) + + marginals_hyperpar_list_gaussian[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for the Gaussian observations"]])) + colnames(marginals_hyperpar_list_gaussian[[i]]) <- c("x for the Gaussian observations", "y for the Gaussian observations") + + if(i %in% phylogenetic_element){ + marginals_hyperpar_list_phy[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for phy_id"]])) + colnames(marginals_hyperpar_list_phy[[i]]) <- c("x for phy_id", "y for phy_id") + } + + if(i %in% spatial_element){ + marginals_hyperpar_list_spa[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for sp_id"]])) + colnames(marginals_hyperpar_list_spa[[i]]) <- c("x for sp_id", "y for sp_id") + } + + if(i %in% L1_nl_element){ + marginals_hyperpar_list_social_L1_nl[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for inla.group(L1_copy)"]])) + colnames(marginals_hyperpar_list_social_L1_nl[[i]]) <- c("x for inla.group(L1_copy)", "y for inla.group(L1_copy)") + } + + if(i %in% L2_prop_nl_element){ + marginals_hyperpar_list_social_L2_prop_nl[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for inla.group(L2_copy)"]])) + colnames(marginals_hyperpar_list_social_L2_prop_nl[[i]]) <- c("x for inla.group(L2_copy)", "y for inla.group(L2_copy)") + } + + if(i %in% phylogenetic_element){ + summary_random_list_phy[[i]] <- cbind(result[[i]]$summary.random$phy_id) %>% + rename(phy_id = ID) %>% + as.data.frame() %>% + mutate(across(where(is.numeric), round, 2)) + } + + if(i %in% spatial_element){ + summary_random_list_spa[[i]] <- cbind(result[[i]]$summary.random$sp_id) %>% + rename(sp_id = ID) %>% + as.data.frame() %>% + mutate(across(where(is.numeric), round, 2)) + } +} + +#beepr::beep(5) + +save(result, file = "output_models/models_Boundness_social.RData") +load("output_models/models_Boundness_social.RData") + + + coefm <- as.data.frame(cbind(predterms_short, coefm)) + colnames(coefm) <- c("model", "WAIC") + coefm <- coefm %>% + mutate(across(.cols=2, as.numeric)) %>% + mutate(across(where(is.numeric), round, 2)) %>% + arrange(WAIC) + + coefm$WAIC <- as.numeric(coefm$WAIC) + coefm <- coefm[order(coefm$WAIC),] + +coefm_path <- paste("output_tables/", "waics", "Boundness_social_models", ".csv", collapse = "") +write.csv(coefm, coefm_path, row.names=FALSE) + +for (i in 1:length(fitted_list)) { + fitted_list[[i]]$model <- names(fitted_list)[i] +} +fitted_list <- dplyr::bind_rows(fitted_list) +fitted_list_path <- paste("output_tables/", "fitted_list", "Boundness_social_models", ".csv", collapse = "") +write.csv(fitted_list, fitted_list_path) + + +phy_effects<-as.data.frame(phy_effects_matrix) +spa_effects<-as.data.frame(spa_effects_matrix) +intercept_effects <- as.data.frame(intercept_matrix) +L1_effects <- as.data.frame(social_effects_matrix_L1) +L1_nl_effects <- as.data.frame(social_effects_matrix_L1_nl) +L2_prop_effects <- as.data.frame(social_effects_matrix_L2_prop) +L2_prop_nl_effects <- as.data.frame(social_effects_matrix_L2_prop_nl) +N_effects<-as.data.frame(social_effects_matrix_N) +E_effects<-as.data.frame(social_effects_matrix_E) +O_effects<-as.data.frame(social_effects_matrix_O) +interaction_effects <- as.data.frame(social_effects_matrix_L1_L2_prop) + +phy_effects$effect <- "phylogenetic SD" +spa_effects$effect <- "spatial SD" +intercept_effects$effect <- "Intercept" +L1_effects$effect <- "L1" +L1_nl_effects$effect <- "social SD:\nL1" +L2_prop_effects$effect <- "L2 proportion" +L2_prop_nl_effects$effect <- "social SD:\nL2 proportion" +N_effects$effect <- "Neighbours" +E_effects$effect <- "Education" +O_effects$effect <- "Official status" +interaction_effects$effect <- "L1*L2 proportion" + +effs <- as.data.frame(rbind(phy_effects, spa_effects, intercept_effects, L1_effects, L1_nl_effects, L2_prop_effects, L2_prop_nl_effects, N_effects, O_effects, E_effects, interaction_effects)) +effs <- effs %>% + mutate(across(.cols=c(1:3, 5), as.numeric)) %>% + mutate(across(where(is.numeric), round, 2)) %>% + na.omit() %>% + arrange(WAIC) %>% + relocate(model) + +effs_path <- paste("output_tables/", "effects", "Boundness_social_models", ".csv", collapse = "") +write.csv(effs, effs_path, row.names=FALSE) + +effs <- read.csv("output_tables/ effects Boundness_social_models .csv") + +effs_table_Main <- effs %>% + rename("2.5%"=2, + "50%" = 3, + "97.5%" = 4) %>% + filter(!grepl("nonlinear", model)) + +effs_table_Main$model <- gsub("(\\s*\\(\\w+\\))", "", effs_table_Main$model) + +effs_table_Main <- effs_table_Main %>% + relocate(effect, .after = model) %>% + flextable() %>% + flextable::bold(~ (`2.5%` > 0 & `97.5%` > 0) | (`2.5%` < 0 & `97.5%` < 0), 2) %>% + autofit() %>% + merge_v(j=c("model", "WAIC")) %>% + fix_border_issues() %>% + border_inner_h() + +save_as_docx( + "Effects in boundness models with fixed and random effects" = effs_table_Main, + path = "output_tables/table_Main_effects_Boundness_social_models.docx") + + +effs_plot <- effs %>% + #filter(WAIC <= top_9) %>% + rename(lower=2, + upper = 4, + mean = 3) %>% #mean here refers to 0.5 quantile + #filter(!effect == "Intercept") %>% + mutate(effect = factor(effect, levels=c("phylogenetic SD", "spatial SD", "Intercept", "social SD:\nL1", "L1", "social SD:\nL2 proportion", "L2 proportion", "Neighbours", "Education", "Official status", "L1*L2 proportion"))) %>% + mutate(WAIC = round(WAIC, 2)) %>% + unite("model", model, WAIC, sep = ",\nWAIC: ", remove=FALSE) %>% + group_by(WAIC) %>% + arrange(WAIC) %>% + mutate(model = forcats::fct_reorder(as.factor(model), WAIC)) %>% #reordering levels within model based on WAIC values + mutate(model = factor(model, levels=rev(levels(model)))) #reversing the order + + + +#plot modified from function ggregplot::Efxplot +cols = c(brewer.pal(12, "Paired")) +cols = c(cols[c(12, 10)], "gray50", cols[c(1:8)]) + +show_col(cols) + +plot_1 <- ggplot(effs_plot, + aes(y = as.factor(model), + x = mean, + group = effect, + colour = effect)) + + geom_pointrangeh(aes(xmin = lower, xmax = upper), position = position_dodge(w = 0.9), size = 1.5) + + geom_vline(aes(xintercept = 0),lty = 2) + labs(x = NULL) + #coord_flip() + + scale_color_manual(values=cols) + + ylab("Model of boundness") + xlab("Estimate") + labs(color = "Effect") + theme_classic() + + theme(axis.text=element_text(size=50), + legend.text=element_text(size=50), + axis.title=element_text(size=50), + legend.title=element_text(size=50), + legend.spacing.y = unit(1.5, 'cm')) + + guides(color = guide_legend(reverse = TRUE, byrow = TRUE)) + + +#plot_1 +ggsave(filename = 'output/SP_models_plot_Boundness_social_models.jpg', + plot_1, height = 20, width = 45) + + +#saving hyperparameters: Gaussian observations +for (i in 1:length(marginals_hyperpar_list_gaussian)) { + marginals_hyperpar_list_gaussian[[i]]$model <- names(marginals_hyperpar_list_gaussian)[i] +} +marginals_hyperpar_list_gaussian <- dplyr::bind_rows(marginals_hyperpar_list_gaussian) + +write.csv(marginals_hyperpar_list_gaussian, "output_tables/Boundness_social_models_marginals_hyperpar_gaussian.csv") + +#saving hyperparameters: phylogenetic +for (i in 1:length(marginals_hyperpar_list_phy)) { + marginals_hyperpar_list_phy[[i]]$model <- names(marginals_hyperpar_list_phy)[i] +} +marginals_hyperpar_list_phy <- dplyr::bind_rows(marginals_hyperpar_list_phy) + +write.csv(marginals_hyperpar_list_phy, "output_tables/Boundness_social_models_marginals_hyperpar_phylogenetic.csv") + +#saving hyperparameters: spatial +for (i in 1:length(marginals_hyperpar_list_spa)) { + marginals_hyperpar_list_spa[[i]]$model <- names(marginals_hyperpar_list_spa)[i] +} +marginals_hyperpar_list_spa <- dplyr::bind_rows(marginals_hyperpar_list_spa) + +write.csv(marginals_hyperpar_list_spa, "output_tables/Boundness_social_models_marginals_hyperpar_spatial.csv") + + +#saving summaries of random effects: phylogenetic +for (i in 1:length(summary_random_list_phy)) { + summary_random_list_phy[[i]]$model <- names(summary_random_list_phy)[i] +} +summary_random_list_phy <- dplyr::bind_rows(summary_random_list_phy) + +write.csv(summary_random_list_phy, "output_tables/Boundness_social_models_summary_random_phy.csv") + +#saving summaries of random effects: spatial +for (i in 1:length(summary_random_list_spa)) { + summary_random_list_spa[[i]]$model <- names(summary_random_list_spa)[i] +} +summary_random_list_spa <- dplyr::bind_rows(summary_random_list_spa) + +write.csv(summary_random_list_spa, "output_tables/Boundness_social_models_summary_random_spa.csv") diff --git a/101/replication_package/models_Boundness_social_only.R b/101/replication_package/models_Boundness_social_only.R new file mode 100644 index 0000000000000000000000000000000000000000..99b51e059e7d68f3600cbff7ad4d7025084aeb94 --- /dev/null +++ b/101/replication_package/models_Boundness_social_only.R @@ -0,0 +1,452 @@ +#model fitting: Boundness predicted by social effects on top of random phylogenetic and spatial factors + +#Script was written by Sam Passmore and modified by Olena Shcherbakova + +source("requirements.R") + +source("install_and_load_INLA.R") + +source("set_up_inla.R") + +metrics_joined <- metrics_joined %>% + filter(!is.na(L1_log10_st)) %>% + rename(L1_log_st = L1_log10_st) %>% + mutate(L1_copy = L1_log_st) %>% + filter(!is.na(L2_prop)) %>% + mutate(L2_copy = L2_prop) %>% + filter(!is.na(neighboring_languages_st)) %>% + filter(!is.na(Official)) %>% + filter(!is.na(Education)) %>% + filter(!is.na(boundness_st)) %>% + filter(!is.na(informativity_st)) + +#dropping tips not in Grambank +metrics_joined <- metrics_joined[metrics_joined$Language_ID %in% tree$tip.label, ] +tree <- keep.tip(tree, metrics_joined$Language_ID) + +x <- assert_that(all(tree$tip.label %in% metrics_joined$Language_ID), msg = "The data and phylogeny taxa do not match") + +## Building standardized phylogenetic precision matrix +tree_scaled <- tree + +tree_vcv = vcv.phylo(tree_scaled) +typical_phylogenetic_variance = exp(mean(log(diag(tree_vcv)))) + +#We opt for a sparse phylogenetic precision matrix (i.e. it is quantified using all nodes and tips), since sparse matrices make the analysis in INLA less time-intensive +tree_scaled$edge.length <- tree_scaled$edge.length/typical_phylogenetic_variance +phylo_prec_mat <- MCMCglmm::inverseA(tree_scaled, + nodes = "ALL", + scale = FALSE)$Ainv + +metrics_joined = metrics_joined[order(match(metrics_joined$Language_ID, rownames(phylo_prec_mat))),] + +#"local" set of parameters +## Create spatial covariance matrix using the matern covariance function +spatial_covar_mat_1 = varcov.spatial(metrics_joined[,c("Longitude", "Latitude")], + cov.pars = phi_1, kappa = kappa)$varcov +# Calculate and standardize by the typical variance +typical_variance_spatial_1 = exp(mean(log(diag(spatial_covar_mat_1)))) +spatial_cov_std_1 = spatial_covar_mat_1 / typical_variance_spatial_1 +spatial_prec_mat_1 = solve(spatial_cov_std_1) +dimnames(spatial_prec_mat_1) = list(metrics_joined$Language_ID, metrics_joined$Language_ID) + +## Since we are using a sparse phylogenetic matrix, we are matching taxa to rows in the matrix +phy_id = match(tree$tip.label, rownames(phylo_prec_mat)) +metrics_joined$phy_id = phy_id + +## Other effects are in the same order they appear in the dataset +metrics_joined$sp_id = 1:nrow(spatial_prec_mat_1) + +#Preparing the formulas for 10 competing models to be used in inla() call +listcombo <- list( + c("L1_log_st"), + + c("f(inla.group(L1_copy), model='rw2', scale.model = TRUE)"), + + c("L2_prop"), + + c("f(inla.group(L2_copy), model='rw2', scale.model = TRUE)"), + + c("f(inla.group(L1_copy), model='rw2', scale.model = TRUE)", "f(inla.group(L2_copy), model='rw2', scale.model = TRUE)"), + + c("L1_log_st", "L2_prop"), + + c("L1_log10:L2_prop"), + + c("neighboring_languages_st"), + + c("Official"), + + c("Education")) + + +predterms <- lapply(listcombo, function(x) paste(x, collapse="+")) + +predterms <- t(as.data.frame(predterms)) + +predterms_short <- predterms + +predterms_short <- gsub("f(inla.group(L1_copy), model='rw2', scale.model = TRUE)", "L1 speakers (nonlinear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("L1_log_st", "L1 speakers (linear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("f(inla.group(L2_copy), model='rw2', scale.model = TRUE)", "L2 proportion (nonlinear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("L2_prop", "L2 proportion (linear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("neighboring_languages_st", "Neighbours", predterms_short, fixed=TRUE) + +L1_element <- data.frame("judgement" = grepl("L1 speakers (linear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L1_element <- L1_element[L1_element$judgement == TRUE,]$number + + +L1_nl_element <- data.frame("judgement" = grepl("L1 speakers (nonlinear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L1_nl_element <- L1_nl_element[L1_nl_element$judgement == TRUE,]$number + +L2_prop_element <- data.frame("judgement" = grepl("L2 proportion (linear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L2_prop_element <- L2_prop_element[L2_prop_element$judgement == TRUE,]$number +L2_prop_element <- L2_prop_element[-length(L2_prop_element)] #making sure that the interaction term (introduced below) is not treated as belonging to this isolated element + +L2_prop_nl_element <- data.frame("judgement" = grepl("L2 proportion (nonlinear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L2_prop_nl_element <- L2_prop_nl_element[L2_prop_nl_element$judgement == TRUE,]$number + +#can use only part of the interaction term within grepl() function +interaction_element <- data.frame("judgement" = grepl(":L2 proportion", predterms_short), + number = 1:length(predterms_short)) +interaction_element <- interaction_element[interaction_element$judgement == TRUE,]$number + +neighbour_element <- data.frame("judgement" = grepl("Neighbours", predterms_short), + number = 1:length(predterms_short)) +neighbour_element <- neighbour_element[neighbour_element$judgement == TRUE,]$number + +official_element <- data.frame("judgement" = grepl("Official", predterms_short), + number = 1:length(predterms_short)) +official_element <- official_element[official_element$judgement == TRUE,]$number + +education_element <- data.frame("judgement" = grepl("Education", predterms_short), + number = 1:length(predterms_short)) +education_element <- education_element[education_element$judgement == TRUE,]$number + + + +#preparing empty matrices to be filled with effect estimates (quantiles), model name, and WAIC value +intercept_matrix <- matrix(NA, 10, 5) +colnames(intercept_matrix) <- c("2.5%", "50%", "97.5%", "model", "WAIC") + +social_effects_matrix_L1 <- matrix(NA, 10, 5) +colnames(social_effects_matrix_L1) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L1_nl <- matrix(NA, 10, 5) +colnames(social_effects_matrix_L1_nl) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L2_prop <- matrix(NA, 10, 5) +colnames(social_effects_matrix_L2_prop) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L2_prop_nl <- matrix(NA, 10, 5) +colnames(social_effects_matrix_L2_prop_nl) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_N <- matrix(NA, 10, 5) +colnames(social_effects_matrix_N) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_O <- matrix(NA, 10, 5) +colnames(social_effects_matrix_O) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_E <- matrix(NA, 10, 5) +colnames(social_effects_matrix_E) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L1_L2_prop <- matrix(NA, 10, 5) +colnames(social_effects_matrix_L1_L2_prop) <- c("2.5%", "50%", "97.5%", "model", "WAIC") + +#fitted values +fitted_list <- vector("list", 10) +names(fitted_list) <- predterms_short + +#marginals of hyperparameters +marginals_hyperpar_list_gaussian <- vector("list", 10) +names(marginals_hyperpar_list_gaussian) <- predterms_short + +marginals_hyperpar_list_social_L1_nl <- vector("list", 10) +names(marginals_hyperpar_list_social_L1_nl) <- predterms_short + +marginals_hyperpar_list_social_L2_prop_nl <- vector("list", 10) +names(marginals_hyperpar_list_social_L2_prop_nl) <- predterms_short + + +#marginals of fixed effects +marginals_fixed_list_Intercept <- vector("list", 10) +names(marginals_fixed_list_Intercept) <- predterms_short + +marginals_fixed_list_L1 <- vector("list", 10) +names(marginals_fixed_list_L1) <- predterms_short + +marginals_fixed_list_L2_prop <- vector("list", 10) +names(marginals_fixed_list_L2_prop) <- predterms_short + +marginals_fixed_list_O <- vector("list", 10) +names(marginals_fixed_list_O) <- predterms_short + +marginals_fixed_list_N <- vector("list", 10) +names(marginals_fixed_list_N) <- predterms_short + +marginals_fixed_list_E <- vector("list", 10) +names(marginals_fixed_list_E) <- predterms_short + +marginals_fixed_list_L1_L2_prop <- vector("list", 10) +names(marginals_fixed_list_L1_L2_prop) <- predterms_short + + +#summary statistics of random effects +summary_random_list_social_L1_nl <- vector("list", 10) +names(summary_random_list_social_L1_nl) <- predterms_short + +summary_random_list_social_L2_prop_nl <- vector("list", 10) +names(summary_random_list_social_L2_prop_nl) <- predterms_short + + +coefm <- matrix(NA,10,1) +result <- vector("list",10) + +for(i in 1:10){ + formula <- as.formula(paste("boundness_st ~ ",predterms[[i]])) + result[[i]] <- inla(formula, family="gaussian", + control.family = list(hyper = pcprior_hyper), + #control.inla = list(tolerance = 1e-8, h = 0.0001), + #tolerance: the tolerance for the optimisation of the hyperparameters + #h: the step-length for the gradient calculations for the hyperparameters. + data=metrics_joined, control.compute=list(waic=TRUE)) + + coefm[i,1] <- round(result[[i]]$waic$waic, 2) + + intercept_matrix[i, 1:3] <- c(result[[i]]$summary.fixed[1,]$`0.025quant`, result[[i]]$summary.fixed[1,]$`0.5quant`, result[[i]]$summary.fixed[1,]$`0.975quant`) + intercept_matrix[i, 4] <- predterms_short[[i]] + intercept_matrix[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_Intercept[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["(Intercept)"]])) + colnames(marginals_fixed_list_Intercept[[i]]) <- c("x for Intercept", "y for Intercept") + + if(i %in% L1_nl_element){ + social_effects_matrix_L1_nl[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for inla.group(L1_copy)`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + social_effects_matrix_L1_nl[i, 4] <- predterms_short[[i]] + social_effects_matrix_L1_nl[i, 5] <- result[[i]]$waic$waic + } + + if(i %in% L2_prop_nl_element){ + social_effects_matrix_L2_prop_nl[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for inla.group(L2_copy)`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + social_effects_matrix_L2_prop_nl[i, 4] <- predterms_short[[i]] + social_effects_matrix_L2_prop_nl[i, 5] <- result[[i]]$waic$waic + } + + if(i %in% L1_element) { + social_effects_matrix_L1[i, 1:3] <- c(result[[i]]$summary.fixed["L1_log_st",]$`0.025quant`, result[[i]]$summary.fixed["L1_log_st",]$`0.5quant`, result[[i]]$summary.fixed["L1_log_st",]$`0.975quant`) + social_effects_matrix_L1[i, 4] <- predterms_short[[i]] + social_effects_matrix_L1[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_L1[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["L1_log_st"]])) + colnames(marginals_fixed_list_L1[[i]]) <- c("x for L1", "y for L1") + } + + if(i %in% L2_prop_element) { + social_effects_matrix_L2_prop[i, 1:3] <- c(result[[i]]$summary.fixed["L2_prop",]$`0.025quant`, result[[i]]$summary.fixed["L2_prop",]$`0.5quant`, result[[i]]$summary.fixed["L2_prop",]$`0.975quant`) + social_effects_matrix_L2_prop[i, 4] <- predterms_short[[i]] + social_effects_matrix_L2_prop[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_L2_prop[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["L2_prop"]])) + colnames(marginals_fixed_list_L2_prop[[i]]) <- c("x for L2 proportion", "y for L2 proportion") + } + + if(i %in% interaction_element) { + social_effects_matrix_L1_L2_prop[i, 1:3] <- c(result[[i]]$summary.fixed["L1_log10:L2_prop",]$`0.025quant`, result[[i]]$summary.fixed["L1_log10:L2_prop",]$`0.5quant`, result[[i]]$summary.fixed["L1_log10:L2_prop",]$`0.975quant`) + social_effects_matrix_L1_L2_prop[i, 4] <- predterms_short[[i]] + social_effects_matrix_L1_L2_prop[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_L1_L2_prop[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["L1_log10:L2_prop"]])) + colnames(marginals_fixed_list_L1_L2_prop[[i]]) <- c("x for L1*L2 proportion", "y for L1*L2 proportion") + } + + if(i %in% neighbour_element) { + social_effects_matrix_N[i, 1:3] <- c(result[[i]]$summary.fixed[2,]$`0.025quant`, result[[i]]$summary.fixed[2,]$`0.5quant`, result[[i]]$summary.fixed[2,]$`0.975quant`) + social_effects_matrix_N[i, 4] <- predterms_short[[i]] + social_effects_matrix_N[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_N[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][[2]])) + colnames(marginals_fixed_list_N[[i]]) <- c("x for Neighbours", "y for Neighbours") + } + + if(i %in% official_element) { + social_effects_matrix_O[i, 1:3] <- c(result[[i]]$summary.fixed[2,]$`0.025quant`, result[[i]]$summary.fixed[2,]$`0.5quant`, result[[i]]$summary.fixed[2,]$`0.975quant`) + social_effects_matrix_O[i, 4] <- predterms_short[[i]] + social_effects_matrix_O[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_O[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][[2]])) + colnames(marginals_fixed_list_O[[i]]) <- c("x for Official", "y for Official") + } + + if(i %in% education_element) { + social_effects_matrix_E[i, 1:3] <- c(result[[i]]$summary.fixed[2,]$`0.025quant`, result[[i]]$summary.fixed[2,]$`0.5quant`, result[[i]]$summary.fixed[2,]$`0.975quant`) + social_effects_matrix_E[i, 4] <- predterms_short[[i]] + social_effects_matrix_E[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_E[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][[2]])) + colnames(marginals_fixed_list_E[[i]]) <- c("x for Education", "y for Education") + } + + fitted_list[[i]] <- result[[i]]$summary.fitted.values + fitted_list[[i]] <- fitted_list[[i]] %>% + mutate(across(where(is.numeric), round, 2)) + + marginals_hyperpar_list_gaussian[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for the Gaussian observations"]])) + colnames(marginals_hyperpar_list_gaussian[[i]]) <- c("x for the Gaussian observations", "y for the Gaussian observations") + + if(i %in% L1_nl_element){ + marginals_hyperpar_list_social_L1_nl[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for inla.group(L1_copy)"]])) + colnames(marginals_hyperpar_list_social_L1_nl[[i]]) <- c("x for inla.group(L1_copy)", "y for inla.group(L1_copy)") + } + + if(i %in% L2_prop_nl_element){ + marginals_hyperpar_list_social_L2_prop_nl[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for inla.group(L2_copy)"]])) + colnames(marginals_hyperpar_list_social_L2_prop_nl[[i]]) <- c("x for inla.group(L2_copy)", "y for inla.group(L2_copy)") + } +} + +#beepr::beep(5) + +save(result, file = "output_models/models_Boundness_social_only.RData") +#load("output_models/models_Boundness_social_only.RData") + +coefm <- as.data.frame(cbind(predterms_short, coefm)) +colnames(coefm) <- c("model", "WAIC") +coefm <- coefm %>% + mutate(across(.cols=2, as.numeric)) %>% + mutate(across(where(is.numeric), round, 2)) %>% + arrange(WAIC) + +coefm$WAIC <- as.numeric(coefm$WAIC) +coefm <- coefm[order(coefm$WAIC),] + +coefm_path <- paste("output_tables/", "waics", "Boundness_social_only_models", ".csv", collapse = "") +write.csv(coefm, coefm_path, row.names=FALSE) + +for (i in 1:length(fitted_list)) { + fitted_list[[i]]$model <- names(fitted_list)[i] +} +fitted_list <- dplyr::bind_rows(fitted_list) +fitted_list_path <- paste("output_tables/", "fitted_list", "Boundness_social_only_models", ".csv", collapse = "") +write.csv(fitted_list, fitted_list_path) + +intercept_effects <- as.data.frame(intercept_matrix) +L1_effects <- as.data.frame(social_effects_matrix_L1) +L1_nl_effects <- as.data.frame(social_effects_matrix_L1_nl) +L2_prop_effects <- as.data.frame(social_effects_matrix_L2_prop) +L2_prop_nl_effects <- as.data.frame(social_effects_matrix_L2_prop_nl) +N_effects<-as.data.frame(social_effects_matrix_N) +E_effects<-as.data.frame(social_effects_matrix_E) +O_effects<-as.data.frame(social_effects_matrix_O) +interaction_effects <- as.data.frame(social_effects_matrix_L1_L2_prop) + +intercept_effects$effect <- "Intercept" +L1_effects$effect <- "L1" +L1_nl_effects$effect <- "social SD:\nL1" +L2_prop_effects$effect <- "L2 proportion" +L2_prop_nl_effects$effect <- "social SD:\nL2 proportion" +N_effects$effect <- "Neighbours" +E_effects$effect <- "Education" +O_effects$effect <- "Official status" +interaction_effects$effect <- "L1*L2 proportion" + +effs <- as.data.frame(rbind(intercept_effects, L1_effects, L1_nl_effects, L2_prop_effects, L2_prop_nl_effects, N_effects, O_effects, E_effects, interaction_effects)) +effs <- effs %>% + mutate(across(.cols=c(1:3, 5), as.numeric)) %>% + mutate(across(where(is.numeric), round, 2)) %>% + na.omit() %>% + arrange(WAIC) %>% + relocate(model) + +effs_path <- paste("output_tables/", "effects", "Boundness_social_only_models", ".csv", collapse = "") +write.csv(effs, effs_path, row.names=FALSE) + +effs <- read.csv("output_tables/ effects Boundness_social_only_models .csv") + +effs_table_SM <- effs %>% + rename("2.5%"=2, + "50%" = 4, + "97.5%" = 3) %>% + flextable() %>% + autofit() %>% + merge_v(j=c("model", "WAIC")) %>% + fix_border_issues() %>% + border_inner_h() + +save_as_docx( + "Effects in boundness models with fixed and random effects (including non-linear implementations of some fixed effects)" = effs_table_SM, + path = "output_tables/table_SM_effects_Boundness_social_only_models.docx") + +effs_table_Main <- effs %>% + rename("2.5%"=2, + "50%" = 4, + "97.5%" = 3) %>% + filter(!grepl("nonlinear", model)) + +effs_table_Main$model <- gsub("(\\s*\\(\\w+\\))", "", effs_table_Main$model) + +effs_table_Main <- effs_table_Main %>% + flextable() %>% + autofit() %>% + merge_v(j=c("model", "WAIC")) %>% + fix_border_issues() %>% + border_inner_h() + +save_as_docx( + "Effects in boundness models with fixed and random effects" = effs_table_Main, + path = "output_tables/table_Main_effects_Boundness_social_only_models.docx") + + +effs_plot <- effs %>% + #filter(WAIC <= top_9) %>% + rename(lower=2, + upper = 4, + mean = 3) %>% #mean here refers to 0.5 quantile + #filter(!effect == "Intercept") %>% + mutate(effect = factor(effect, levels=c("Intercept", "social SD:\nL1", "L1", "social SD:\nL2 proportion", "L2 proportion", "Neighbours", "Education", "Official status", "L1*L2 proportion"))) %>% + mutate(WAIC = round(WAIC, 2)) %>% + unite("model", model, WAIC, sep = ",\nWAIC: ", remove=FALSE) %>% + group_by(WAIC) %>% + arrange(WAIC) %>% + mutate(model = forcats::fct_reorder(as.factor(model), WAIC)) %>% #reordering levels within model based on WAIC values + mutate(model = factor(model, levels=rev(levels(model)))) #reversing the order + + +#plot modified from function ggregplot::Efxplot +cols = c(brewer.pal(12, "Paired")) +cols = c("gray50", cols[c(1:8)]) + +show_col(cols) + +plot_1 <- ggplot(effs_plot, + aes(y = as.factor(model), + x = mean, + group = effect, + colour = effect)) + + geom_pointrangeh(aes(xmin = lower, xmax = upper), position = position_dodge(w = 0.9), size = 1.5) + + geom_vline(aes(xintercept = 0),lty = 2) + labs(x = NULL) + #coord_flip() + + scale_color_manual(values=cols) + + ylab("Model of boundness") + xlab("Estimate") + labs(color = "Effect") + theme_classic() + + theme(axis.text=element_text(size=50), + legend.text=element_text(size=50), + axis.title=element_text(size=50), + legend.title=element_text(size=50), + legend.spacing.y = unit(1.5, 'cm')) + + guides(color = guide_legend(reverse = TRUE, byrow = TRUE)) + + + +#plot_1 +ggsave(filename = 'output/SP_models_plot_Boundness_social_only_models.jpg', + plot_1, height = 20, width = 45) + + +#saving hyperparameters: Gaussian observations +for (i in 1:length(marginals_hyperpar_list_gaussian)) { + marginals_hyperpar_list_gaussian[[i]]$model <- names(marginals_hyperpar_list_gaussian)[i] +} +marginals_hyperpar_list_gaussian <- dplyr::bind_rows(marginals_hyperpar_list_gaussian) + +write.csv(marginals_hyperpar_list_gaussian, "output_tables/Boundness_social_only_models_marginals_hyperpar_gaussian.csv") \ No newline at end of file diff --git a/101/replication_package/models_Informativity_phylogenetic_spatial.R b/101/replication_package/models_Informativity_phylogenetic_spatial.R new file mode 100644 index 0000000000000000000000000000000000000000..f3c670279d1daa75328c55ecffcd56eaf8b738e9 --- /dev/null +++ b/101/replication_package/models_Informativity_phylogenetic_spatial.R @@ -0,0 +1,414 @@ +#model fitting: Informativity predicted by combinations of random phylogenetic and spatial factors + +#Script was written by Sam Passmore and modified by Olena Shcherbakova + +source("requirements.R") + +source("install_and_load_INLA.R") + +source("set_up_inla.R") + +metrics_joined <- metrics_joined %>% + filter(!is.na(L1_log10_st)) %>% + rename(L1_log_st = L1_log10_st) %>% + mutate(L1_copy = L1_log_st) %>% + filter(!is.na(L2_prop)) %>% + mutate(L2_copy = L2_prop) %>% + filter(!is.na(neighboring_languages_st)) %>% + filter(!is.na(Official)) %>% + filter(!is.na(Education)) %>% + filter(!is.na(boundness_st)) %>% + filter(!is.na(informativity_st)) + +#dropping tips not in Grambank +metrics_joined <- metrics_joined[metrics_joined$Language_ID %in% tree$tip.label, ] +tree <- keep.tip(tree, metrics_joined$Language_ID) + +x <- assert_that(all(tree$tip.label %in% metrics_joined$Language_ID), msg = "The data and phylogeny taxa do not match") + +## Building standardized phylogenetic precision matrix +tree_scaled <- tree + +tree_vcv = vcv.phylo(tree_scaled) +typical_phylogenetic_variance = exp(mean(log(diag(tree_vcv)))) + +#We opt for a sparse phylogenetic precision matrix (i.e. it is quantified using all nodes and tips), since sparse matrices make the analysis in INLA less time-intensive +tree_scaled$edge.length <- tree_scaled$edge.length/typical_phylogenetic_variance +phylo_prec_mat <- MCMCglmm::inverseA(tree_scaled, + nodes = "ALL", + scale = FALSE)$Ainv + +metrics_joined = metrics_joined[order(match(metrics_joined$Language_ID, rownames(phylo_prec_mat))),] + +#"local" set of parameters +## Create spatial covariance matrix using the matern covariance function +spatial_covar_mat_1 = varcov.spatial(metrics_joined[,c("Longitude", "Latitude")], + cov.pars = phi_1, kappa = kappa)$varcov +# Calculate and standardize by the typical variance +typical_variance_spatial_1 = exp(mean(log(diag(spatial_covar_mat_1)))) +spatial_cov_std_1 = spatial_covar_mat_1 / typical_variance_spatial_1 +spatial_prec_mat_1 = solve(spatial_cov_std_1) +dimnames(spatial_prec_mat_1) = list(metrics_joined$Language_ID, metrics_joined$Language_ID) + +#"regional" set of parameters +spatial_covar_mat_2 = varcov.spatial(metrics_joined[,c("Longitude", "Latitude")], cov.pars = phi_2, kappa = kappa)$varcov +typical_variance_spatial_2 = exp(mean(log(diag(spatial_covar_mat_2)))) +spatial_cov_std_2 = spatial_covar_mat_2 / typical_variance_spatial_2 +spatial_prec_mat_2 = solve(spatial_cov_std_2) +dimnames(spatial_prec_mat_2) = list(metrics_joined$Language_ID, metrics_joined$Language_ID) + +## Since we are using a sparse phylogenetic matrix, we are matching taxa to rows in the matrix +phy_id = match(tree$tip.label, rownames(phylo_prec_mat)) +metrics_joined$phy_id = phy_id + +## Other effects are in the same order they appear in the dataset +metrics_joined$sp_id = 1:nrow(spatial_prec_mat_1) + +#Preparing the formulas for 7 competing models to be used in inla() call +listcombo <- list(#phylogenetic and spatial effects in isolation + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper)"), + c("f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper)"), + c("f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_2, constr = TRUE, hyper = pcprior_hyper)"), + c("f(AUTOTYP_area, model = 'iid', hyper = pcprior_hyper)"), + #phylogenetic and distinct spatial effects in combination + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper)", + "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper)"), + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper)", + "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_2, constr = TRUE, hyper = pcprior_hyper)"), + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper)", + "f(AUTOTYP_area, model = 'iid', hyper = pcprior_hyper)")) + +predterms <- lapply(listcombo, function(x) paste(x, collapse="+")) + +predterms <- t(as.data.frame(predterms)) + +predterms_short <- predterms +predterms_short <- gsub("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper)", "Phylogenetic", predterms_short, fixed=TRUE) +predterms_short <- gsub("f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper)", "Spatial: local", predterms_short, fixed=TRUE) +predterms_short <- gsub("f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_2, constr = TRUE, hyper = pcprior_hyper)", "Spatial: regional", predterms_short, fixed=TRUE) +predterms_short <- gsub("f(AUTOTYP_area, model = 'iid', hyper = pcprior_hyper)", "Areal", predterms_short, fixed=TRUE) + +phylogenetic_element <- data.frame("judgement" = grepl("Phylogenetic", predterms_short), + number = 1:length(predterms_short)) +phylogenetic_element <- phylogenetic_element[phylogenetic_element$judgement == TRUE,]$number + +spatial_element_local <- data.frame("judgement" = grepl("local", predterms_short), + number = 1:length(predterms_short)) +spatial_element_local <- spatial_element_local[spatial_element_local$judgement == TRUE,]$number + +spatial_element_regional <- data.frame("judgement" = grepl("regional", predterms_short), + number = 1:length(predterms_short)) +spatial_element_regional <- spatial_element_regional[spatial_element_regional$judgement == TRUE,]$number + +spatial_element <- c(spatial_element_local, spatial_element_regional) + +areal_element <- data.frame("judgement" = grepl("Areal", predterms_short), + number = 1:length(predterms_short)) +areal_element <- areal_element[areal_element$judgement == TRUE,]$number + + +#preparing empty matrices to be filled with effect estimates (quantiles), model name, and WAIC value +phy_effects_matrix <- matrix(NA, 7, 5) +colnames(phy_effects_matrix) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +spa_effects_matrix <- matrix(NA, 7, 5) +colnames(spa_effects_matrix) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +area_effects_matrix <- matrix(NA, 7, 5) +colnames(area_effects_matrix) <- c("2.5%", "50%", "97.5%", "model", "WAIC") + +intercept_matrix <- matrix(NA, 7, 5) +colnames(intercept_matrix) <- c("2.5%", "50%", "97.5%", "model", "WAIC") + +#fitted values +fitted_list <- vector("list", 7) +names(fitted_list) <- predterms_short + +#marginals of hyperparameters +marginals_hyperpar_list_gaussian <- vector("list", 7) +names(marginals_hyperpar_list_gaussian) <- predterms_short + +marginals_hyperpar_list_phy <- vector("list", 7) +names(marginals_hyperpar_list_phy) <- predterms_short + +marginals_hyperpar_list_spa <- vector("list", 7) +names(marginals_hyperpar_list_spa) <- predterms_short + +marginals_hyperpar_list_area <- vector("list", 7) +names(marginals_hyperpar_list_area) <- predterms_short + + +#marginals of fixed effects +marginals_fixed_list_Intercept <- vector("list", 7) +names(marginals_fixed_list_Intercept) <- predterms_short + + +#summary statistics of random effects +summary_random_list_phy <- vector("list", 7) +names(summary_random_list_phy) <- predterms_short + +summary_random_list_spa <- vector("list", 7) +names(summary_random_list_spa) <- predterms_short + +summary_random_list_area <- vector("list", 7) +names(summary_random_list_area) <- predterms_short + +coefm <- matrix(NA,7,1) +result <- vector("list",7) + +for(i in 1:7){ + formula <- as.formula(paste("informativity_st ~ ",predterms[[i]])) + result[[i]] <- inla(formula, family="gaussian", + control.family = list(hyper = pcprior_hyper), + #control.inla = list(tolerance = 1e-8, h = 0.0001), + #tolerance: the tolerance for the optimisation of the hyperparameters + #h: the step-length for the gradient calculations for the hyperparameters. + data=metrics_joined, control.compute=list(waic=TRUE)) + + coefm[i,1] <- round(result[[i]]$waic$waic, 2) + + intercept_matrix[i, 1:3] <- c(result[[i]]$summary.fixed[1,]$`0.025quant`, result[[i]]$summary.fixed[1,]$`0.5quant`, result[[i]]$summary.fixed[1,]$`0.975quant`) + intercept_matrix[i, 4] <- predterms_short[[i]] + intercept_matrix[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_Intercept[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["(Intercept)"]])) + colnames(marginals_fixed_list_Intercept[[i]]) <- c("x for Intercept", "y for Intercept") + + if(i %in% phylogenetic_element) { + phy_effects_matrix[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for phy_id`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + phy_effects_matrix[i, 4] <- predterms_short[[i]] + phy_effects_matrix[i, 5] <- result[[i]]$waic$waic + } + + if(i %in% spatial_element) { + spa_effects_matrix[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for sp_id`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + spa_effects_matrix[i, 4] <- predterms_short[[i]] + spa_effects_matrix[i, 5] <- result[[i]]$waic$waic + } + + if(i %in% areal_element){ + area_effects_matrix[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for AUTOTYP_area`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + area_effects_matrix[i, 4] <- predterms_short[[i]] + area_effects_matrix[i, 5] <- result[[i]]$waic$waic + } + + fitted_list[[i]] <- result[[i]]$summary.fitted.values + fitted_list[[i]] <- fitted_list[[i]] %>% + mutate(across(where(is.numeric), round, 2)) + + marginals_hyperpar_list_gaussian[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for the Gaussian observations"]])) + colnames(marginals_hyperpar_list_gaussian[[i]]) <- c("x for the Gaussian observations", "y for the Gaussian observations") + + if(i %in% phylogenetic_element){ + marginals_hyperpar_list_phy[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for phy_id"]])) + colnames(marginals_hyperpar_list_phy[[i]]) <- c("x for phy_id", "y for phy_id") + } + + if(i %in% spatial_element){ + marginals_hyperpar_list_spa[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for sp_id"]])) + colnames(marginals_hyperpar_list_spa[[i]]) <- c("x for sp_id", "y for sp_id") + } + + if(i %in% areal_element){ + marginals_hyperpar_list_area[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for AUTOTYP_area"]])) + colnames(marginals_hyperpar_list_area[[i]]) <- c("x for AUTOTYP_area", "y for AUTOTYP_area") + } + + if(i %in% phylogenetic_element){ + summary_random_list_phy[[i]] <- cbind(result[[i]]$summary.random$phy_id) %>% + rename(phy_id = ID) %>% + as.data.frame() %>% + mutate(across(where(is.numeric), round, 2)) + } + + if(i %in% spatial_element){ + summary_random_list_spa[[i]] <- cbind(result[[i]]$summary.random$sp_id) %>% + rename(sp_id = ID) %>% + as.data.frame() %>% + mutate(across(where(is.numeric), round, 2)) + } + + if(i %in% areal_element){ + summary_random_list_area[[i]] <- cbind(result[[i]]$summary.random$AUTOTYP_area) %>% + rename(AUTOTYP_area = ID) %>% + as.data.frame() %>% + mutate(across(where(is.numeric), round, 2)) + } +} + +#beepr::beep(5) + +save(result, file = "output_models/models_Informativity_phylogenetic_spatial.RData") + +coefm <- as.data.frame(cbind(predterms_short, coefm)) +colnames(coefm) <- c("model", "WAIC") +coefm <- coefm %>% + mutate(across(.cols=2, as.numeric)) %>% + mutate(across(where(is.numeric), round, 2)) %>% + arrange(WAIC) + +coefm$WAIC <- as.numeric(coefm$WAIC) +coefm <- coefm[order(coefm$WAIC),] + +coefm_path <- paste("output_tables/", "waics", "Informativity_phylogenetic_spatial_models", ".csv", collapse = "") +write.csv(coefm, coefm_path, row.names=FALSE) + +for (i in 1:length(fitted_list)) { + fitted_list[[i]]$model <- names(fitted_list)[i] +} +fitted_list <- dplyr::bind_rows(fitted_list) +fitted_list_path <- paste("output_tables/", "fitted_list", "Informativity_phylogenetic_spatial_models", ".csv", collapse = "") +write.csv(fitted_list, fitted_list_path) + +phy_effects<-as.data.frame(phy_effects_matrix) +spa_effects<-as.data.frame(spa_effects_matrix) +area_effects <- as.data.frame(area_effects_matrix) +intercept_effects <- as.data.frame(intercept_matrix) + +phy_effects$effect <- "phylogenetic SD" +spa_effects$effect <- "spatial SD" +area_effects$effect <- "areal SD" +intercept_effects$effect <- "Intercept" + +effs <- as.data.frame(rbind(phy_effects, spa_effects, area_effects, intercept_effects)) +effs <- effs %>% + mutate(across(.cols=c(1:3, 5), as.numeric)) %>% + mutate(across(where(is.numeric), round, 2)) %>% + na.omit() %>% + arrange(WAIC) %>% + relocate(model) + +effs_path <- paste("output_tables/", "effects", "Informativity_phylogenetic_spatial_models", ".csv", collapse = "") +write.csv(effs, effs_path, row.names=FALSE) + +effs <- read.csv("output_tables/ effects Informativity_phylogenetic_spatial_models .csv") + +effs_table_SM <- effs %>% + mutate(effect = + dplyr::recode(effect, + "areal SD" = "spatial SD")) %>% + rename("2.5%"=2, + "50%" = 4, + "97.5%" = 3) %>% + flextable() %>% + autofit() %>% + merge_v(j=c("model", "WAIC")) %>% + fix_border_issues() %>% + border_inner_h() + +save_as_docx( + "Effects in informativity models with random effects" = effs_table_SM, + path = "output_tables/table_SM_effects_Informativity_phylogenetic_spatial_models.docx") + + +effs_plot <- effs %>% + #filter(WAIC <= top_9) %>% + rename(lower=2, + upper = 4, + mean = 3) %>% #mean here refers to 0.5 quantile + #filter(!effect == "Intercept") %>% + mutate(effect = + dplyr::recode(effect, + "areal SD" = "spatial SD")) %>% + mutate(effect = factor(effect, levels=c("phylogenetic SD", "spatial SD", "areal SD", "Intercept"))) %>% + mutate(WAIC = round(WAIC, 2)) %>% + unite("model", model, WAIC, sep = ",\nWAIC: ", remove=FALSE) %>% + group_by(WAIC) %>% + arrange(WAIC) %>% + mutate(model = forcats::fct_reorder(as.factor(model), WAIC)) %>% #reordering levels within model based on WAIC values + mutate(model = factor(model, levels=rev(levels(model)))) #reversing the order + + + +#plot modified from function ggregplot::Efxplot +cols = c(brewer.pal(12, "Paired")) +cols = c(cols[c(12, 10)], "gray50") + +show_col(cols) + +plot_1 <- ggplot(effs_plot, + aes(y = as.factor(model), + x = mean, + group = effect, + colour = effect)) + + geom_pointrangeh(aes(xmin = lower, xmax = upper), position = position_dodge(w = 0.9), size = 1.5) + + geom_vline(aes(xintercept = 0),lty = 2) + labs(x = NULL) + #coord_flip() + + scale_color_manual(values=cols) + + ylab("Model of informativity") + xlab("Estimate") + labs(color = "Effect") + theme_classic() + + theme(axis.text=element_text(size=50), + legend.text=element_text(size=50), + axis.title=element_text(size=50), + legend.title=element_text(size=50), + legend.spacing.y = unit(1.5, 'cm')) + + guides(color = guide_legend(reverse = TRUE, byrow = TRUE)) + + + +#plot_1 +ggsave(filename = 'output/SP_models_plot_Informativity_phylogenetic_spatial_models.jpg', + plot_1, height = 29, width = 33) + + +#saving hyperparameters: Gaussian observations +for (i in 1:length(marginals_hyperpar_list_gaussian)) { + marginals_hyperpar_list_gaussian[[i]]$model <- names(marginals_hyperpar_list_gaussian)[i] +} +marginals_hyperpar_list_gaussian <- dplyr::bind_rows(marginals_hyperpar_list_gaussian) + +write.csv(marginals_hyperpar_list_gaussian, "output_tables/Informativity_phylogenetic_spatial_models_marginals_hyperpar_gaussian.csv") + +#saving hyperparameters: phylogenetic +for (i in 1:length(marginals_hyperpar_list_phy)) { + marginals_hyperpar_list_phy[[i]]$model <- names(marginals_hyperpar_list_phy)[i] +} +marginals_hyperpar_list_phy <- dplyr::bind_rows(marginals_hyperpar_list_phy) + +write.csv(marginals_hyperpar_list_phy, "output_tables/Informativity_phylogenetic_spatial_models_marginals_hyperpar_phylogenetic.csv") + +#saving hyperparameters: spatial +for (i in 1:length(marginals_hyperpar_list_spa)) { + marginals_hyperpar_list_spa[[i]]$model <- names(marginals_hyperpar_list_spa)[i] +} +marginals_hyperpar_list_spa <- dplyr::bind_rows(marginals_hyperpar_list_spa) + +write.csv(marginals_hyperpar_list_spa, "output_tables/Informativity_phylogenetic_spatial_models_marginals_hyperpar_spatial.csv") + +#saving hyperparameters: areas +for (i in 1:length(marginals_hyperpar_list_area)) { + marginals_hyperpar_list_area[[i]]$model <- names(marginals_hyperpar_list_area)[i] +} +marginals_hyperpar_list_area <- dplyr::bind_rows(marginals_hyperpar_list_area) + +write.csv(marginals_hyperpar_list_area, "output_tables/Informativity_phylogenetic_spatial_models_marginals_hyperpar_areal.csv") + + +#saving summaries of random effects: phylogenetic +for (i in 1:length(summary_random_list_phy)) { + summary_random_list_phy[[i]]$model <- names(summary_random_list_phy)[i] +} +summary_random_list_phy <- dplyr::bind_rows(summary_random_list_phy) + +write.csv(summary_random_list_phy, "output_tables/Informativity_phylogenetic_spatial_models_summary_random_phy.csv") + +#saving summaries of random effects: spatial +for (i in 1:length(summary_random_list_spa)) { + summary_random_list_spa[[i]]$model <- names(summary_random_list_spa)[i] +} +summary_random_list_spa <- dplyr::bind_rows(summary_random_list_spa) + +write.csv(summary_random_list_spa, "output_tables/Informativity_phylogenetic_spatial_models_summary_random_spa.csv") + +#saving summaries of random effects: areas +for (i in 1:length(summary_random_list_area)) { + summary_random_list_area[[i]]$model <- names(summary_random_list_area)[i] +} +summary_random_list_area <- dplyr::bind_rows(summary_random_list_area) + +write.csv(summary_random_list_area, "output_tables/Informativity_phylogenetic_spatial_models_summary_random_areas.csv") diff --git a/101/replication_package/models_Informativity_reduced_social.R b/101/replication_package/models_Informativity_reduced_social.R new file mode 100644 index 0000000000000000000000000000000000000000..e3ae0b73dc390a31cad33ef29457ac65a0009ea8 --- /dev/null +++ b/101/replication_package/models_Informativity_reduced_social.R @@ -0,0 +1,537 @@ +#model fitting: Informativity predicted by social effects on top of random phylogenetic and spatial factors + +#Script was written by Sam Passmore and modified by Olena Shcherbakova + +source("requirements.R") + +source("install_and_load_INLA.R") + +source("set_up_inla.R") + +metrics_joined <- metrics_joined %>% + filter(!is.na(L1_log10_st)) %>% + rename(L1_log_st = L1_log10_st) %>% + mutate(L1_copy = L1_log_st) %>% + filter(!is.na(L2_prop)) %>% + mutate(L2_copy = L2_prop) %>% + filter(!is.na(neighboring_languages_st)) %>% + filter(!is.na(Official)) %>% + filter(!is.na(Education)) %>% + filter(!is.na(boundness_st)) %>% + filter(!is.na(informativity_st)) + +#dropping tips not in Grambank +metrics_joined <- metrics_joined[metrics_joined$Language_ID %in% tree$tip.label, ] +tree <- keep.tip(tree, metrics_joined$Language_ID) + +x <- assert_that(all(tree$tip.label %in% metrics_joined$Language_ID), msg = "The data and phylogeny taxa do not match") + +## Building standardized phylogenetic precision matrix +tree_scaled <- tree + +tree_vcv = vcv.phylo(tree_scaled) +typical_phylogenetic_variance = exp(mean(log(diag(tree_vcv)))) + +#We opt for a sparse phylogenetic precision matrix (i.e. it is quantified using all nodes and tips), since sparse matrices make the analysis in INLA less time-intensive +tree_scaled$edge.length <- tree_scaled$edge.length/typical_phylogenetic_variance +phylo_prec_mat <- MCMCglmm::inverseA(tree_scaled, + nodes = "ALL", + scale = FALSE)$Ainv + +metrics_joined = metrics_joined[order(match(metrics_joined$Language_ID, rownames(phylo_prec_mat))),] + +#"local" set of parameters +## Create spatial covariance matrix using the matern covariance function +spatial_covar_mat_1 = varcov.spatial(metrics_joined[,c("Longitude", "Latitude")], + cov.pars = phi_1, kappa = kappa)$varcov +# Calculate and standardize by the typical variance +typical_variance_spatial_1 = exp(mean(log(diag(spatial_covar_mat_1)))) +spatial_cov_std_1 = spatial_covar_mat_1 / typical_variance_spatial_1 +spatial_prec_mat_1 = solve(spatial_cov_std_1) +dimnames(spatial_prec_mat_1) = list(metrics_joined$Language_ID, metrics_joined$Language_ID) + +## Since we are using a sparse phylogenetic matrix, we are matching taxa to rows in the matrix +phy_id = match(tree$tip.label, rownames(phylo_prec_mat)) +metrics_joined$phy_id = phy_id + +## Other effects are in the same order they appear in the dataset +metrics_joined$sp_id = 1:nrow(spatial_prec_mat_1) + +#Preparing the formulas for 10 competing models to be used in inla() call +listcombo <- list( + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper)", "L1_log_st"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper)", "f(inla.group(L1_copy), model='rw2', scale.model = TRUE)"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper)", "L2_prop"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper)", "f(inla.group(L2_copy), model='rw2', scale.model = TRUE)"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper)", "f(inla.group(L1_copy), model='rw2', scale.model = TRUE)", "f(inla.group(L2_copy), model='rw2', scale.model = TRUE)"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper)", "L1_log_st", "L2_prop"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper)", "neighboring_languages_st"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper)", "Official"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper)", "Education")) + + +predterms <- lapply(listcombo, function(x) paste(x, collapse="+")) + +predterms <- t(as.data.frame(predterms)) + +predterms_short <- predterms +predterms_short <- gsub("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper)", "Phylogenetic", predterms_short, fixed=TRUE) +predterms_short <- gsub("f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper)", "Spatial: local", predterms_short, fixed=TRUE) + +predterms_short <- gsub("f(inla.group(L1_copy), model='rw2', scale.model = TRUE)", "L1 speakers (nonlinear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("L1_log_st", "L1 speakers (linear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("f(inla.group(L2_copy), model='rw2', scale.model = TRUE)", "L2 proportion (nonlinear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("L2_prop", "L2 proportion (linear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("neighboring_languages_st", "Neighbours", predterms_short, fixed=TRUE) + + +phylogenetic_element <- data.frame("judgement" = grepl("Phylogenetic", predterms_short), + number = 1:length(predterms_short)) +phylogenetic_element <- phylogenetic_element[phylogenetic_element$judgement == TRUE,]$number + +spatial_element_local <- data.frame("judgement" = grepl("local", predterms_short), + number = 1:length(predterms_short)) +spatial_element_local <- spatial_element_local[spatial_element_local$judgement == TRUE,]$number + +spatial_element_regional <- data.frame("judgement" = grepl("regional", predterms_short), + number = 1:length(predterms_short)) +spatial_element_regional <- spatial_element_regional[spatial_element_regional$judgement == TRUE,]$number + +spatial_element <- c(spatial_element_local, spatial_element_regional) + +L1_element <- data.frame("judgement" = grepl("L1 speakers (linear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L1_element <- L1_element[L1_element$judgement == TRUE,]$number + + +L1_nl_element <- data.frame("judgement" = grepl("L1 speakers (nonlinear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L1_nl_element <- L1_nl_element[L1_nl_element$judgement == TRUE,]$number + +L2_prop_element <- data.frame("judgement" = grepl("L2 proportion (linear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L2_prop_element <- L2_prop_element[L2_prop_element$judgement == TRUE,]$number + +L2_prop_nl_element <- data.frame("judgement" = grepl("L2 proportion (nonlinear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L2_prop_nl_element <- L2_prop_nl_element[L2_prop_nl_element$judgement == TRUE,]$number + +neighbour_element <- data.frame("judgement" = grepl("Neighbours", predterms_short), + number = 1:length(predterms_short)) +neighbour_element <- neighbour_element[neighbour_element$judgement == TRUE,]$number + +official_element <- data.frame("judgement" = grepl("Official", predterms_short), + number = 1:length(predterms_short)) +official_element <- official_element[official_element$judgement == TRUE,]$number + +education_element <- data.frame("judgement" = grepl("Education", predterms_short), + number = 1:length(predterms_short)) +education_element <- education_element[education_element$judgement == TRUE,]$number + +models_number <- length(predterms_short) + +#preparing empty matrices to be filled with effect estimates (quantiles), model name, and WAIC value +phy_effects_matrix <- matrix(NA, models_number, 5) +colnames(phy_effects_matrix) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +spa_effects_matrix <- matrix(NA, models_number, 5) +colnames(spa_effects_matrix) <- c("2.5%", "50%", "97.5%", "model", "WAIC") + +intercept_matrix <- matrix(NA, models_number, 5) +colnames(intercept_matrix) <- c("2.5%", "50%", "97.5%", "model", "WAIC") + +social_effects_matrix_L1 <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_L1) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L1_nl <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_L1_nl) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L2_prop <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_L2_prop) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L2_prop_nl <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_L2_prop_nl) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_N <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_N) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_O <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_O) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_E <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_E) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L1_L2_prop <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_L1_L2_prop) <- c("2.5%", "50%", "97.5%", "model", "WAIC") + +#fitted values +fitted_list <- vector("list", models_number) +names(fitted_list) <- predterms_short + +#marginals of hyperparameters +marginals_hyperpar_list_gaussian <- vector("list", models_number) +names(marginals_hyperpar_list_gaussian) <- predterms_short + +marginals_hyperpar_list_phy <- vector("list", models_number) +names(marginals_hyperpar_list_phy) <- predterms_short + +marginals_hyperpar_list_spa <- vector("list", models_number) +names(marginals_hyperpar_list_spa) <- predterms_short + +marginals_hyperpar_list_social_L1_nl <- vector("list", models_number) +names(marginals_hyperpar_list_social_L1_nl) <- predterms_short + +marginals_hyperpar_list_social_L2_prop_nl <- vector("list", models_number) +names(marginals_hyperpar_list_social_L2_prop_nl) <- predterms_short + + +#marginals of fixed effects +marginals_fixed_list_Intercept <- vector("list", models_number) +names(marginals_fixed_list_Intercept) <- predterms_short + +marginals_fixed_list_L1 <- vector("list", models_number) +names(marginals_fixed_list_L1) <- predterms_short + +marginals_fixed_list_L2_prop <- vector("list", models_number) +names(marginals_fixed_list_L2_prop) <- predterms_short + +marginals_fixed_list_O <- vector("list", models_number) +names(marginals_fixed_list_O) <- predterms_short + +marginals_fixed_list_N <- vector("list", models_number) +names(marginals_fixed_list_N) <- predterms_short + +marginals_fixed_list_E <- vector("list", models_number) +names(marginals_fixed_list_E) <- predterms_short + +marginals_fixed_list_L1_L2_prop <- vector("list", models_number) +names(marginals_fixed_list_L1_L2_prop) <- predterms_short + + + + +#summary statistics of random effects +summary_random_list_phy <- vector("list", models_number) +names(summary_random_list_phy) <- predterms_short + +summary_random_list_spa <- vector("list", models_number) +names(summary_random_list_spa) <- predterms_short + +summary_random_list_social_L1_nl <- vector("list", models_number) +names(summary_random_list_social_L1_nl) <- predterms_short + +summary_random_list_social_L2_prop_nl <- vector("list", models_number) +names(summary_random_list_social_L2_prop_nl) <- predterms_short + + +coefm <- matrix(NA,models_number,1) +result <- vector("list",models_number) + +for(i in 1:models_number){ + formula <- as.formula(paste("informativity_st ~ ",predterms[[i]])) + result[[i]] <- inla(formula, family="gaussian", + control.family = list(hyper = pcprior_hyper), + #control.inla = list(tolerance = 1e-8, h = 0.0001), + #tolerance: the tolerance for the optimisation of the hyperparameters + #h: the step-length for the gradient calculations for the hyperparameters. + data=metrics_joined, control.compute=list(waic=TRUE)) + + coefm[i,1] <- round(result[[i]]$waic$waic, 2) + + intercept_matrix[i, 1:3] <- c(result[[i]]$summary.fixed[1,]$`0.025quant`, result[[i]]$summary.fixed[1,]$`0.5quant`, result[[i]]$summary.fixed[1,]$`0.975quant`) + intercept_matrix[i, 4] <- predterms_short[[i]] + intercept_matrix[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_Intercept[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["(Intercept)"]])) + colnames(marginals_fixed_list_Intercept[[i]]) <- c("x for Intercept", "y for Intercept") + + if(i %in% phylogenetic_element) { + phy_effects_matrix[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for phy_id`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + phy_effects_matrix[i, 4] <- predterms_short[[i]] + phy_effects_matrix[i, 5] <- result[[i]]$waic$waic + } + + if(i %in% spatial_element) { + spa_effects_matrix[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for sp_id`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + spa_effects_matrix[i, 4] <- predterms_short[[i]] + spa_effects_matrix[i, 5] <- result[[i]]$waic$waic + } + + + if(i %in% L1_nl_element){ + social_effects_matrix_L1_nl[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for inla.group(L1_copy)`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + social_effects_matrix_L1_nl[i, 4] <- predterms_short[[i]] + social_effects_matrix_L1_nl[i, 5] <- result[[i]]$waic$waic + } + + if(i %in% L2_prop_nl_element){ + social_effects_matrix_L2_prop_nl[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for inla.group(L2_copy)`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + social_effects_matrix_L2_prop_nl[i, 4] <- predterms_short[[i]] + social_effects_matrix_L2_prop_nl[i, 5] <- result[[i]]$waic$waic + } + + if(i %in% L1_element) { + social_effects_matrix_L1[i, 1:3] <- c(result[[i]]$summary.fixed["L1_log_st",]$`0.025quant`, result[[i]]$summary.fixed["L1_log_st",]$`0.5quant`, result[[i]]$summary.fixed["L1_log_st",]$`0.975quant`) + social_effects_matrix_L1[i, 4] <- predterms_short[[i]] + social_effects_matrix_L1[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_L1[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["L1_log_st"]])) + colnames(marginals_fixed_list_L1[[i]]) <- c("x for L1", "y for L1") + } + + if(i %in% L2_prop_element) { + social_effects_matrix_L2_prop[i, 1:3] <- c(result[[i]]$summary.fixed["L2_prop",]$`0.025quant`, result[[i]]$summary.fixed["L2_prop",]$`0.5quant`, result[[i]]$summary.fixed["L2_prop",]$`0.975quant`) + social_effects_matrix_L2_prop[i, 4] <- predterms_short[[i]] + social_effects_matrix_L2_prop[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_L2_prop[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["L2_prop"]])) + colnames(marginals_fixed_list_L2_prop[[i]]) <- c("x for L2 proportion", "y for L2 proportion") + } + + if(i %in% neighbour_element) { + social_effects_matrix_N[i, 1:3] <- c(result[[i]]$summary.fixed[2,]$`0.025quant`, result[[i]]$summary.fixed[2,]$`0.5quant`, result[[i]]$summary.fixed[2,]$`0.975quant`) + social_effects_matrix_N[i, 4] <- predterms_short[[i]] + social_effects_matrix_N[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_N[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][[2]])) + colnames(marginals_fixed_list_N[[i]]) <- c("x for Neighbours", "y for Neighbours") + } + + if(i %in% official_element) { + social_effects_matrix_O[i, 1:3] <- c(result[[i]]$summary.fixed[2,]$`0.025quant`, result[[i]]$summary.fixed[2,]$`0.5quant`, result[[i]]$summary.fixed[2,]$`0.975quant`) + social_effects_matrix_O[i, 4] <- predterms_short[[i]] + social_effects_matrix_O[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_O[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][[2]])) + colnames(marginals_fixed_list_O[[i]]) <- c("x for Official", "y for Official") + } + + if(i %in% education_element) { + social_effects_matrix_E[i, 1:3] <- c(result[[i]]$summary.fixed[2,]$`0.025quant`, result[[i]]$summary.fixed[2,]$`0.5quant`, result[[i]]$summary.fixed[2,]$`0.975quant`) + social_effects_matrix_E[i, 4] <- predterms_short[[i]] + social_effects_matrix_E[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_E[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][[2]])) + colnames(marginals_fixed_list_E[[i]]) <- c("x for Education", "y for Education") + } + + fitted_list[[i]] <- result[[i]]$summary.fitted.values + fitted_list[[i]] <- fitted_list[[i]] %>% + mutate(across(where(is.numeric), round, 2)) + + marginals_hyperpar_list_gaussian[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for the Gaussian observations"]])) + colnames(marginals_hyperpar_list_gaussian[[i]]) <- c("x for the Gaussian observations", "y for the Gaussian observations") + + if(i %in% phylogenetic_element){ + marginals_hyperpar_list_phy[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for phy_id"]])) + colnames(marginals_hyperpar_list_phy[[i]]) <- c("x for phy_id", "y for phy_id") + } + + if(i %in% spatial_element){ + marginals_hyperpar_list_spa[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for sp_id"]])) + colnames(marginals_hyperpar_list_spa[[i]]) <- c("x for sp_id", "y for sp_id") + } + + if(i %in% L1_nl_element){ + marginals_hyperpar_list_social_L1_nl[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for inla.group(L1_copy)"]])) + colnames(marginals_hyperpar_list_social_L1_nl[[i]]) <- c("x for inla.group(L1_copy)", "y for inla.group(L1_copy)") + } + + if(i %in% L2_prop_nl_element){ + marginals_hyperpar_list_social_L2_prop_nl[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for inla.group(L2_copy)"]])) + colnames(marginals_hyperpar_list_social_L2_prop_nl[[i]]) <- c("x for inla.group(L2_copy)", "y for inla.group(L2_copy)") + } + + if(i %in% phylogenetic_element){ + summary_random_list_phy[[i]] <- cbind(result[[i]]$summary.random$phy_id) %>% + rename(phy_id = ID) %>% + as.data.frame() %>% + mutate(across(where(is.numeric), round, 2)) + } + + if(i %in% spatial_element){ + summary_random_list_spa[[i]] <- cbind(result[[i]]$summary.random$sp_id) %>% + rename(sp_id = ID) %>% + as.data.frame() %>% + mutate(across(where(is.numeric), round, 2)) + } +} + +#beepr::beep(5) + +save(result, file = "output_models_reduced/models_Informativity_social.RData") + + +coefm <- as.data.frame(cbind(predterms_short, coefm)) +colnames(coefm) <- c("model", "WAIC") +coefm <- coefm %>% + mutate(across(.cols=2, as.numeric)) %>% + mutate(across(where(is.numeric), round, 2)) %>% + arrange(WAIC) + +coefm$WAIC <- as.numeric(coefm$WAIC) +coefm <- coefm[order(coefm$WAIC),] + +coefm_path <- paste("output_tables_reduced/", "waics", "Informativity_social_models", ".csv", collapse = "") +write.csv(coefm, coefm_path, row.names=FALSE) + +for (i in 1:length(fitted_list)) { + fitted_list[[i]]$model <- names(fitted_list)[i] +} +fitted_list <- dplyr::bind_rows(fitted_list) +fitted_list_path <- paste("output_tables_reduced/", "fitted_list", "Informativity_social_models", ".csv", collapse = "") +write.csv(fitted_list, fitted_list_path) + +phy_effects<-as.data.frame(phy_effects_matrix) +spa_effects<-as.data.frame(spa_effects_matrix) +intercept_effects <- as.data.frame(intercept_matrix) +L1_effects <- as.data.frame(social_effects_matrix_L1) +L1_nl_effects <- as.data.frame(social_effects_matrix_L1_nl) +L2_prop_effects <- as.data.frame(social_effects_matrix_L2_prop) +L2_prop_nl_effects <- as.data.frame(social_effects_matrix_L2_prop_nl) +N_effects<-as.data.frame(social_effects_matrix_N) +E_effects<-as.data.frame(social_effects_matrix_E) +O_effects<-as.data.frame(social_effects_matrix_O) + +phy_effects$effect <- "phylogenetic SD" +spa_effects$effect <- "spatial SD" +intercept_effects$effect <- "Intercept" +L1_effects$effect <- "L1" +L1_nl_effects$effect <- "social SD:\nL1" +L2_prop_effects$effect <- "L2 proportion" +L2_prop_nl_effects$effect <- "social SD:\nL2 proportion" +N_effects$effect <- "Neighbours" +E_effects$effect <- "Education" +O_effects$effect <- "Official status" + +effs <- as.data.frame(rbind(phy_effects, spa_effects, intercept_effects, L1_effects, L1_nl_effects, L2_prop_effects, L2_prop_nl_effects, N_effects, O_effects, E_effects)) +effs <- effs %>% + mutate(across(.cols=c(1:3, 5), as.numeric)) %>% + mutate(across(where(is.numeric), round, 2)) %>% + na.omit() %>% + arrange(WAIC) %>% + relocate(model) + +effs_path <- paste("output_tables_reduced/", "effects", "Informativity_social_models", ".csv", collapse = "") +write.csv(effs, effs_path, row.names=FALSE) + +effs <- read.csv("output_tables_reduced/ effects Informativity_social_models .csv") + +effs_table_Main <- effs %>% + rename("2.5%"=2, + "50%" = 3, + "97.5%" = 4) %>% + filter(!grepl("nonlinear", model)) + +effs_table_Main$model <- gsub("(\\s*\\(\\w+\\))", "", effs_table_Main$model) + +effs_table_Main <- effs_table_Main %>% + relocate(effect, .after = model) %>% + flextable() %>% + flextable::bold(~ (`2.5%` > 0 & `97.5%` > 0) | (`2.5%` < 0 & `97.5%` < 0), 2) %>% + autofit() %>% + merge_v(j=c("model", "WAIC")) %>% + fix_border_issues() %>% + border_inner_h() + +save_as_docx( + "Effects in informativity models with fixed and random effects" = effs_table_Main, + path = "output_tables_reduced/table_Main_effects_Informativity_social_models.docx") + + +effs_plot <- effs %>% + #filter(WAIC <= top_9) %>% + rename(lower=2, + upper = 4, + mean = 3) %>% #mean here refers to 0.5 quantile + #filter(!effect == "Intercept") %>% + mutate(effect = factor(effect, levels=c("phylogenetic SD", "spatial SD", "Intercept", "social SD:\nL1", "L1", "social SD:\nL2 proportion", "L2 proportion", "Neighbours", "Education", "Official status"))) %>% + mutate(WAIC = round(WAIC, 2)) %>% + unite("model", model, WAIC, sep = ",\nWAIC: ", remove=FALSE) %>% + group_by(WAIC) %>% + arrange(WAIC) %>% + mutate(model = forcats::fct_reorder(as.factor(model), WAIC)) %>% #reordering levels within model based on WAIC values + mutate(model = factor(model, levels=rev(levels(model)))) #reversing the order + + +#plot modified from function ggregplot::Efxplot +cols = c(brewer.pal(12, "Paired")) +cols = c(cols[c(12, 10)], "gray50", cols[c(1:8)]) + +show_col(cols) + +plot_1 <- ggplot(effs_plot, + aes(y = as.factor(model), + x = mean, + group = effect, + colour = effect)) + + geom_pointrangeh(aes(xmin = lower, xmax = upper), position = position_dodge(w = 0.9), size = 1.5) + + geom_vline(aes(xintercept = 0),lty = 2) + labs(x = NULL) + #coord_flip() + + scale_color_manual(values=cols) + + ylab("Model of informativity") + xlab("Estimate") + labs(color = "Effect") + theme_classic() + + theme(axis.text=element_text(size=50), + legend.text=element_text(size=50), + axis.title=element_text(size=50), + legend.title=element_text(size=50), + legend.spacing.y = unit(1.5, 'cm')) + + guides(color = guide_legend(reverse = TRUE, byrow = TRUE)) + + + +#plot_1 +ggsave(filename = 'output_reduced/SP_models_plot_Informativity_social_models.jpg', + plot_1, height = 20, width = 45) + + +#saving hyperparameters: Gaussian observations +for (i in 1:length(marginals_hyperpar_list_gaussian)) { + marginals_hyperpar_list_gaussian[[i]]$model <- names(marginals_hyperpar_list_gaussian)[i] +} +marginals_hyperpar_list_gaussian <- dplyr::bind_rows(marginals_hyperpar_list_gaussian) + +write.csv(marginals_hyperpar_list_gaussian, "output_tables_reduced/Informativity_social_models_marginals_hyperpar_gaussian.csv") + +#saving hyperparameters: phylogenetic +for (i in 1:length(marginals_hyperpar_list_phy)) { + marginals_hyperpar_list_phy[[i]]$model <- names(marginals_hyperpar_list_phy)[i] +} +marginals_hyperpar_list_phy <- dplyr::bind_rows(marginals_hyperpar_list_phy) + +write.csv(marginals_hyperpar_list_phy, "output_tables_reduced/Informativity_social_models_marginals_hyperpar_phylogenetic.csv") + +#saving hyperparameters: spatial +for (i in 1:length(marginals_hyperpar_list_spa)) { + marginals_hyperpar_list_spa[[i]]$model <- names(marginals_hyperpar_list_spa)[i] +} +marginals_hyperpar_list_spa <- dplyr::bind_rows(marginals_hyperpar_list_spa) + +write.csv(marginals_hyperpar_list_spa, "output_tables_reduced/Informativity_social_models_marginals_hyperpar_spatial.csv") + + +#saving summaries of random effects: phylogenetic +for (i in 1:length(summary_random_list_phy)) { + summary_random_list_phy[[i]]$model <- names(summary_random_list_phy)[i] +} +summary_random_list_phy <- dplyr::bind_rows(summary_random_list_phy) + +write.csv(summary_random_list_phy, "output_tables_reduced/Informativity_social_models_summary_random_phy.csv") + +#saving summaries of random effects: spatial +for (i in 1:length(summary_random_list_spa)) { + summary_random_list_spa[[i]]$model <- names(summary_random_list_spa)[i] +} +summary_random_list_spa <- dplyr::bind_rows(summary_random_list_spa) + +write.csv(summary_random_list_spa, "output_tables_reduced/Informativity_social_models_summary_random_spa.csv") diff --git a/101/replication_package/models_Informativity_reduced_social_only.R b/101/replication_package/models_Informativity_reduced_social_only.R new file mode 100644 index 0000000000000000000000000000000000000000..13c2bb8ad8a65b2c3f691a3538c29d6d646dce7f --- /dev/null +++ b/101/replication_package/models_Informativity_reduced_social_only.R @@ -0,0 +1,435 @@ +#model fitting: Informativity predicted by social effects on top of random phylogenetic and spatial factors + +#Script was written by Sam Passmore and modified by Olena Shcherbakova + +source("requirements.R") + +source("install_and_load_INLA.R") + +source("set_up_inla.R") + +metrics_joined <- metrics_joined %>% + filter(!is.na(L1_log10_st)) %>% + rename(L1_log_st = L1_log10_st) %>% + mutate(L1_copy = L1_log_st) %>% + filter(!is.na(L2_prop)) %>% + mutate(L2_copy = L2_prop) %>% + filter(!is.na(neighboring_languages_st)) %>% + filter(!is.na(Official)) %>% + filter(!is.na(Education)) %>% + filter(!is.na(boundness_st)) %>% + filter(!is.na(informativity_st)) + +#dropping tips not in Grambank +metrics_joined <- metrics_joined[metrics_joined$Language_ID %in% tree$tip.label, ] +tree <- keep.tip(tree, metrics_joined$Language_ID) + +x <- assert_that(all(tree$tip.label %in% metrics_joined$Language_ID), msg = "The data and phylogeny taxa do not match") + +## Building standardized phylogenetic precision matrix +tree_scaled <- tree + +tree_vcv = vcv.phylo(tree_scaled) +typical_phylogenetic_variance = exp(mean(log(diag(tree_vcv)))) + +#We opt for a sparse phylogenetic precision matrix (i.e. it is quantified using all nodes and tips), since sparse matrices make the analysis in INLA less time-intensive +tree_scaled$edge.length <- tree_scaled$edge.length/typical_phylogenetic_variance +phylo_prec_mat <- MCMCglmm::inverseA(tree_scaled, + nodes = "ALL", + scale = FALSE)$Ainv + +metrics_joined = metrics_joined[order(match(metrics_joined$Language_ID, rownames(phylo_prec_mat))),] + +#"local" set of parameters +## Create spatial covariance matrix using the matern covariance function +spatial_covar_mat_1 = varcov.spatial(metrics_joined[,c("Longitude", "Latitude")], + cov.pars = phi_1, kappa = kappa)$varcov +# Calculate and standardize by the typical variance +typical_variance_spatial_1 = exp(mean(log(diag(spatial_covar_mat_1)))) +spatial_cov_std_1 = spatial_covar_mat_1 / typical_variance_spatial_1 +spatial_prec_mat_1 = solve(spatial_cov_std_1) +dimnames(spatial_prec_mat_1) = list(metrics_joined$Language_ID, metrics_joined$Language_ID) + +## Since we are using a sparse phylogenetic matrix, we are matching taxa to rows in the matrix +phy_id = match(tree$tip.label, rownames(phylo_prec_mat)) +metrics_joined$phy_id = phy_id + +## Other effects are in the same order they appear in the dataset +metrics_joined$sp_id = 1:nrow(spatial_prec_mat_1) + +#Preparing the formulas for 10 competing models to be used in inla() call +listcombo <- list( + c("L1_log_st"), + + c("f(inla.group(L1_copy), model='rw2', scale.model = TRUE)"), + + c("L2_prop"), + + c("f(inla.group(L2_copy), model='rw2', scale.model = TRUE)"), + + c("f(inla.group(L1_copy), model='rw2', scale.model = TRUE)", "f(inla.group(L2_copy), model='rw2', scale.model = TRUE)"), + + c("L1_log_st", "L2_prop"), + + c("neighboring_languages_st"), + + c("Official"), + + c("Education")) + + +predterms <- lapply(listcombo, function(x) paste(x, collapse="+")) + +predterms <- t(as.data.frame(predterms)) + +predterms_short <- predterms + +predterms_short <- gsub("f(inla.group(L1_copy), model='rw2', scale.model = TRUE)", "L1 speakers (nonlinear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("L1_log_st", "L1 speakers (linear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("f(inla.group(L2_copy), model='rw2', scale.model = TRUE)", "L2 proportion (nonlinear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("L2_prop", "L2 proportion (linear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("neighboring_languages_st", "Neighbours", predterms_short, fixed=TRUE) + +L1_element <- data.frame("judgement" = grepl("L1 speakers (linear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L1_element <- L1_element[L1_element$judgement == TRUE,]$number + + +L1_nl_element <- data.frame("judgement" = grepl("L1 speakers (nonlinear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L1_nl_element <- L1_nl_element[L1_nl_element$judgement == TRUE,]$number + +L2_prop_element <- data.frame("judgement" = grepl("L2 proportion (linear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L2_prop_element <- L2_prop_element[L2_prop_element$judgement == TRUE,]$number + +L2_prop_nl_element <- data.frame("judgement" = grepl("L2 proportion (nonlinear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L2_prop_nl_element <- L2_prop_nl_element[L2_prop_nl_element$judgement == TRUE,]$number + +neighbour_element <- data.frame("judgement" = grepl("Neighbours", predterms_short), + number = 1:length(predterms_short)) +neighbour_element <- neighbour_element[neighbour_element$judgement == TRUE,]$number + +official_element <- data.frame("judgement" = grepl("Official", predterms_short), + number = 1:length(predterms_short)) +official_element <- official_element[official_element$judgement == TRUE,]$number + +education_element <- data.frame("judgement" = grepl("Education", predterms_short), + number = 1:length(predterms_short)) +education_element <- education_element[education_element$judgement == TRUE,]$number + +models_number <- length(predterms_short) + +#preparing empty matrices to be filled with effect estimates (quantiles), model name, and WAIC value +intercept_matrix <- matrix(NA, models_number, 5) +colnames(intercept_matrix) <- c("2.5%", "50%", "97.5%", "model", "WAIC") + +social_effects_matrix_L1 <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_L1) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L1_nl <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_L1_nl) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L2_prop <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_L2_prop) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L2_prop_nl <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_L2_prop_nl) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_N <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_N) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_O <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_O) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_E <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_E) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L1_L2_prop <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_L1_L2_prop) <- c("2.5%", "50%", "97.5%", "model", "WAIC") + +#fitted values +fitted_list <- vector("list", models_number) +names(fitted_list) <- predterms_short + +#marginals of hyperparameters +marginals_hyperpar_list_gaussian <- vector("list", models_number) +names(marginals_hyperpar_list_gaussian) <- predterms_short + +marginals_hyperpar_list_social_L1_nl <- vector("list", models_number) +names(marginals_hyperpar_list_social_L1_nl) <- predterms_short + +marginals_hyperpar_list_social_L2_prop_nl <- vector("list", models_number) +names(marginals_hyperpar_list_social_L2_prop_nl) <- predterms_short + + +#marginals of fixed effects +marginals_fixed_list_Intercept <- vector("list", models_number) +names(marginals_fixed_list_Intercept) <- predterms_short + +marginals_fixed_list_L1 <- vector("list", models_number) +names(marginals_fixed_list_L1) <- predterms_short + +marginals_fixed_list_L2_prop <- vector("list", models_number) +names(marginals_fixed_list_L2_prop) <- predterms_short + +marginals_fixed_list_O <- vector("list", models_number) +names(marginals_fixed_list_O) <- predterms_short + +marginals_fixed_list_N <- vector("list", models_number) +names(marginals_fixed_list_N) <- predterms_short + +marginals_fixed_list_E <- vector("list", models_number) +names(marginals_fixed_list_E) <- predterms_short + +marginals_fixed_list_L1_L2_prop <- vector("list", models_number) +names(marginals_fixed_list_L1_L2_prop) <- predterms_short + + + + +#summary statistics of random effects +summary_random_list_social_L1_nl <- vector("list", models_number) +names(summary_random_list_social_L1_nl) <- predterms_short + +summary_random_list_social_L2_prop_nl <- vector("list", models_number) +names(summary_random_list_social_L2_prop_nl) <- predterms_short + + +coefm <- matrix(NA,models_number,1) +result <- vector("list",models_number) + +for(i in 1:models_number){ + formula <- as.formula(paste("informativity_st ~ ",predterms[[i]])) + result[[i]] <- inla(formula, family="gaussian", + control.family = list(hyper = pcprior_hyper), + #control.inla = list(tolerance = 1e-8, h = 0.0001), + #tolerance: the tolerance for the optimisation of the hyperparameters + #h: the step-length for the gradient calculations for the hyperparameters. + data=metrics_joined, control.compute=list(waic=TRUE)) + + coefm[i,1] <- round(result[[i]]$waic$waic, 2) + + intercept_matrix[i, 1:3] <- c(result[[i]]$summary.fixed[1,]$`0.025quant`, result[[i]]$summary.fixed[1,]$`0.5quant`, result[[i]]$summary.fixed[1,]$`0.975quant`) + intercept_matrix[i, 4] <- predterms_short[[i]] + intercept_matrix[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_Intercept[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["(Intercept)"]])) + colnames(marginals_fixed_list_Intercept[[i]]) <- c("x for Intercept", "y for Intercept") + + if(i %in% L1_nl_element){ + social_effects_matrix_L1_nl[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for inla.group(L1_copy)`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + social_effects_matrix_L1_nl[i, 4] <- predterms_short[[i]] + social_effects_matrix_L1_nl[i, 5] <- result[[i]]$waic$waic + } + + if(i %in% L2_prop_nl_element){ + social_effects_matrix_L2_prop_nl[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for inla.group(L2_copy)`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + social_effects_matrix_L2_prop_nl[i, 4] <- predterms_short[[i]] + social_effects_matrix_L2_prop_nl[i, 5] <- result[[i]]$waic$waic + } + + if(i %in% L1_element) { + social_effects_matrix_L1[i, 1:3] <- c(result[[i]]$summary.fixed["L1_log_st",]$`0.025quant`, result[[i]]$summary.fixed["L1_log_st",]$`0.5quant`, result[[i]]$summary.fixed["L1_log_st",]$`0.975quant`) + social_effects_matrix_L1[i, 4] <- predterms_short[[i]] + social_effects_matrix_L1[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_L1[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["L1_log_st"]])) + colnames(marginals_fixed_list_L1[[i]]) <- c("x for L1", "y for L1") + } + + if(i %in% L2_prop_element) { + social_effects_matrix_L2_prop[i, 1:3] <- c(result[[i]]$summary.fixed["L2_prop",]$`0.025quant`, result[[i]]$summary.fixed["L2_prop",]$`0.5quant`, result[[i]]$summary.fixed["L2_prop",]$`0.975quant`) + social_effects_matrix_L2_prop[i, 4] <- predterms_short[[i]] + social_effects_matrix_L2_prop[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_L2_prop[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["L2_prop"]])) + colnames(marginals_fixed_list_L2_prop[[i]]) <- c("x for L2 proportion", "y for L2 proportion") + } + + if(i %in% neighbour_element) { + social_effects_matrix_N[i, 1:3] <- c(result[[i]]$summary.fixed[2,]$`0.025quant`, result[[i]]$summary.fixed[2,]$`0.5quant`, result[[i]]$summary.fixed[2,]$`0.975quant`) + social_effects_matrix_N[i, 4] <- predterms_short[[i]] + social_effects_matrix_N[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_N[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][[2]])) + colnames(marginals_fixed_list_N[[i]]) <- c("x for Neighbours", "y for Neighbours") + } + + if(i %in% official_element) { + social_effects_matrix_O[i, 1:3] <- c(result[[i]]$summary.fixed[2,]$`0.025quant`, result[[i]]$summary.fixed[2,]$`0.5quant`, result[[i]]$summary.fixed[2,]$`0.975quant`) + social_effects_matrix_O[i, 4] <- predterms_short[[i]] + social_effects_matrix_O[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_O[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][[2]])) + colnames(marginals_fixed_list_O[[i]]) <- c("x for Official", "y for Official") + } + + if(i %in% education_element) { + social_effects_matrix_E[i, 1:3] <- c(result[[i]]$summary.fixed[2,]$`0.025quant`, result[[i]]$summary.fixed[2,]$`0.5quant`, result[[i]]$summary.fixed[2,]$`0.975quant`) + social_effects_matrix_E[i, 4] <- predterms_short[[i]] + social_effects_matrix_E[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_E[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][[2]])) + colnames(marginals_fixed_list_E[[i]]) <- c("x for Education", "y for Education") + } + + fitted_list[[i]] <- result[[i]]$summary.fitted.values + fitted_list[[i]] <- fitted_list[[i]] %>% + mutate(across(where(is.numeric), round, 2)) + + marginals_hyperpar_list_gaussian[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for the Gaussian observations"]])) + colnames(marginals_hyperpar_list_gaussian[[i]]) <- c("x for the Gaussian observations", "y for the Gaussian observations") + + if(i %in% L1_nl_element){ + marginals_hyperpar_list_social_L1_nl[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for inla.group(L1_copy)"]])) + colnames(marginals_hyperpar_list_social_L1_nl[[i]]) <- c("x for inla.group(L1_copy)", "y for inla.group(L1_copy)") + } + + if(i %in% L2_prop_nl_element){ + marginals_hyperpar_list_social_L2_prop_nl[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for inla.group(L2_copy)"]])) + colnames(marginals_hyperpar_list_social_L2_prop_nl[[i]]) <- c("x for inla.group(L2_copy)", "y for inla.group(L2_copy)") + } +} + +#beepr::beep(5) + +save(result, file = "output_models_reduced/models_Informativity_social_only.RData") + + +coefm <- as.data.frame(cbind(predterms_short, coefm)) +colnames(coefm) <- c("model", "WAIC") +coefm <- coefm %>% + mutate(across(.cols=2, as.numeric)) %>% + mutate(across(where(is.numeric), round, 2)) %>% + arrange(WAIC) + +coefm$WAIC <- as.numeric(coefm$WAIC) +coefm <- coefm[order(coefm$WAIC),] + +coefm_path <- paste("output_tables_reduced/", "waics", "Informativity_social_only_models", ".csv", collapse = "") +write.csv(coefm, coefm_path, row.names=FALSE) + +for (i in 1:length(fitted_list)) { + fitted_list[[i]]$model <- names(fitted_list)[i] +} +fitted_list <- dplyr::bind_rows(fitted_list) +fitted_list_path <- paste("output_tables_reduced/", "fitted_list", "Informativity_social_only_models", ".csv", collapse = "") +write.csv(fitted_list, fitted_list_path) + +intercept_effects <- as.data.frame(intercept_matrix) +L1_effects <- as.data.frame(social_effects_matrix_L1) +L1_nl_effects <- as.data.frame(social_effects_matrix_L1_nl) +L2_prop_effects <- as.data.frame(social_effects_matrix_L2_prop) +L2_prop_nl_effects <- as.data.frame(social_effects_matrix_L2_prop_nl) +N_effects<-as.data.frame(social_effects_matrix_N) +E_effects<-as.data.frame(social_effects_matrix_E) +O_effects<-as.data.frame(social_effects_matrix_O) + +intercept_effects$effect <- "Intercept" +L1_effects$effect <- "L1" +L1_nl_effects$effect <- "social SD:\nL1" +L2_prop_effects$effect <- "L2 proportion" +L2_prop_nl_effects$effect <- "social SD:\nL2 proportion" +N_effects$effect <- "Neighbours" +E_effects$effect <- "Education" +O_effects$effect <- "Official status" + +effs <- as.data.frame(rbind(intercept_effects, L1_effects, L1_nl_effects, L2_prop_effects, L2_prop_nl_effects, N_effects, O_effects, E_effects)) +effs <- effs %>% + mutate(across(.cols=c(1:3, 5), as.numeric)) %>% + mutate(across(where(is.numeric), round, 2)) %>% + na.omit() %>% + arrange(WAIC) %>% + relocate(model) + +effs_path <- paste("output_tables_reduced/", "effects", "Informativity_social_only_models", ".csv", collapse = "") +write.csv(effs, effs_path, row.names=FALSE) + +effs <- read.csv("output_tables_reduced/ effects Informativity_social_only_models .csv") + +effs_table_SM <- effs %>% + rename("2.5%"=2, + "50%" = 4, + "97.5%" = 3) %>% + flextable() %>% + autofit() %>% + merge_v(j=c("model", "WAIC")) %>% + fix_border_issues() %>% + border_inner_h() + +save_as_docx( + "Effects in informativity models with fixed and random effects (including non-linear implementations of some fixed effects)" = effs_table_SM, + path = "output_tables_reduced/table_SM_effects_Informativity_social_only_models.docx") + +effs_table_Main <- effs %>% + rename("2.5%"=2, + "50%" = 4, + "97.5%" = 3) %>% + filter(!grepl("nonlinear", model)) + +effs_table_Main$model <- gsub("(\\s*\\(\\w+\\))", "", effs_table_Main$model) + +effs_table_Main <- effs_table_Main %>% + flextable() %>% + autofit() %>% + merge_v(j=c("model", "WAIC")) %>% + fix_border_issues() %>% + border_inner_h() + +save_as_docx( + "Effects in informativity models with fixed and random effects" = effs_table_Main, + path = "output_tables_reduced/table_Main_effects_Informativity_social_only_models.docx") + + +effs_plot <- effs %>% + #filter(WAIC <= top_9) %>% + rename(lower=2, + upper = 4, + mean = 3) %>% #mean here refers to 0.5 quantile + #filter(!effect == "Intercept") %>% + mutate(effect = factor(effect, levels=c("Intercept", "social SD:\nL1", "L1", "social SD:\nL2 proportion", "L2 proportion", "Neighbours", "Education", "Official status"))) %>% + mutate(WAIC = round(WAIC, 2)) %>% + unite("model", model, WAIC, sep = ",\nWAIC: ", remove=FALSE) %>% + group_by(WAIC) %>% + arrange(WAIC) %>% + mutate(model = forcats::fct_reorder(as.factor(model), WAIC)) %>% #reordering levels within model based on WAIC values + mutate(model = factor(model, levels=rev(levels(model)))) #reversing the order + + +#plot modified from function ggregplot::Efxplot +cols = c(brewer.pal(12, "Paired")) +cols = c("gray50", cols[c(1:8)]) + +show_col(cols) + +plot_1 <- ggplot(effs_plot, + aes(y = as.factor(model), + x = mean, + group = effect, + colour = effect)) + + geom_pointrangeh(aes(xmin = lower, xmax = upper), position = position_dodge(w = 0.9), size = 1.5) + + geom_vline(aes(xintercept = 0),lty = 2) + labs(x = NULL) + #coord_flip() + + scale_color_manual(values=cols) + + ylab("Model of informativity") + xlab("Estimate") + labs(color = "Effect") + theme_classic() + + theme(axis.text=element_text(size=50), + legend.text=element_text(size=50), + axis.title=element_text(size=50), + legend.title=element_text(size=50), + legend.spacing.y = unit(1.5, 'cm')) + + guides(color = guide_legend(reverse = TRUE, byrow = TRUE)) + + + +#plot_1 +ggsave(filename = 'output_reduced/SP_models_plot_Informativity_social_only_models.jpg', + plot_1, height = 20, width = 45) + + +#saving hyperparameters: Gaussian observations +for (i in 1:length(marginals_hyperpar_list_gaussian)) { + marginals_hyperpar_list_gaussian[[i]]$model <- names(marginals_hyperpar_list_gaussian)[i] +} +marginals_hyperpar_list_gaussian <- dplyr::bind_rows(marginals_hyperpar_list_gaussian) + +write.csv(marginals_hyperpar_list_gaussian, "output_tables_reduced/Informativity_social_only_models_marginals_hyperpar_gaussian.csv") diff --git a/101/replication_package/models_Informativity_social.R b/101/replication_package/models_Informativity_social.R new file mode 100644 index 0000000000000000000000000000000000000000..16ea3d4267bb899ed32a7757a10167c06c1feb13 --- /dev/null +++ b/101/replication_package/models_Informativity_social.R @@ -0,0 +1,556 @@ +#model fitting: Informativity predicted by social effects on top of random phylogenetic and spatial factors + +#Script was written by Sam Passmore and modified by Olena Shcherbakova + +source("requirements.R") + +source("install_and_load_INLA.R") + +source("set_up_inla.R") + +metrics_joined <- metrics_joined %>% + filter(!is.na(L1_log10_st)) %>% + rename(L1_log_st = L1_log10_st) %>% + mutate(L1_copy = L1_log_st) %>% + filter(!is.na(L2_prop)) %>% + mutate(L2_copy = L2_prop) %>% + filter(!is.na(neighboring_languages_st)) %>% + filter(!is.na(Official)) %>% + filter(!is.na(Education)) %>% + filter(!is.na(boundness_st)) %>% + filter(!is.na(informativity_st)) + +#dropping tips not in Grambank +metrics_joined <- metrics_joined[metrics_joined$Language_ID %in% tree$tip.label, ] +tree <- keep.tip(tree, metrics_joined$Language_ID) + +x <- assert_that(all(tree$tip.label %in% metrics_joined$Language_ID), msg = "The data and phylogeny taxa do not match") + +## Building standardized phylogenetic precision matrix +tree_scaled <- tree + +tree_vcv = vcv.phylo(tree_scaled) +typical_phylogenetic_variance = exp(mean(log(diag(tree_vcv)))) + +#We opt for a sparse phylogenetic precision matrix (i.e. it is quantified using all nodes and tips), since sparse matrices make the analysis in INLA less time-intensive +tree_scaled$edge.length <- tree_scaled$edge.length/typical_phylogenetic_variance +phylo_prec_mat <- MCMCglmm::inverseA(tree_scaled, + nodes = "ALL", + scale = FALSE)$Ainv + +metrics_joined = metrics_joined[order(match(metrics_joined$Language_ID, rownames(phylo_prec_mat))),] + +#"local" set of parameters +## Create spatial covariance matrix using the matern covariance function +spatial_covar_mat_1 = varcov.spatial(metrics_joined[,c("Longitude", "Latitude")], + cov.pars = phi_1, kappa = kappa)$varcov +# Calculate and standardize by the typical variance +typical_variance_spatial_1 = exp(mean(log(diag(spatial_covar_mat_1)))) +spatial_cov_std_1 = spatial_covar_mat_1 / typical_variance_spatial_1 +spatial_prec_mat_1 = solve(spatial_cov_std_1) +dimnames(spatial_prec_mat_1) = list(metrics_joined$Language_ID, metrics_joined$Language_ID) + +## Since we are using a sparse phylogenetic matrix, we are matching taxa to rows in the matrix +phy_id = match(tree$tip.label, rownames(phylo_prec_mat)) +metrics_joined$phy_id = phy_id + +## Other effects are in the same order they appear in the dataset +metrics_joined$sp_id = 1:nrow(spatial_prec_mat_1) + +#Preparing the formulas for 10 competing models to be used in inla() call +listcombo <- list( + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper)", "L1_log_st"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper)", "f(inla.group(L1_copy), model='rw2', scale.model = TRUE)"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper)", "L2_prop"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper)", "f(inla.group(L2_copy), model='rw2', scale.model = TRUE)"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper)", "f(inla.group(L1_copy), model='rw2', scale.model = TRUE)", "f(inla.group(L2_copy), model='rw2', scale.model = TRUE)"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper)", "L1_log_st", "L2_prop"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper)", "L1_log10:L2_prop"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper)", "neighboring_languages_st"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper)", "Official"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper)", "Education")) + + +predterms <- lapply(listcombo, function(x) paste(x, collapse="+")) + +predterms <- t(as.data.frame(predterms)) + +predterms_short <- predterms +predterms_short <- gsub("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper)", "Phylogenetic", predterms_short, fixed=TRUE) +predterms_short <- gsub("f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper)", "Spatial: local", predterms_short, fixed=TRUE) + +predterms_short <- gsub("f(inla.group(L1_copy), model='rw2', scale.model = TRUE)", "L1 speakers (nonlinear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("L1_log_st", "L1 speakers (linear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("f(inla.group(L2_copy), model='rw2', scale.model = TRUE)", "L2 proportion (nonlinear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("L2_prop", "L2 proportion (linear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("neighboring_languages_st", "Neighbours", predterms_short, fixed=TRUE) + + +phylogenetic_element <- data.frame("judgement" = grepl("Phylogenetic", predterms_short), + number = 1:length(predterms_short)) +phylogenetic_element <- phylogenetic_element[phylogenetic_element$judgement == TRUE,]$number + +spatial_element_local <- data.frame("judgement" = grepl("local", predterms_short), + number = 1:length(predterms_short)) +spatial_element_local <- spatial_element_local[spatial_element_local$judgement == TRUE,]$number + +spatial_element_regional <- data.frame("judgement" = grepl("regional", predterms_short), + number = 1:length(predterms_short)) +spatial_element_regional <- spatial_element_regional[spatial_element_regional$judgement == TRUE,]$number + +spatial_element <- c(spatial_element_local, spatial_element_regional) + +L1_element <- data.frame("judgement" = grepl("L1 speakers (linear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L1_element <- L1_element[L1_element$judgement == TRUE,]$number + + +L1_nl_element <- data.frame("judgement" = grepl("L1 speakers (nonlinear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L1_nl_element <- L1_nl_element[L1_nl_element$judgement == TRUE,]$number + +L2_prop_element <- data.frame("judgement" = grepl("L2 proportion (linear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L2_prop_element <- L2_prop_element[L2_prop_element$judgement == TRUE,]$number +L2_prop_element <- L2_prop_element[-length(L2_prop_element)] #making sure that the interaction term (introduced below) is not treated as belonging to this isolated element + +L2_prop_nl_element <- data.frame("judgement" = grepl("L2 proportion (nonlinear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L2_prop_nl_element <- L2_prop_nl_element[L2_prop_nl_element$judgement == TRUE,]$number + +#can use only part of the interaction term within grepl() function +interaction_element <- data.frame("judgement" = grepl(":L2 proportion", predterms_short), + number = 1:length(predterms_short)) +interaction_element <- interaction_element[interaction_element$judgement == TRUE,]$number + +neighbour_element <- data.frame("judgement" = grepl("Neighbours", predterms_short), + number = 1:length(predterms_short)) +neighbour_element <- neighbour_element[neighbour_element$judgement == TRUE,]$number + +official_element <- data.frame("judgement" = grepl("Official", predterms_short), + number = 1:length(predterms_short)) +official_element <- official_element[official_element$judgement == TRUE,]$number + +education_element <- data.frame("judgement" = grepl("Education", predterms_short), + number = 1:length(predterms_short)) +education_element <- education_element[education_element$judgement == TRUE,]$number + + + +#preparing empty matrices to be filled with effect estimates (quantiles), model name, and WAIC value +phy_effects_matrix <- matrix(NA, 10, 5) +colnames(phy_effects_matrix) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +spa_effects_matrix <- matrix(NA, 10, 5) +colnames(spa_effects_matrix) <- c("2.5%", "50%", "97.5%", "model", "WAIC") + +intercept_matrix <- matrix(NA, 10, 5) +colnames(intercept_matrix) <- c("2.5%", "50%", "97.5%", "model", "WAIC") + +social_effects_matrix_L1 <- matrix(NA, 10, 5) +colnames(social_effects_matrix_L1) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L1_nl <- matrix(NA, 10, 5) +colnames(social_effects_matrix_L1_nl) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L2_prop <- matrix(NA, 10, 5) +colnames(social_effects_matrix_L2_prop) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L2_prop_nl <- matrix(NA, 10, 5) +colnames(social_effects_matrix_L2_prop_nl) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_N <- matrix(NA, 10, 5) +colnames(social_effects_matrix_N) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_O <- matrix(NA, 10, 5) +colnames(social_effects_matrix_O) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_E <- matrix(NA, 10, 5) +colnames(social_effects_matrix_E) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L1_L2_prop <- matrix(NA, 10, 5) +colnames(social_effects_matrix_L1_L2_prop) <- c("2.5%", "50%", "97.5%", "model", "WAIC") + +#fitted values +fitted_list <- vector("list", 10) +names(fitted_list) <- predterms_short + +#marginals of hyperparameters +marginals_hyperpar_list_gaussian <- vector("list", 10) +names(marginals_hyperpar_list_gaussian) <- predterms_short + +marginals_hyperpar_list_phy <- vector("list", 10) +names(marginals_hyperpar_list_phy) <- predterms_short + +marginals_hyperpar_list_spa <- vector("list", 10) +names(marginals_hyperpar_list_spa) <- predterms_short + +marginals_hyperpar_list_social_L1_nl <- vector("list", 10) +names(marginals_hyperpar_list_social_L1_nl) <- predterms_short + +marginals_hyperpar_list_social_L2_prop_nl <- vector("list", 10) +names(marginals_hyperpar_list_social_L2_prop_nl) <- predterms_short + + +#marginals of fixed effects +marginals_fixed_list_Intercept <- vector("list", 10) +names(marginals_fixed_list_Intercept) <- predterms_short + +marginals_fixed_list_L1 <- vector("list", 10) +names(marginals_fixed_list_L1) <- predterms_short + +marginals_fixed_list_L2_prop <- vector("list", 10) +names(marginals_fixed_list_L2_prop) <- predterms_short + +marginals_fixed_list_O <- vector("list", 10) +names(marginals_fixed_list_O) <- predterms_short + +marginals_fixed_list_N <- vector("list", 10) +names(marginals_fixed_list_N) <- predterms_short + +marginals_fixed_list_E <- vector("list", 10) +names(marginals_fixed_list_E) <- predterms_short + +marginals_fixed_list_L1_L2_prop <- vector("list", 10) +names(marginals_fixed_list_L1_L2_prop) <- predterms_short + + + + +#summary statistics of random effects +summary_random_list_phy <- vector("list", 10) +names(summary_random_list_phy) <- predterms_short + +summary_random_list_spa <- vector("list", 10) +names(summary_random_list_spa) <- predterms_short + +summary_random_list_social_L1_nl <- vector("list", 10) +names(summary_random_list_social_L1_nl) <- predterms_short + +summary_random_list_social_L2_prop_nl <- vector("list", 10) +names(summary_random_list_social_L2_prop_nl) <- predterms_short + + +coefm <- matrix(NA,10,1) +result <- vector("list",10) + +for(i in 1:10){ + formula <- as.formula(paste("informativity_st ~ ",predterms[[i]])) + result[[i]] <- inla(formula, family="gaussian", + control.family = list(hyper = pcprior_hyper), + #control.inla = list(tolerance = 1e-8, h = 0.0001), + #tolerance: the tolerance for the optimisation of the hyperparameters + #h: the step-length for the gradient calculations for the hyperparameters. + data=metrics_joined, control.compute=list(waic=TRUE)) + + coefm[i,1] <- round(result[[i]]$waic$waic, 2) + + intercept_matrix[i, 1:3] <- c(result[[i]]$summary.fixed[1,]$`0.025quant`, result[[i]]$summary.fixed[1,]$`0.5quant`, result[[i]]$summary.fixed[1,]$`0.975quant`) + intercept_matrix[i, 4] <- predterms_short[[i]] + intercept_matrix[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_Intercept[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["(Intercept)"]])) + colnames(marginals_fixed_list_Intercept[[i]]) <- c("x for Intercept", "y for Intercept") + + if(i %in% phylogenetic_element) { + phy_effects_matrix[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for phy_id`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + phy_effects_matrix[i, 4] <- predterms_short[[i]] + phy_effects_matrix[i, 5] <- result[[i]]$waic$waic + } + + if(i %in% spatial_element) { + spa_effects_matrix[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for sp_id`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + spa_effects_matrix[i, 4] <- predterms_short[[i]] + spa_effects_matrix[i, 5] <- result[[i]]$waic$waic + } + + + if(i %in% L1_nl_element){ + social_effects_matrix_L1_nl[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for inla.group(L1_copy)`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + social_effects_matrix_L1_nl[i, 4] <- predterms_short[[i]] + social_effects_matrix_L1_nl[i, 5] <- result[[i]]$waic$waic + } + + if(i %in% L2_prop_nl_element){ + social_effects_matrix_L2_prop_nl[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for inla.group(L2_copy)`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + social_effects_matrix_L2_prop_nl[i, 4] <- predterms_short[[i]] + social_effects_matrix_L2_prop_nl[i, 5] <- result[[i]]$waic$waic + } + + if(i %in% L1_element) { + social_effects_matrix_L1[i, 1:3] <- c(result[[i]]$summary.fixed["L1_log_st",]$`0.025quant`, result[[i]]$summary.fixed["L1_log_st",]$`0.5quant`, result[[i]]$summary.fixed["L1_log_st",]$`0.975quant`) + social_effects_matrix_L1[i, 4] <- predterms_short[[i]] + social_effects_matrix_L1[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_L1[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["L1_log_st"]])) + colnames(marginals_fixed_list_L1[[i]]) <- c("x for L1", "y for L1") + } + + if(i %in% L2_prop_element) { + social_effects_matrix_L2_prop[i, 1:3] <- c(result[[i]]$summary.fixed["L2_prop",]$`0.025quant`, result[[i]]$summary.fixed["L2_prop",]$`0.5quant`, result[[i]]$summary.fixed["L2_prop",]$`0.975quant`) + social_effects_matrix_L2_prop[i, 4] <- predterms_short[[i]] + social_effects_matrix_L2_prop[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_L2_prop[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["L2_prop"]])) + colnames(marginals_fixed_list_L2_prop[[i]]) <- c("x for L2 proportion", "y for L2 proportion") + } + + if(i %in% interaction_element) { + social_effects_matrix_L1_L2_prop[i, 1:3] <- c(result[[i]]$summary.fixed["L1_log10:L2_prop",]$`0.025quant`, result[[i]]$summary.fixed["L1_log10:L2_prop",]$`0.5quant`, result[[i]]$summary.fixed["L1_log10:L2_prop",]$`0.975quant`) + social_effects_matrix_L1_L2_prop[i, 4] <- predterms_short[[i]] + social_effects_matrix_L1_L2_prop[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_L1_L2_prop[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["L1_log10:L2_prop"]])) + colnames(marginals_fixed_list_L1_L2_prop[[i]]) <- c("x for L1*L2 proportion", "y for L1*L2 proportion") + } + + if(i %in% neighbour_element) { + social_effects_matrix_N[i, 1:3] <- c(result[[i]]$summary.fixed[2,]$`0.025quant`, result[[i]]$summary.fixed[2,]$`0.5quant`, result[[i]]$summary.fixed[2,]$`0.975quant`) + social_effects_matrix_N[i, 4] <- predterms_short[[i]] + social_effects_matrix_N[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_N[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][[2]])) + colnames(marginals_fixed_list_N[[i]]) <- c("x for Neighbours", "y for Neighbours") + } + + if(i %in% official_element) { + social_effects_matrix_O[i, 1:3] <- c(result[[i]]$summary.fixed[2,]$`0.025quant`, result[[i]]$summary.fixed[2,]$`0.5quant`, result[[i]]$summary.fixed[2,]$`0.975quant`) + social_effects_matrix_O[i, 4] <- predterms_short[[i]] + social_effects_matrix_O[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_O[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][[2]])) + colnames(marginals_fixed_list_O[[i]]) <- c("x for Official", "y for Official") + } + + if(i %in% education_element) { + social_effects_matrix_E[i, 1:3] <- c(result[[i]]$summary.fixed[2,]$`0.025quant`, result[[i]]$summary.fixed[2,]$`0.5quant`, result[[i]]$summary.fixed[2,]$`0.975quant`) + social_effects_matrix_E[i, 4] <- predterms_short[[i]] + social_effects_matrix_E[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_E[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][[2]])) + colnames(marginals_fixed_list_E[[i]]) <- c("x for Education", "y for Education") + } + + fitted_list[[i]] <- result[[i]]$summary.fitted.values + fitted_list[[i]] <- fitted_list[[i]] %>% + mutate(across(where(is.numeric), round, 2)) + + marginals_hyperpar_list_gaussian[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for the Gaussian observations"]])) + colnames(marginals_hyperpar_list_gaussian[[i]]) <- c("x for the Gaussian observations", "y for the Gaussian observations") + + if(i %in% phylogenetic_element){ + marginals_hyperpar_list_phy[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for phy_id"]])) + colnames(marginals_hyperpar_list_phy[[i]]) <- c("x for phy_id", "y for phy_id") + } + + if(i %in% spatial_element){ + marginals_hyperpar_list_spa[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for sp_id"]])) + colnames(marginals_hyperpar_list_spa[[i]]) <- c("x for sp_id", "y for sp_id") + } + + if(i %in% L1_nl_element){ + marginals_hyperpar_list_social_L1_nl[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for inla.group(L1_copy)"]])) + colnames(marginals_hyperpar_list_social_L1_nl[[i]]) <- c("x for inla.group(L1_copy)", "y for inla.group(L1_copy)") + } + + if(i %in% L2_prop_nl_element){ + marginals_hyperpar_list_social_L2_prop_nl[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for inla.group(L2_copy)"]])) + colnames(marginals_hyperpar_list_social_L2_prop_nl[[i]]) <- c("x for inla.group(L2_copy)", "y for inla.group(L2_copy)") + } + + if(i %in% phylogenetic_element){ + summary_random_list_phy[[i]] <- cbind(result[[i]]$summary.random$phy_id) %>% + rename(phy_id = ID) %>% + as.data.frame() %>% + mutate(across(where(is.numeric), round, 2)) + } + + if(i %in% spatial_element){ + summary_random_list_spa[[i]] <- cbind(result[[i]]$summary.random$sp_id) %>% + rename(sp_id = ID) %>% + as.data.frame() %>% + mutate(across(where(is.numeric), round, 2)) + } +} + +#beepr::beep(5) + +save(result, file = "output_models/models_Informativity_social.RData") + + +coefm <- as.data.frame(cbind(predterms_short, coefm)) +colnames(coefm) <- c("model", "WAIC") +coefm <- coefm %>% + mutate(across(.cols=2, as.numeric)) %>% + mutate(across(where(is.numeric), round, 2)) %>% + arrange(WAIC) + +coefm$WAIC <- as.numeric(coefm$WAIC) +coefm <- coefm[order(coefm$WAIC),] + +coefm_path <- paste("output_tables/", "waics", "Informativity_social_models", ".csv", collapse = "") +write.csv(coefm, coefm_path, row.names=FALSE) + +for (i in 1:length(fitted_list)) { + fitted_list[[i]]$model <- names(fitted_list)[i] +} +fitted_list <- dplyr::bind_rows(fitted_list) +fitted_list_path <- paste("output_tables/", "fitted_list", "Informativity_social_models", ".csv", collapse = "") +write.csv(fitted_list, fitted_list_path) + +phy_effects<-as.data.frame(phy_effects_matrix) +spa_effects<-as.data.frame(spa_effects_matrix) +intercept_effects <- as.data.frame(intercept_matrix) +L1_effects <- as.data.frame(social_effects_matrix_L1) +L1_nl_effects <- as.data.frame(social_effects_matrix_L1_nl) +L2_prop_effects <- as.data.frame(social_effects_matrix_L2_prop) +L2_prop_nl_effects <- as.data.frame(social_effects_matrix_L2_prop_nl) +N_effects<-as.data.frame(social_effects_matrix_N) +E_effects<-as.data.frame(social_effects_matrix_E) +O_effects<-as.data.frame(social_effects_matrix_O) +interaction_effects <- as.data.frame(social_effects_matrix_L1_L2_prop) + +phy_effects$effect <- "phylogenetic SD" +spa_effects$effect <- "spatial SD" +intercept_effects$effect <- "Intercept" +L1_effects$effect <- "L1" +L1_nl_effects$effect <- "social SD:\nL1" +L2_prop_effects$effect <- "L2 proportion" +L2_prop_nl_effects$effect <- "social SD:\nL2 proportion" +N_effects$effect <- "Neighbours" +E_effects$effect <- "Education" +O_effects$effect <- "Official status" +interaction_effects$effect <- "L1*L2 proportion" + +effs <- as.data.frame(rbind(phy_effects, spa_effects, intercept_effects, L1_effects, L1_nl_effects, L2_prop_effects, L2_prop_nl_effects, N_effects, O_effects, E_effects, interaction_effects)) +effs <- effs %>% + mutate(across(.cols=c(1:3, 5), as.numeric)) %>% + mutate(across(where(is.numeric), round, 2)) %>% + na.omit() %>% + arrange(WAIC) %>% + relocate(model) + +effs_path <- paste("output_tables/", "effects", "Informativity_social_models", ".csv", collapse = "") +write.csv(effs, effs_path, row.names=FALSE) + +effs <- read.csv("output_tables/ effects Informativity_social_models .csv") + +effs_table_Main <- effs %>% + rename("2.5%"=2, + "50%" = 3, + "97.5%" = 4) %>% + filter(!grepl("nonlinear", model)) + +effs_table_Main$model <- gsub("(\\s*\\(\\w+\\))", "", effs_table_Main$model) + +effs_table_Main <- effs_table_Main %>% + relocate(effect, .after = model) %>% + flextable() %>% + flextable::bold(~ (`2.5%` > 0 & `97.5%` > 0) | (`2.5%` < 0 & `97.5%` < 0), 2) %>% + autofit() %>% + merge_v(j=c("model", "WAIC")) %>% + fix_border_issues() %>% + border_inner_h() + +save_as_docx( + "Effects in informativity models with fixed and random effects" = effs_table_Main, + path = "output_tables/table_Main_effects_Informativity_social_models.docx") + + +effs_plot <- effs %>% + #filter(WAIC <= top_9) %>% + rename(lower=2, + upper = 4, + mean = 3) %>% #mean here refers to 0.5 quantile + #filter(!effect == "Intercept") %>% + mutate(effect = factor(effect, levels=c("phylogenetic SD", "spatial SD", "Intercept", "social SD:\nL1", "L1", "social SD:\nL2 proportion", "L2 proportion", "Neighbours", "Education", "Official status", "L1*L2 proportion"))) %>% + mutate(WAIC = round(WAIC, 2)) %>% + unite("model", model, WAIC, sep = ",\nWAIC: ", remove=FALSE) %>% + group_by(WAIC) %>% + arrange(WAIC) %>% + mutate(model = forcats::fct_reorder(as.factor(model), WAIC)) %>% #reordering levels within model based on WAIC values + mutate(model = factor(model, levels=rev(levels(model)))) #reversing the order + + +#plot modified from function ggregplot::Efxplot +cols = c(brewer.pal(12, "Paired")) +cols = c(cols[c(12, 10)], "gray50", cols[c(1:8)]) + +show_col(cols) + +plot_1 <- ggplot(effs_plot, + aes(y = as.factor(model), + x = mean, + group = effect, + colour = effect)) + + geom_pointrangeh(aes(xmin = lower, xmax = upper), position = position_dodge(w = 0.9), size = 1.5) + + geom_vline(aes(xintercept = 0),lty = 2) + labs(x = NULL) + #coord_flip() + + scale_color_manual(values=cols) + + ylab("Model of informativity") + xlab("Estimate") + labs(color = "Effect") + theme_classic() + + theme(axis.text=element_text(size=50), + legend.text=element_text(size=50), + axis.title=element_text(size=50), + legend.title=element_text(size=50), + legend.spacing.y = unit(1.5, 'cm')) + + guides(color = guide_legend(reverse = TRUE, byrow = TRUE)) + + + +#plot_1 +ggsave(filename = 'output/SP_models_plot_Informativity_social_models.jpg', + plot_1, height = 20, width = 45) + + +#saving hyperparameters: Gaussian observations +for (i in 1:length(marginals_hyperpar_list_gaussian)) { + marginals_hyperpar_list_gaussian[[i]]$model <- names(marginals_hyperpar_list_gaussian)[i] +} +marginals_hyperpar_list_gaussian <- dplyr::bind_rows(marginals_hyperpar_list_gaussian) + +write.csv(marginals_hyperpar_list_gaussian, "output_tables/Informativity_social_models_marginals_hyperpar_gaussian.csv") + +#saving hyperparameters: phylogenetic +for (i in 1:length(marginals_hyperpar_list_phy)) { + marginals_hyperpar_list_phy[[i]]$model <- names(marginals_hyperpar_list_phy)[i] +} +marginals_hyperpar_list_phy <- dplyr::bind_rows(marginals_hyperpar_list_phy) + +write.csv(marginals_hyperpar_list_phy, "output_tables/Informativity_social_models_marginals_hyperpar_phylogenetic.csv") + +#saving hyperparameters: spatial +for (i in 1:length(marginals_hyperpar_list_spa)) { + marginals_hyperpar_list_spa[[i]]$model <- names(marginals_hyperpar_list_spa)[i] +} +marginals_hyperpar_list_spa <- dplyr::bind_rows(marginals_hyperpar_list_spa) + +write.csv(marginals_hyperpar_list_spa, "output_tables/Informativity_social_models_marginals_hyperpar_spatial.csv") + + +#saving summaries of random effects: phylogenetic +for (i in 1:length(summary_random_list_phy)) { + summary_random_list_phy[[i]]$model <- names(summary_random_list_phy)[i] +} +summary_random_list_phy <- dplyr::bind_rows(summary_random_list_phy) + +write.csv(summary_random_list_phy, "output_tables/Informativity_social_models_summary_random_phy.csv") + +#saving summaries of random effects: spatial +for (i in 1:length(summary_random_list_spa)) { + summary_random_list_spa[[i]]$model <- names(summary_random_list_spa)[i] +} +summary_random_list_spa <- dplyr::bind_rows(summary_random_list_spa) + +write.csv(summary_random_list_spa, "output_tables/Informativity_social_models_summary_random_spa.csv") diff --git a/101/replication_package/models_Informativity_social_only.R b/101/replication_package/models_Informativity_social_only.R new file mode 100644 index 0000000000000000000000000000000000000000..9ad4f28f96a52e735eeec6628c028207d8d1ff34 --- /dev/null +++ b/101/replication_package/models_Informativity_social_only.R @@ -0,0 +1,454 @@ +#model fitting: Informativity predicted by social effects on top of random phylogenetic and spatial factors + +#Script was written by Sam Passmore and modified by Olena Shcherbakova + +source("requirements.R") + +source("install_and_load_INLA.R") + +source("set_up_inla.R") + +metrics_joined <- metrics_joined %>% + filter(!is.na(L1_log10_st)) %>% + rename(L1_log_st = L1_log10_st) %>% + mutate(L1_copy = L1_log_st) %>% + filter(!is.na(L2_prop)) %>% + mutate(L2_copy = L2_prop) %>% + filter(!is.na(neighboring_languages_st)) %>% + filter(!is.na(Official)) %>% + filter(!is.na(Education)) %>% + filter(!is.na(boundness_st)) %>% + filter(!is.na(informativity_st)) + +#dropping tips not in Grambank +metrics_joined <- metrics_joined[metrics_joined$Language_ID %in% tree$tip.label, ] +tree <- keep.tip(tree, metrics_joined$Language_ID) + +x <- assert_that(all(tree$tip.label %in% metrics_joined$Language_ID), msg = "The data and phylogeny taxa do not match") + +## Building standardized phylogenetic precision matrix +tree_scaled <- tree + +tree_vcv = vcv.phylo(tree_scaled) +typical_phylogenetic_variance = exp(mean(log(diag(tree_vcv)))) + +#We opt for a sparse phylogenetic precision matrix (i.e. it is quantified using all nodes and tips), since sparse matrices make the analysis in INLA less time-intensive +tree_scaled$edge.length <- tree_scaled$edge.length/typical_phylogenetic_variance +phylo_prec_mat <- MCMCglmm::inverseA(tree_scaled, + nodes = "ALL", + scale = FALSE)$Ainv + +metrics_joined = metrics_joined[order(match(metrics_joined$Language_ID, rownames(phylo_prec_mat))),] + +#"local" set of parameters +## Create spatial covariance matrix using the matern covariance function +spatial_covar_mat_1 = varcov.spatial(metrics_joined[,c("Longitude", "Latitude")], + cov.pars = phi_1, kappa = kappa)$varcov +# Calculate and standardize by the typical variance +typical_variance_spatial_1 = exp(mean(log(diag(spatial_covar_mat_1)))) +spatial_cov_std_1 = spatial_covar_mat_1 / typical_variance_spatial_1 +spatial_prec_mat_1 = solve(spatial_cov_std_1) +dimnames(spatial_prec_mat_1) = list(metrics_joined$Language_ID, metrics_joined$Language_ID) + +## Since we are using a sparse phylogenetic matrix, we are matching taxa to rows in the matrix +phy_id = match(tree$tip.label, rownames(phylo_prec_mat)) +metrics_joined$phy_id = phy_id + +## Other effects are in the same order they appear in the dataset +metrics_joined$sp_id = 1:nrow(spatial_prec_mat_1) + +#Preparing the formulas for 10 competing models to be used in inla() call +listcombo <- list( + c("L1_log_st"), + + c("f(inla.group(L1_copy), model='rw2', scale.model = TRUE)"), + + c("L2_prop"), + + c("f(inla.group(L2_copy), model='rw2', scale.model = TRUE)"), + + c("f(inla.group(L1_copy), model='rw2', scale.model = TRUE)", "f(inla.group(L2_copy), model='rw2', scale.model = TRUE)"), + + c("L1_log_st", "L2_prop"), + + c("L1_log10:L2_prop"), + + c("neighboring_languages_st"), + + c("Official"), + + c("Education")) + + +predterms <- lapply(listcombo, function(x) paste(x, collapse="+")) + +predterms <- t(as.data.frame(predterms)) + +predterms_short <- predterms + +predterms_short <- gsub("f(inla.group(L1_copy), model='rw2', scale.model = TRUE)", "L1 speakers (nonlinear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("L1_log_st", "L1 speakers (linear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("f(inla.group(L2_copy), model='rw2', scale.model = TRUE)", "L2 proportion (nonlinear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("L2_prop", "L2 proportion (linear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("neighboring_languages_st", "Neighbours", predterms_short, fixed=TRUE) + +L1_element <- data.frame("judgement" = grepl("L1 speakers (linear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L1_element <- L1_element[L1_element$judgement == TRUE,]$number + + +L1_nl_element <- data.frame("judgement" = grepl("L1 speakers (nonlinear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L1_nl_element <- L1_nl_element[L1_nl_element$judgement == TRUE,]$number + +L2_prop_element <- data.frame("judgement" = grepl("L2 proportion (linear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L2_prop_element <- L2_prop_element[L2_prop_element$judgement == TRUE,]$number +L2_prop_element <- L2_prop_element[-length(L2_prop_element)] #making sure that the interaction term (introduced below) is not treated as belonging to this isolated element + +L2_prop_nl_element <- data.frame("judgement" = grepl("L2 proportion (nonlinear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L2_prop_nl_element <- L2_prop_nl_element[L2_prop_nl_element$judgement == TRUE,]$number + +#can use only part of the interaction term within grepl() function +interaction_element <- data.frame("judgement" = grepl(":L2 proportion", predterms_short), + number = 1:length(predterms_short)) +interaction_element <- interaction_element[interaction_element$judgement == TRUE,]$number + +neighbour_element <- data.frame("judgement" = grepl("Neighbours", predterms_short), + number = 1:length(predterms_short)) +neighbour_element <- neighbour_element[neighbour_element$judgement == TRUE,]$number + +official_element <- data.frame("judgement" = grepl("Official", predterms_short), + number = 1:length(predterms_short)) +official_element <- official_element[official_element$judgement == TRUE,]$number + +education_element <- data.frame("judgement" = grepl("Education", predterms_short), + number = 1:length(predterms_short)) +education_element <- education_element[education_element$judgement == TRUE,]$number + + + +#preparing empty matrices to be filled with effect estimates (quantiles), model name, and WAIC value +intercept_matrix <- matrix(NA, 10, 5) +colnames(intercept_matrix) <- c("2.5%", "50%", "97.5%", "model", "WAIC") + +social_effects_matrix_L1 <- matrix(NA, 10, 5) +colnames(social_effects_matrix_L1) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L1_nl <- matrix(NA, 10, 5) +colnames(social_effects_matrix_L1_nl) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L2_prop <- matrix(NA, 10, 5) +colnames(social_effects_matrix_L2_prop) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L2_prop_nl <- matrix(NA, 10, 5) +colnames(social_effects_matrix_L2_prop_nl) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_N <- matrix(NA, 10, 5) +colnames(social_effects_matrix_N) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_O <- matrix(NA, 10, 5) +colnames(social_effects_matrix_O) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_E <- matrix(NA, 10, 5) +colnames(social_effects_matrix_E) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L1_L2_prop <- matrix(NA, 10, 5) +colnames(social_effects_matrix_L1_L2_prop) <- c("2.5%", "50%", "97.5%", "model", "WAIC") + +#fitted values +fitted_list <- vector("list", 10) +names(fitted_list) <- predterms_short + +#marginals of hyperparameters +marginals_hyperpar_list_gaussian <- vector("list", 10) +names(marginals_hyperpar_list_gaussian) <- predterms_short + +marginals_hyperpar_list_social_L1_nl <- vector("list", 10) +names(marginals_hyperpar_list_social_L1_nl) <- predterms_short + +marginals_hyperpar_list_social_L2_prop_nl <- vector("list", 10) +names(marginals_hyperpar_list_social_L2_prop_nl) <- predterms_short + + +#marginals of fixed effects +marginals_fixed_list_Intercept <- vector("list", 10) +names(marginals_fixed_list_Intercept) <- predterms_short + +marginals_fixed_list_L1 <- vector("list", 10) +names(marginals_fixed_list_L1) <- predterms_short + +marginals_fixed_list_L2_prop <- vector("list", 10) +names(marginals_fixed_list_L2_prop) <- predterms_short + +marginals_fixed_list_O <- vector("list", 10) +names(marginals_fixed_list_O) <- predterms_short + +marginals_fixed_list_N <- vector("list", 10) +names(marginals_fixed_list_N) <- predterms_short + +marginals_fixed_list_E <- vector("list", 10) +names(marginals_fixed_list_E) <- predterms_short + +marginals_fixed_list_L1_L2_prop <- vector("list", 10) +names(marginals_fixed_list_L1_L2_prop) <- predterms_short + + + + +#summary statistics of random effects +summary_random_list_social_L1_nl <- vector("list", 10) +names(summary_random_list_social_L1_nl) <- predterms_short + +summary_random_list_social_L2_prop_nl <- vector("list", 10) +names(summary_random_list_social_L2_prop_nl) <- predterms_short + + +coefm <- matrix(NA,10,1) +result <- vector("list",10) + +for(i in 1:10){ + formula <- as.formula(paste("informativity_st ~ ",predterms[[i]])) + result[[i]] <- inla(formula, family="gaussian", + control.family = list(hyper = pcprior_hyper), + #control.inla = list(tolerance = 1e-8, h = 0.0001), + #tolerance: the tolerance for the optimisation of the hyperparameters + #h: the step-length for the gradient calculations for the hyperparameters. + data=metrics_joined, control.compute=list(waic=TRUE)) + + coefm[i,1] <- round(result[[i]]$waic$waic, 2) + + intercept_matrix[i, 1:3] <- c(result[[i]]$summary.fixed[1,]$`0.025quant`, result[[i]]$summary.fixed[1,]$`0.5quant`, result[[i]]$summary.fixed[1,]$`0.975quant`) + intercept_matrix[i, 4] <- predterms_short[[i]] + intercept_matrix[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_Intercept[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["(Intercept)"]])) + colnames(marginals_fixed_list_Intercept[[i]]) <- c("x for Intercept", "y for Intercept") + + if(i %in% L1_nl_element){ + social_effects_matrix_L1_nl[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for inla.group(L1_copy)`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + social_effects_matrix_L1_nl[i, 4] <- predterms_short[[i]] + social_effects_matrix_L1_nl[i, 5] <- result[[i]]$waic$waic + } + + if(i %in% L2_prop_nl_element){ + social_effects_matrix_L2_prop_nl[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for inla.group(L2_copy)`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + social_effects_matrix_L2_prop_nl[i, 4] <- predterms_short[[i]] + social_effects_matrix_L2_prop_nl[i, 5] <- result[[i]]$waic$waic + } + + if(i %in% L1_element) { + social_effects_matrix_L1[i, 1:3] <- c(result[[i]]$summary.fixed["L1_log_st",]$`0.025quant`, result[[i]]$summary.fixed["L1_log_st",]$`0.5quant`, result[[i]]$summary.fixed["L1_log_st",]$`0.975quant`) + social_effects_matrix_L1[i, 4] <- predterms_short[[i]] + social_effects_matrix_L1[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_L1[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["L1_log_st"]])) + colnames(marginals_fixed_list_L1[[i]]) <- c("x for L1", "y for L1") + } + + if(i %in% L2_prop_element) { + social_effects_matrix_L2_prop[i, 1:3] <- c(result[[i]]$summary.fixed["L2_prop",]$`0.025quant`, result[[i]]$summary.fixed["L2_prop",]$`0.5quant`, result[[i]]$summary.fixed["L2_prop",]$`0.975quant`) + social_effects_matrix_L2_prop[i, 4] <- predterms_short[[i]] + social_effects_matrix_L2_prop[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_L2_prop[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["L2_prop"]])) + colnames(marginals_fixed_list_L2_prop[[i]]) <- c("x for L2 proportion", "y for L2 proportion") + } + + if(i %in% interaction_element) { + social_effects_matrix_L1_L2_prop[i, 1:3] <- c(result[[i]]$summary.fixed["L1_log10:L2_prop",]$`0.025quant`, result[[i]]$summary.fixed["L1_log10:L2_prop",]$`0.5quant`, result[[i]]$summary.fixed["L1_log10:L2_prop",]$`0.975quant`) + social_effects_matrix_L1_L2_prop[i, 4] <- predterms_short[[i]] + social_effects_matrix_L1_L2_prop[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_L1_L2_prop[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["L1_log10:L2_prop"]])) + colnames(marginals_fixed_list_L1_L2_prop[[i]]) <- c("x for L1*L2 proportion", "y for L1*L2 proportion") + } + + if(i %in% neighbour_element) { + social_effects_matrix_N[i, 1:3] <- c(result[[i]]$summary.fixed[2,]$`0.025quant`, result[[i]]$summary.fixed[2,]$`0.5quant`, result[[i]]$summary.fixed[2,]$`0.975quant`) + social_effects_matrix_N[i, 4] <- predterms_short[[i]] + social_effects_matrix_N[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_N[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][[2]])) + colnames(marginals_fixed_list_N[[i]]) <- c("x for Neighbours", "y for Neighbours") + } + + if(i %in% official_element) { + social_effects_matrix_O[i, 1:3] <- c(result[[i]]$summary.fixed[2,]$`0.025quant`, result[[i]]$summary.fixed[2,]$`0.5quant`, result[[i]]$summary.fixed[2,]$`0.975quant`) + social_effects_matrix_O[i, 4] <- predterms_short[[i]] + social_effects_matrix_O[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_O[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][[2]])) + colnames(marginals_fixed_list_O[[i]]) <- c("x for Official", "y for Official") + } + + if(i %in% education_element) { + social_effects_matrix_E[i, 1:3] <- c(result[[i]]$summary.fixed[2,]$`0.025quant`, result[[i]]$summary.fixed[2,]$`0.5quant`, result[[i]]$summary.fixed[2,]$`0.975quant`) + social_effects_matrix_E[i, 4] <- predterms_short[[i]] + social_effects_matrix_E[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_E[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][[2]])) + colnames(marginals_fixed_list_E[[i]]) <- c("x for Education", "y for Education") + } + + fitted_list[[i]] <- result[[i]]$summary.fitted.values + fitted_list[[i]] <- fitted_list[[i]] %>% + mutate(across(where(is.numeric), round, 2)) + + marginals_hyperpar_list_gaussian[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for the Gaussian observations"]])) + colnames(marginals_hyperpar_list_gaussian[[i]]) <- c("x for the Gaussian observations", "y for the Gaussian observations") + + if(i %in% L1_nl_element){ + marginals_hyperpar_list_social_L1_nl[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for inla.group(L1_copy)"]])) + colnames(marginals_hyperpar_list_social_L1_nl[[i]]) <- c("x for inla.group(L1_copy)", "y for inla.group(L1_copy)") + } + + if(i %in% L2_prop_nl_element){ + marginals_hyperpar_list_social_L2_prop_nl[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for inla.group(L2_copy)"]])) + colnames(marginals_hyperpar_list_social_L2_prop_nl[[i]]) <- c("x for inla.group(L2_copy)", "y for inla.group(L2_copy)") + } +} + +#beepr::beep(5) + +save(result, file = "output_models/models_Informativity_social_only.RData") + + +coefm <- as.data.frame(cbind(predterms_short, coefm)) +colnames(coefm) <- c("model", "WAIC") +coefm <- coefm %>% + mutate(across(.cols=2, as.numeric)) %>% + mutate(across(where(is.numeric), round, 2)) %>% + arrange(WAIC) + +coefm$WAIC <- as.numeric(coefm$WAIC) +coefm <- coefm[order(coefm$WAIC),] + +coefm_path <- paste("output_tables/", "waics", "Informativity_social_only_models", ".csv", collapse = "") +write.csv(coefm, coefm_path, row.names=FALSE) + +for (i in 1:length(fitted_list)) { + fitted_list[[i]]$model <- names(fitted_list)[i] +} +fitted_list <- dplyr::bind_rows(fitted_list) +fitted_list_path <- paste("output_tables/", "fitted_list", "Informativity_social_only_models", ".csv", collapse = "") +write.csv(fitted_list, fitted_list_path) + +intercept_effects <- as.data.frame(intercept_matrix) +L1_effects <- as.data.frame(social_effects_matrix_L1) +L1_nl_effects <- as.data.frame(social_effects_matrix_L1_nl) +L2_prop_effects <- as.data.frame(social_effects_matrix_L2_prop) +L2_prop_nl_effects <- as.data.frame(social_effects_matrix_L2_prop_nl) +N_effects<-as.data.frame(social_effects_matrix_N) +E_effects<-as.data.frame(social_effects_matrix_E) +O_effects<-as.data.frame(social_effects_matrix_O) +interaction_effects <- as.data.frame(social_effects_matrix_L1_L2_prop) + +intercept_effects$effect <- "Intercept" +L1_effects$effect <- "L1" +L1_nl_effects$effect <- "social SD:\nL1" +L2_prop_effects$effect <- "L2 proportion" +L2_prop_nl_effects$effect <- "social SD:\nL2 proportion" +N_effects$effect <- "Neighbours" +E_effects$effect <- "Education" +O_effects$effect <- "Official status" +interaction_effects$effect <- "L1*L2 proportion" + +effs <- as.data.frame(rbind(intercept_effects, L1_effects, L1_nl_effects, L2_prop_effects, L2_prop_nl_effects, N_effects, O_effects, E_effects, interaction_effects)) +effs <- effs %>% + mutate(across(.cols=c(1:3, 5), as.numeric)) %>% + mutate(across(where(is.numeric), round, 2)) %>% + na.omit() %>% + arrange(WAIC) %>% + relocate(model) + +effs_path <- paste("output_tables/", "effects", "Informativity_social_only_models", ".csv", collapse = "") +write.csv(effs, effs_path, row.names=FALSE) + +effs <- read.csv("output_tables/ effects Informativity_social_only_models .csv") + +effs_table_SM <- effs %>% + rename("2.5%"=2, + "50%" = 4, + "97.5%" = 3) %>% + flextable() %>% + autofit() %>% + merge_v(j=c("model", "WAIC")) %>% + fix_border_issues() %>% + border_inner_h() + +save_as_docx( + "Effects in informativity models with fixed and random effects (including non-linear implementations of some fixed effects)" = effs_table_SM, + path = "output_tables/table_SM_effects_Informativity_social_only_models.docx") + +effs_table_Main <- effs %>% + rename("2.5%"=2, + "50%" = 4, + "97.5%" = 3) %>% + filter(!grepl("nonlinear", model)) + +effs_table_Main$model <- gsub("(\\s*\\(\\w+\\))", "", effs_table_Main$model) + +effs_table_Main <- effs_table_Main %>% + flextable() %>% + autofit() %>% + merge_v(j=c("model", "WAIC")) %>% + fix_border_issues() %>% + border_inner_h() + +save_as_docx( + "Effects in informativity models with fixed and random effects" = effs_table_Main, + path = "output_tables/table_Main_effects_Informativity_social_only_models.docx") + + +effs_plot <- effs %>% + #filter(WAIC <= top_9) %>% + rename(lower=2, + upper = 4, + mean = 3) %>% #mean here refers to 0.5 quantile + #filter(!effect == "Intercept") %>% + mutate(effect = factor(effect, levels=c("Intercept", "social SD:\nL1", "L1", "social SD:\nL2 proportion", "L2 proportion", "Neighbours", "Education", "Official status", "L1*L2 proportion"))) %>% + mutate(WAIC = round(WAIC, 2)) %>% + unite("model", model, WAIC, sep = ",\nWAIC: ", remove=FALSE) %>% + group_by(WAIC) %>% + arrange(WAIC) %>% + mutate(model = forcats::fct_reorder(as.factor(model), WAIC)) %>% #reordering levels within model based on WAIC values + mutate(model = factor(model, levels=rev(levels(model)))) #reversing the order + + +#plot modified from function ggregplot::Efxplot +cols = c(brewer.pal(12, "Paired")) +cols = c("gray50", cols[c(1:8)]) + +show_col(cols) + +plot_1 <- ggplot(effs_plot, + aes(y = as.factor(model), + x = mean, + group = effect, + colour = effect)) + + geom_pointrangeh(aes(xmin = lower, xmax = upper), position = position_dodge(w = 0.9), size = 1.5) + + geom_vline(aes(xintercept = 0),lty = 2) + labs(x = NULL) + #coord_flip() + + scale_color_manual(values=cols) + + ylab("Model of informativity") + xlab("Estimate") + labs(color = "Effect") + theme_classic() + + theme(axis.text=element_text(size=50), + legend.text=element_text(size=50), + axis.title=element_text(size=50), + legend.title=element_text(size=50), + legend.spacing.y = unit(1.5, 'cm')) + + guides(color = guide_legend(reverse = TRUE, byrow = TRUE)) + + + +#plot_1 +ggsave(filename = 'output/SP_models_plot_Informativity_social_only_models.jpg', + plot_1, height = 20, width = 45) + + +#saving hyperparameters: Gaussian observations +for (i in 1:length(marginals_hyperpar_list_gaussian)) { + marginals_hyperpar_list_gaussian[[i]]$model <- names(marginals_hyperpar_list_gaussian)[i] +} +marginals_hyperpar_list_gaussian <- dplyr::bind_rows(marginals_hyperpar_list_gaussian) + +write.csv(marginals_hyperpar_list_gaussian, "output_tables/Informativity_social_only_models_marginals_hyperpar_gaussian.csv") \ No newline at end of file diff --git a/101/replication_package/output/Bound_morph/bound_morph_score.tsv b/101/replication_package/output/Bound_morph/bound_morph_score.tsv new file mode 100644 index 0000000000000000000000000000000000000000..61f957e1f248a118c0457894c83102edd616b4db --- /dev/null +++ b/101/replication_package/output/Bound_morph/bound_morph_score.tsv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ecd0d3d93eb4ab4d6e6878d47926bfdf88d788d4d95405bb7afc948079ca2951 +size 69462 diff --git a/101/replication_package/output/Informativity/informativity_score.tsv b/101/replication_package/output/Informativity/informativity_score.tsv new file mode 100644 index 0000000000000000000000000000000000000000..82560fca5f2173921d60738746fddcacdf24f477 --- /dev/null +++ b/101/replication_package/output/Informativity/informativity_score.tsv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:118f1ae7e51f874190a34faeef6a146e728c4cfeb200d6aa46f1d638a6c33e16 +size 69173 diff --git a/101/replication_package/output_tables/ effects Boundness_phylogenetic_spatial_models .csv b/101/replication_package/output_tables/ effects Boundness_phylogenetic_spatial_models .csv new file mode 100644 index 0000000000000000000000000000000000000000..ce9001adc38548bac939d693730a67eef3be351a --- /dev/null +++ b/101/replication_package/output_tables/ effects Boundness_phylogenetic_spatial_models .csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cfed9a25867240132c4fe5904e664139fbd556356b471fa8b4eab904770d5f93 +size 1024 diff --git a/101/replication_package/output_tables/ effects Boundness_social_models .csv b/101/replication_package/output_tables/ effects Boundness_social_models .csv new file mode 100644 index 0000000000000000000000000000000000000000..6e1f3e386345b13cf6a5407b38fe8202e8597b8e --- /dev/null +++ b/101/replication_package/output_tables/ effects Boundness_social_models .csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bee79ae8c8236dd59b5d42bad83276e804026345fb63236d437f28a303c84ce5 +size 3976 diff --git a/101/replication_package/output_tables/ effects Boundness_social_models prior_0.01 .csv b/101/replication_package/output_tables/ effects Boundness_social_models prior_0.01 .csv new file mode 100644 index 0000000000000000000000000000000000000000..4f117e31aac5b07de8a1ff5f15380e455132a3bf --- /dev/null +++ b/101/replication_package/output_tables/ effects Boundness_social_models prior_0.01 .csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f2e7d56a2f09b6efd8ffd98fa108ff67b2f204830629595847a27aea81149939 +size 3959 diff --git a/101/replication_package/output_tables/ effects Boundness_social_models prior_0.5 .csv b/101/replication_package/output_tables/ effects Boundness_social_models prior_0.5 .csv new file mode 100644 index 0000000000000000000000000000000000000000..00fb226008b2d3d3549578b08104d0a2f818dce7 --- /dev/null +++ b/101/replication_package/output_tables/ effects Boundness_social_models prior_0.5 .csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:19e65e55557d35a540bb0b12107b4b4e1eeb81a7fda23a566493687a8476fead +size 3966 diff --git a/101/replication_package/output_tables/ effects Boundness_social_models prior_0.99 .csv b/101/replication_package/output_tables/ effects Boundness_social_models prior_0.99 .csv new file mode 100644 index 0000000000000000000000000000000000000000..bae4f86ea1fa62e085ef30974463e0a2f6f85fba --- /dev/null +++ b/101/replication_package/output_tables/ effects Boundness_social_models prior_0.99 .csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d25006009459bee25ec627686ed01fd8a872b8e05311a17995cdc2bd341ade26 +size 3964 diff --git a/101/replication_package/output_tables/ effects Boundness_social_only_models .csv b/101/replication_package/output_tables/ effects Boundness_social_only_models .csv new file mode 100644 index 0000000000000000000000000000000000000000..b31bef366ffa55870ce1513cb123fb56ec7b279f --- /dev/null +++ b/101/replication_package/output_tables/ effects Boundness_social_only_models .csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bc3187df105f34b9934146aa4f8e2d4d067be5046b32843981bb2f0db02b3048 +size 1503 diff --git a/101/replication_package/output_tables/ effects Informativity_phylogenetic_spatial_models .csv b/101/replication_package/output_tables/ effects Informativity_phylogenetic_spatial_models .csv new file mode 100644 index 0000000000000000000000000000000000000000..dfc8a9180ac19b37c9f3a3268267154ae0391c57 --- /dev/null +++ b/101/replication_package/output_tables/ effects Informativity_phylogenetic_spatial_models .csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b02524f6fa89828f8166fc4256bc38057f3e956973f6fd60580dda0b701ce7ac +size 1040 diff --git a/101/replication_package/output_tables/ effects Informativity_social_models .csv b/101/replication_package/output_tables/ effects Informativity_social_models .csv new file mode 100644 index 0000000000000000000000000000000000000000..5199d60a5b1a6877cda8d86f5059ebc2cefed6f7 --- /dev/null +++ b/101/replication_package/output_tables/ effects Informativity_social_models .csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c6d195a99e05dd02ec13cc2a60a70eab930ae4121d617662b609c0a4cfd90eaa +size 3814 diff --git a/101/replication_package/output_tables/ effects Informativity_social_models prior_0.01 .csv b/101/replication_package/output_tables/ effects Informativity_social_models prior_0.01 .csv new file mode 100644 index 0000000000000000000000000000000000000000..8d578466620ad0468340fd0c603fc211e1118325 --- /dev/null +++ b/101/replication_package/output_tables/ effects Informativity_social_models prior_0.01 .csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:51c12456fd7ebcb0900fbe4915a6c9bd1b0f2a76826c8db726118b192bb57101 +size 3988 diff --git a/101/replication_package/output_tables/ effects Informativity_social_models prior_0.5 .csv b/101/replication_package/output_tables/ effects Informativity_social_models prior_0.5 .csv new file mode 100644 index 0000000000000000000000000000000000000000..c5f1f0b9199d898826ceaf91fc31d4c92fc10cb5 --- /dev/null +++ b/101/replication_package/output_tables/ effects Informativity_social_models prior_0.5 .csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:411509ed65a4d4ad8e72170b9f61ba604d985e0f66b9329b87ea5d7a0d054ec8 +size 3984 diff --git a/101/replication_package/output_tables/ effects Informativity_social_models prior_0.99 .csv b/101/replication_package/output_tables/ effects Informativity_social_models prior_0.99 .csv new file mode 100644 index 0000000000000000000000000000000000000000..ba0bdf1fa79e784d14cbcfb59851663db3492511 --- /dev/null +++ b/101/replication_package/output_tables/ effects Informativity_social_models prior_0.99 .csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e95581eb8f4433c7c0a08cebb20face913ce91a5b1b942de1ddbfbae66a98a5c +size 3969 diff --git a/101/replication_package/output_tables/ effects Informativity_social_only_models .csv b/101/replication_package/output_tables/ effects Informativity_social_only_models .csv new file mode 100644 index 0000000000000000000000000000000000000000..0685c2a7793230a532d29d0bb80ede0e7c39b6a2 --- /dev/null +++ b/101/replication_package/output_tables/ effects Informativity_social_only_models .csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:32223f519df73decd3015e43284f9e3465685ebf92158f17e5511e04cf9e82fc +size 1503 diff --git a/101/replication_package/output_tables/ fitted_list Boundness_phylogenetic_spatial_models .csv b/101/replication_package/output_tables/ fitted_list Boundness_phylogenetic_spatial_models .csv new file mode 100644 index 0000000000000000000000000000000000000000..253b49206d763e1d6f1a9720f55375de89385e9c --- /dev/null +++ b/101/replication_package/output_tables/ fitted_list Boundness_phylogenetic_spatial_models .csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cd7b856f424039989d81976ba20612d64ffbaf62e642bab42f867ecc63a556dd +size 766250 diff --git a/101/replication_package/output_tables/ fitted_list Boundness_social_models .csv b/101/replication_package/output_tables/ fitted_list Boundness_social_models .csv new file mode 100644 index 0000000000000000000000000000000000000000..ebd24b696431ecda6ac131414bd3cf94efb963bb --- /dev/null +++ b/101/replication_package/output_tables/ fitted_list Boundness_social_models .csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:04549649f8a82153b500dee215b8d5efff7017d8d4bbc852a3e4450cd3f032ad +size 1548614 diff --git a/101/replication_package/output_tables/ fitted_list Boundness_social_only_models .csv b/101/replication_package/output_tables/ fitted_list Boundness_social_only_models .csv new file mode 100644 index 0000000000000000000000000000000000000000..f87d87fc88af6f399f1a2b17fefd2d76f79cc6eb --- /dev/null +++ b/101/replication_package/output_tables/ fitted_list Boundness_social_only_models .csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:def02becb02871653a5ac69158fcc4d5b6d3b0589eb3783a40d8cd1d8b1884c1 +size 1191605 diff --git a/101/replication_package/output_tables/ fitted_list Informativity_phylogenetic_spatial_models .csv b/101/replication_package/output_tables/ fitted_list Informativity_phylogenetic_spatial_models .csv new file mode 100644 index 0000000000000000000000000000000000000000..3c129816b37537f0a73cfd353c2ab5c68571270a --- /dev/null +++ b/101/replication_package/output_tables/ fitted_list Informativity_phylogenetic_spatial_models .csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:91c9d7951e518f739d5083168098240138a074d693cb018495934c79f558e87d +size 766411 diff --git a/101/replication_package/output_tables/ fitted_list Informativity_social_models .csv b/101/replication_package/output_tables/ fitted_list Informativity_social_models .csv new file mode 100644 index 0000000000000000000000000000000000000000..0ac1b069703df14b5415ffa8e5f2d27147563a68 --- /dev/null +++ b/101/replication_package/output_tables/ fitted_list Informativity_social_models .csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:20fce3c2ab18bcb83b07e60714a446c77d75eaec592b3089eb83e17a6590a59d +size 1549221 diff --git a/101/replication_package/output_tables/ fitted_list Informativity_social_only_models .csv b/101/replication_package/output_tables/ fitted_list Informativity_social_only_models .csv new file mode 100644 index 0000000000000000000000000000000000000000..e73b0a5c29ddf11cfd7fdf5333868d5c89642aed --- /dev/null +++ b/101/replication_package/output_tables/ fitted_list Informativity_social_only_models .csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9f38d52300c9d75ab6e026510bb489ce3c15f38d436c714f3cf3ad1844ef4f22 +size 1153814 diff --git a/101/replication_package/output_tables/ waics Boundness_phylogenetic_spatial_models .csv b/101/replication_package/output_tables/ waics Boundness_phylogenetic_spatial_models .csv new file mode 100644 index 0000000000000000000000000000000000000000..75234a15c247e0bf1acdd228bbeeec6a151f0caa --- /dev/null +++ b/101/replication_package/output_tables/ waics Boundness_phylogenetic_spatial_models .csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f6f00c32bb0049b6df63ac8d37878f58ffda7b28f5b1f75aba8d174ebeb84330 +size 214 diff --git a/101/replication_package/output_tables/ waics Boundness_social_models .csv b/101/replication_package/output_tables/ waics Boundness_social_models .csv new file mode 100644 index 0000000000000000000000000000000000000000..ab877ce4bd61722c9f53ae8f658844f89a89f05f --- /dev/null +++ b/101/replication_package/output_tables/ waics Boundness_social_models .csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:14b6b8761767a762e40d4497fbef1b650b55f7984723c901e772e428e89edacf +size 645 diff --git a/101/replication_package/output_tables/ waics Boundness_social_models prior_0.01 .csv b/101/replication_package/output_tables/ waics Boundness_social_models prior_0.01 .csv new file mode 100644 index 0000000000000000000000000000000000000000..1658231560c660caf34f13f440e91824dea9c2a5 --- /dev/null +++ b/101/replication_package/output_tables/ waics Boundness_social_models prior_0.01 .csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2899126e443c5a4a9fc1127ae18d5ee25cfd3e1978f6c150876f222a8fa21ffd +size 640 diff --git a/101/replication_package/output_tables/ waics Boundness_social_models prior_0.5 .csv b/101/replication_package/output_tables/ waics Boundness_social_models prior_0.5 .csv new file mode 100644 index 0000000000000000000000000000000000000000..a8b29300ba02dd39d6b959f471b762bbe219167e --- /dev/null +++ b/101/replication_package/output_tables/ waics Boundness_social_models prior_0.5 .csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5087ff03c779361cb7ee9ac5aafe6d540c6f8fcd9b6756d9c163bbe26cbccab4 +size 642 diff --git a/101/replication_package/output_tables/ waics Boundness_social_models prior_0.99 .csv b/101/replication_package/output_tables/ waics Boundness_social_models prior_0.99 .csv new file mode 100644 index 0000000000000000000000000000000000000000..57757a3532963f692dccb8e884e448046550a7b7 --- /dev/null +++ b/101/replication_package/output_tables/ waics Boundness_social_models prior_0.99 .csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:611919800a767705963974dfde41aafa1ad86f8c842c65616541245d3c41b780 +size 644 diff --git a/101/replication_package/output_tables/ waics Boundness_social_only_models .csv b/101/replication_package/output_tables/ waics Boundness_social_only_models .csv new file mode 100644 index 0000000000000000000000000000000000000000..d655ccb8b0b364e530a1aeb5f8f5c33877818305 --- /dev/null +++ b/101/replication_package/output_tables/ waics Boundness_social_only_models .csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6bdb8e5143a14fbb02296595627dc56cfb33b323732a294d563bcf2e4f1328db +size 364 diff --git a/101/replication_package/output_tables/ waics Informativity_phylogenetic_spatial_models .csv b/101/replication_package/output_tables/ waics Informativity_phylogenetic_spatial_models .csv new file mode 100644 index 0000000000000000000000000000000000000000..fc2520d0d9896046d97cbbee2fb990b987fd9d13 --- /dev/null +++ b/101/replication_package/output_tables/ waics Informativity_phylogenetic_spatial_models .csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:09ed8da885df59d9104673154a52e8d928830e8552318dc5740a3c5dc9da8bbb +size 214 diff --git a/101/replication_package/output_tables/ waics Informativity_social_models .csv b/101/replication_package/output_tables/ waics Informativity_social_models .csv new file mode 100644 index 0000000000000000000000000000000000000000..16b34e2ada69814892ba06e1f0c2877af66e845b --- /dev/null +++ b/101/replication_package/output_tables/ waics Informativity_social_models .csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bf8ff7b195630041f0694a3f5dc5366ffed0a6911dc37b9789d3290f18a78eb9 +size 645 diff --git a/101/replication_package/output_tables/ waics Informativity_social_models prior_0.01 .csv b/101/replication_package/output_tables/ waics Informativity_social_models prior_0.01 .csv new file mode 100644 index 0000000000000000000000000000000000000000..9702f1c1befa9f247de0761b0beaef1d44add38e --- /dev/null +++ b/101/replication_package/output_tables/ waics Informativity_social_models prior_0.01 .csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fc61dc3985828e1acd6a10d5364f0ffe1dd2c289bc156a1dc17679b5bf560e0a +size 645 diff --git a/101/replication_package/output_tables/ waics Informativity_social_models prior_0.5 .csv b/101/replication_package/output_tables/ waics Informativity_social_models prior_0.5 .csv new file mode 100644 index 0000000000000000000000000000000000000000..20f45fc9289ad8be21020cf9c18a1b8c8e998aca --- /dev/null +++ b/101/replication_package/output_tables/ waics Informativity_social_models prior_0.5 .csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0a69b6f1fbd39f2604e6a8f57dfa8fbca8cd03b4863fb3cf38f24393b9d3de83 +size 645 diff --git a/101/replication_package/output_tables/ waics Informativity_social_models prior_0.99 .csv b/101/replication_package/output_tables/ waics Informativity_social_models prior_0.99 .csv new file mode 100644 index 0000000000000000000000000000000000000000..eb0c17e2f5dd03b2f50362753220cabb46a73a1d --- /dev/null +++ b/101/replication_package/output_tables/ waics Informativity_social_models prior_0.99 .csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8ae81a58dddc8a2612e3b4c08605b97e8a5788f4a9e06bbfc6532ae9c188815d +size 641 diff --git a/101/replication_package/output_tables/ waics Informativity_social_only_models .csv b/101/replication_package/output_tables/ waics Informativity_social_only_models .csv new file mode 100644 index 0000000000000000000000000000000000000000..7493c3d589ecaf679ab3b0bba9411f559af89ceb --- /dev/null +++ b/101/replication_package/output_tables/ waics Informativity_social_only_models .csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d550f6698bb5679cf9cf4e9c815899f81e2946790bb6615fa5ee884810ea0e0c +size 364 diff --git a/101/replication_package/output_tables/Boundness_phylogenetic_spatial_models_marginals_hyperpar_areal.csv b/101/replication_package/output_tables/Boundness_phylogenetic_spatial_models_marginals_hyperpar_areal.csv new file mode 100644 index 0000000000000000000000000000000000000000..1edf6d6946c1c4cb74d840d052ab1a0c5af0a9f8 --- /dev/null +++ b/101/replication_package/output_tables/Boundness_phylogenetic_spatial_models_marginals_hyperpar_areal.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e06ff404801837af4662af3ea9a6b0923df69974dc6e849a3add74d7cab5ca94 +size 4962 diff --git a/101/replication_package/output_tables/Boundness_phylogenetic_spatial_models_marginals_hyperpar_gaussian.csv b/101/replication_package/output_tables/Boundness_phylogenetic_spatial_models_marginals_hyperpar_gaussian.csv new file mode 100644 index 0000000000000000000000000000000000000000..205bc5c0a8c752f1c01f850cc83a03d89d3026c9 --- /dev/null +++ b/101/replication_package/output_tables/Boundness_phylogenetic_spatial_models_marginals_hyperpar_gaussian.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a03982cd5ded8faec0ad4581d5ec1d480160b428d9890ea8925e66d1ccb3c42c +size 18438 diff --git a/101/replication_package/output_tables/Boundness_phylogenetic_spatial_models_marginals_hyperpar_phylogenetic.csv b/101/replication_package/output_tables/Boundness_phylogenetic_spatial_models_marginals_hyperpar_phylogenetic.csv new file mode 100644 index 0000000000000000000000000000000000000000..e39286041d50f500d6f699c5b09f8326242cbf71 --- /dev/null +++ b/101/replication_package/output_tables/Boundness_phylogenetic_spatial_models_marginals_hyperpar_phylogenetic.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:50a5fca8e2b15283fbaa91ce19d47b532109ddd09ea7020c49ce83188429d43c +size 11360 diff --git a/101/replication_package/output_tables/Boundness_phylogenetic_spatial_models_marginals_hyperpar_spatial.csv b/101/replication_package/output_tables/Boundness_phylogenetic_spatial_models_marginals_hyperpar_spatial.csv new file mode 100644 index 0000000000000000000000000000000000000000..4f8b799780228c202bc35694966c05a8e3fd52aa --- /dev/null +++ b/101/replication_package/output_tables/Boundness_phylogenetic_spatial_models_marginals_hyperpar_spatial.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bb0deb60c19a67a6ba7ade70ee0c6ea8c07e13cf7ae15fb80e6de9c35df8ff6e +size 11371 diff --git a/101/replication_package/output_tables/Boundness_phylogenetic_spatial_models_summary_random_areas.csv b/101/replication_package/output_tables/Boundness_phylogenetic_spatial_models_summary_random_areas.csv new file mode 100644 index 0000000000000000000000000000000000000000..1ef69f3f1b2d0c29c22e12d322e766cf9579ca1b --- /dev/null +++ b/101/replication_package/output_tables/Boundness_phylogenetic_spatial_models_summary_random_areas.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:59a75eb40fbda7668a50f8271ad833fdfe96ad913fb174ea857e3b2e3ee2b9ad +size 3622 diff --git a/101/replication_package/output_tables/Boundness_phylogenetic_spatial_models_summary_random_phy.csv b/101/replication_package/output_tables/Boundness_phylogenetic_spatial_models_summary_random_phy.csv new file mode 100644 index 0000000000000000000000000000000000000000..36cdb122c6a62652e5c37ad99e3f0ce4d5fede16 --- /dev/null +++ b/101/replication_package/output_tables/Boundness_phylogenetic_spatial_models_summary_random_phy.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e124240a4e4dc6401f6f22d6267e9bbb0a3b6071d3948367ebdea33b3289d247 +size 736900 diff --git a/101/replication_package/output_tables/Boundness_phylogenetic_spatial_models_summary_random_spa.csv b/101/replication_package/output_tables/Boundness_phylogenetic_spatial_models_summary_random_spa.csv new file mode 100644 index 0000000000000000000000000000000000000000..397b35e7924b6520458e6cbe165fd73fb091a56b --- /dev/null +++ b/101/replication_package/output_tables/Boundness_phylogenetic_spatial_models_summary_random_spa.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e7ee758a7eb98dc5fa01a924b2656ed3c2eedd6c1f986c1afcb33733ca94828f +size 365926 diff --git a/101/replication_package/output_tables/Boundness_social_models_marginals_hyperpar_gaussian.csv b/101/replication_package/output_tables/Boundness_social_models_marginals_hyperpar_gaussian.csv new file mode 100644 index 0000000000000000000000000000000000000000..6439b280a026a922a77421a324d05033dbced211 --- /dev/null +++ b/101/replication_package/output_tables/Boundness_social_models_marginals_hyperpar_gaussian.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b07531abfbbe2384e458e3612c4af0fae7313fde90163e1d2dee388ef72a8b8d +size 41345 diff --git a/101/replication_package/output_tables/Boundness_social_models_marginals_hyperpar_phylogenetic.csv b/101/replication_package/output_tables/Boundness_social_models_marginals_hyperpar_phylogenetic.csv new file mode 100644 index 0000000000000000000000000000000000000000..8a57db76d98781f87d35d87b904390587e34de24 --- /dev/null +++ b/101/replication_package/output_tables/Boundness_social_models_marginals_hyperpar_phylogenetic.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:479cff0baeb360ba43de1d26217f787d89a577ca26b5c08ff6afab8f1dcbe56f +size 41323 diff --git a/101/replication_package/output_tables/Boundness_social_models_marginals_hyperpar_spatial.csv b/101/replication_package/output_tables/Boundness_social_models_marginals_hyperpar_spatial.csv new file mode 100644 index 0000000000000000000000000000000000000000..48211dfc9a1615d2d2fa96d20eae073ff49038e9 --- /dev/null +++ b/101/replication_package/output_tables/Boundness_social_models_marginals_hyperpar_spatial.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d705b63f31958718504465b958e72f5e37ffd11935cad28ade111c502c5b92ed +size 41349 diff --git a/101/replication_package/output_tables/Boundness_social_models_summary_random_phy.csv b/101/replication_package/output_tables/Boundness_social_models_summary_random_phy.csv new file mode 100644 index 0000000000000000000000000000000000000000..99b1a5e1691b703bfee67bebe2eca4758bbe9d60 --- /dev/null +++ b/101/replication_package/output_tables/Boundness_social_models_summary_random_phy.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:79fe266a5e384b8476018d1e2b351d361ee06222c5b22c2e786d99aab90518bd +size 2651911 diff --git a/101/replication_package/output_tables/Boundness_social_models_summary_random_spa.csv b/101/replication_package/output_tables/Boundness_social_models_summary_random_spa.csv new file mode 100644 index 0000000000000000000000000000000000000000..a6971bf3933aa66a243599039ddcd4c87ab74b45 --- /dev/null +++ b/101/replication_package/output_tables/Boundness_social_models_summary_random_spa.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:4f70b0a5f8f0711f8d3504393c52e07fb269fa2b030907fbca6d1e8f49782346 +size 1312942 diff --git a/101/replication_package/output_tables/Boundness_social_only_models_marginals_hyperpar_gaussian.csv b/101/replication_package/output_tables/Boundness_social_only_models_marginals_hyperpar_gaussian.csv new file mode 100644 index 0000000000000000000000000000000000000000..313cb9b885170759d7758cff0285bab3a0fb2cb7 --- /dev/null +++ b/101/replication_package/output_tables/Boundness_social_only_models_marginals_hyperpar_gaussian.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f07080d836ddb3b002713220a42a5528a853749c592ec4f149305227a4737d63 +size 28931 diff --git a/101/replication_package/output_tables/Informativity_phylogenetic_spatial_models_marginals_hyperpar_areal.csv b/101/replication_package/output_tables/Informativity_phylogenetic_spatial_models_marginals_hyperpar_areal.csv new file mode 100644 index 0000000000000000000000000000000000000000..d98a59e07db4d968ae05f074afb2faebb34378fd --- /dev/null +++ b/101/replication_package/output_tables/Informativity_phylogenetic_spatial_models_marginals_hyperpar_areal.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:77ab821e6da172d454bc3683acc1912241f4fd0cd67a5717b3dc583daf9a6cf1 +size 4993 diff --git a/101/replication_package/output_tables/Informativity_phylogenetic_spatial_models_marginals_hyperpar_gaussian.csv b/101/replication_package/output_tables/Informativity_phylogenetic_spatial_models_marginals_hyperpar_gaussian.csv new file mode 100644 index 0000000000000000000000000000000000000000..a9a3dd2db23886a74f0c11bfb826f97d21a8d31b --- /dev/null +++ b/101/replication_package/output_tables/Informativity_phylogenetic_spatial_models_marginals_hyperpar_gaussian.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a811e37d3128ffa1de66fb14578c8fb3c73655bb9020267aeb1872899adbcd22 +size 18302 diff --git a/101/replication_package/output_tables/Informativity_phylogenetic_spatial_models_marginals_hyperpar_phylogenetic.csv b/101/replication_package/output_tables/Informativity_phylogenetic_spatial_models_marginals_hyperpar_phylogenetic.csv new file mode 100644 index 0000000000000000000000000000000000000000..c11c1a9e75b2a9374ae902678e8898d2c18af25b --- /dev/null +++ b/101/replication_package/output_tables/Informativity_phylogenetic_spatial_models_marginals_hyperpar_phylogenetic.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:deef69795310afaf6099fd72963962fa6d18ae758bce2df39f28a0789b50187c +size 11368 diff --git a/101/replication_package/output_tables/Informativity_phylogenetic_spatial_models_marginals_hyperpar_spatial.csv b/101/replication_package/output_tables/Informativity_phylogenetic_spatial_models_marginals_hyperpar_spatial.csv new file mode 100644 index 0000000000000000000000000000000000000000..3126e301fbe8af93c49d973ccd83d4454041f271 --- /dev/null +++ b/101/replication_package/output_tables/Informativity_phylogenetic_spatial_models_marginals_hyperpar_spatial.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dbb130c8e49d3aa47262c37c55aa002da9f671412899325dc85ba7646bb6690f +size 11376 diff --git a/101/replication_package/output_tables/Informativity_phylogenetic_spatial_models_summary_random_areas.csv b/101/replication_package/output_tables/Informativity_phylogenetic_spatial_models_summary_random_areas.csv new file mode 100644 index 0000000000000000000000000000000000000000..dbe22b886550fcbb1e10e29be9dafe5739ec0592 --- /dev/null +++ b/101/replication_package/output_tables/Informativity_phylogenetic_spatial_models_summary_random_areas.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c6c2e3314309870d011fdb84f9a6326a1660ea1fac769ade1e31e12ac40b5c77 +size 3587 diff --git a/101/replication_package/output_tables/Informativity_phylogenetic_spatial_models_summary_random_phy.csv b/101/replication_package/output_tables/Informativity_phylogenetic_spatial_models_summary_random_phy.csv new file mode 100644 index 0000000000000000000000000000000000000000..42812529c67477a25fffc665f144734d0cf84383 --- /dev/null +++ b/101/replication_package/output_tables/Informativity_phylogenetic_spatial_models_summary_random_phy.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c4ab0e526c3530ea1b3d42e3fc6d8f2a2999d336248e5bf3102819f76778a47d +size 738211 diff --git a/101/replication_package/output_tables/Informativity_phylogenetic_spatial_models_summary_random_spa.csv b/101/replication_package/output_tables/Informativity_phylogenetic_spatial_models_summary_random_spa.csv new file mode 100644 index 0000000000000000000000000000000000000000..067d6bc7899518c1d0f5fca2c144db3b49d9faf6 --- /dev/null +++ b/101/replication_package/output_tables/Informativity_phylogenetic_spatial_models_summary_random_spa.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3eb4f17a870a446152b8b576c4d207b67968dfbcb4320f8a7b0e6290cb0d3577 +size 367372 diff --git a/101/replication_package/output_tables/Informativity_social_models_marginals_hyperpar_gaussian.csv b/101/replication_package/output_tables/Informativity_social_models_marginals_hyperpar_gaussian.csv new file mode 100644 index 0000000000000000000000000000000000000000..dace522b6220846c8f8eda9b153212f3ab1c229d --- /dev/null +++ b/101/replication_package/output_tables/Informativity_social_models_marginals_hyperpar_gaussian.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fbfac4e468893bdd2df21c71968e103a36ac85857d9e7a57481e51b7e7350a02 +size 40952 diff --git a/101/replication_package/output_tables/Informativity_social_models_marginals_hyperpar_phylogenetic.csv b/101/replication_package/output_tables/Informativity_social_models_marginals_hyperpar_phylogenetic.csv new file mode 100644 index 0000000000000000000000000000000000000000..3be2450a290abe154eee090c1cd67e1d25f4b3b1 --- /dev/null +++ b/101/replication_package/output_tables/Informativity_social_models_marginals_hyperpar_phylogenetic.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:518b35bd754b1e4bfcef1283f3461db4dc9d63e0cb10c6e8479c3995f9fe53ae +size 41360 diff --git a/101/replication_package/output_tables/Informativity_social_models_marginals_hyperpar_spatial.csv b/101/replication_package/output_tables/Informativity_social_models_marginals_hyperpar_spatial.csv new file mode 100644 index 0000000000000000000000000000000000000000..aefdea9f083231f08e44e0bfd8323eacac8dd40c --- /dev/null +++ b/101/replication_package/output_tables/Informativity_social_models_marginals_hyperpar_spatial.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:82ab9103daa87b1e9fa9dd88a9baca23ad9af65ff1048be77443b67d573818ec +size 41330 diff --git a/101/replication_package/output_tables/Informativity_social_models_summary_random_phy.csv b/101/replication_package/output_tables/Informativity_social_models_summary_random_phy.csv new file mode 100644 index 0000000000000000000000000000000000000000..f7d453ddcc2cc1ecb2e5c48cdc71ea0edf064540 --- /dev/null +++ b/101/replication_package/output_tables/Informativity_social_models_summary_random_phy.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8d4e126e789552ded7abaebf459648ba396b260cba185b5c465955aa91146b72 +size 2657307 diff --git a/101/replication_package/output_tables/Informativity_social_models_summary_random_spa.csv b/101/replication_package/output_tables/Informativity_social_models_summary_random_spa.csv new file mode 100644 index 0000000000000000000000000000000000000000..9202747ac1026e0b807ebeff53a8c8bd6f51aa4c --- /dev/null +++ b/101/replication_package/output_tables/Informativity_social_models_summary_random_spa.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:23b2e8de528fe2cbce77b82b48808b675a002ac5864186c253f264c28e832faf +size 1316155 diff --git a/101/replication_package/output_tables/Informativity_social_only_models_marginals_hyperpar_gaussian.csv b/101/replication_package/output_tables/Informativity_social_only_models_marginals_hyperpar_gaussian.csv new file mode 100644 index 0000000000000000000000000000000000000000..b7ffc9c696f159a5cb3bc915a2e7e53725f408a4 --- /dev/null +++ b/101/replication_package/output_tables/Informativity_social_only_models_marginals_hyperpar_gaussian.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6f86a48dafa431b66479511bc0e087770ac2ce2eef747bc75dbd512415a939f8 +size 28990 diff --git a/101/replication_package/output_tables/Table_INLA_all_models.csv b/101/replication_package/output_tables/Table_INLA_all_models.csv new file mode 100644 index 0000000000000000000000000000000000000000..fada1704a4f4c95caa619043ee1ae8d48ba106d8 --- /dev/null +++ b/101/replication_package/output_tables/Table_INLA_all_models.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:881cdc226b15e752377e406edab3609b6e2c183ccc900b66990f4948636e9cc2 +size 15708 diff --git a/101/replication_package/output_tables/Table_phylosig.csv b/101/replication_package/output_tables/Table_phylosig.csv new file mode 100644 index 0000000000000000000000000000000000000000..e91e6c419cdff86642e2a78ada9827672f4441fc --- /dev/null +++ b/101/replication_package/output_tables/Table_phylosig.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:515af7354375b0d4be35e9662b740b1e7a4a270b8f5ce992ee04208f032fed6b +size 164 diff --git a/101/replication_package/output_tables/Table_sensitivity.csv b/101/replication_package/output_tables/Table_sensitivity.csv new file mode 100644 index 0000000000000000000000000000000000000000..00884865ff256a261b4a285aaec5a5c794fe7907 --- /dev/null +++ b/101/replication_package/output_tables/Table_sensitivity.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:34f6dbff693b43f71df5c5bea62b9c1574e85ddb3ec61d2f63f501e298369803 +size 7095 diff --git a/101/replication_package/output_tables/Table_variance_top_ranking_models.csv b/101/replication_package/output_tables/Table_variance_top_ranking_models.csv new file mode 100644 index 0000000000000000000000000000000000000000..07e8e185259886660f0a7c252e22da817afaee7a --- /dev/null +++ b/101/replication_package/output_tables/Table_variance_top_ranking_models.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3aed2fef6024cf3dd08f3da2de9006e76f9337bde504fa8277defaa45e9231b7 +size 402 diff --git a/101/replication_package/output_tables/WALS_high_coverage.csv b/101/replication_package/output_tables/WALS_high_coverage.csv new file mode 100644 index 0000000000000000000000000000000000000000..ee7fb0bca41daba57965de7c9d661b83f86cc3e0 --- /dev/null +++ b/101/replication_package/output_tables/WALS_high_coverage.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f8734676e28c045c8300af5a344b5cd15e09242224982583f1628eb192baf4d8 +size 17713 diff --git a/101/replication_package/output_tables/WALS_morph_compl_effects.csv b/101/replication_package/output_tables/WALS_morph_compl_effects.csv new file mode 100644 index 0000000000000000000000000000000000000000..548f59299504de67efe5685ae6c7564eb499c543 --- /dev/null +++ b/101/replication_package/output_tables/WALS_morph_compl_effects.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2e110a7c1c5a876f0e8f294df47453ea61dfcb8942b238460bfeecbd7dff7ada +size 323 diff --git a/101/replication_package/output_tables/effects Informativity_phylogenetic_spatial_models .csv b/101/replication_package/output_tables/effects Informativity_phylogenetic_spatial_models .csv new file mode 100644 index 0000000000000000000000000000000000000000..ecb5bf64453b450df43cfa538317e276340d40b3 --- /dev/null +++ b/101/replication_package/output_tables/effects Informativity_phylogenetic_spatial_models .csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:84d00e31b798b82ad8cf8919b234339b9ecb4765b1de8d541a561f1b45164045 +size 962 diff --git a/101/replication_package/output_tables_reduced/ effects Boundness_social_models .csv b/101/replication_package/output_tables_reduced/ effects Boundness_social_models .csv new file mode 100644 index 0000000000000000000000000000000000000000..b35408b90cf7da1a7048ea87f7b0d895cc12d780 --- /dev/null +++ b/101/replication_package/output_tables_reduced/ effects Boundness_social_models .csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:920b8963ee5abf26bfb2a20c8dcfc7730c5d8bac5da81db7897c4e94240cc258 +size 3569 diff --git a/101/replication_package/output_tables_reduced/ effects Boundness_social_models prior_0.01 .csv b/101/replication_package/output_tables_reduced/ effects Boundness_social_models prior_0.01 .csv new file mode 100644 index 0000000000000000000000000000000000000000..b12d45f6a6fe43eb62f582db4e0f82e81a4b6e95 --- /dev/null +++ b/101/replication_package/output_tables_reduced/ effects Boundness_social_models prior_0.01 .csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ce1379c59f638488e03594f5c24893e4486240e552c0dc1ffb56b1859849b972 +size 3565 diff --git a/101/replication_package/output_tables_reduced/ effects Boundness_social_models prior_0.5 .csv b/101/replication_package/output_tables_reduced/ effects Boundness_social_models prior_0.5 .csv new file mode 100644 index 0000000000000000000000000000000000000000..3bb14c664be6854164162804267fbff57f071482 --- /dev/null +++ b/101/replication_package/output_tables_reduced/ effects Boundness_social_models prior_0.5 .csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:528702e7c4e255c736fb092618f586fbb67cdc27bce01f3bb8e902887d993595 +size 3559 diff --git a/101/replication_package/output_tables_reduced/ effects Boundness_social_models prior_0.99 .csv b/101/replication_package/output_tables_reduced/ effects Boundness_social_models prior_0.99 .csv new file mode 100644 index 0000000000000000000000000000000000000000..5f649481414c5d94f6590835cd7f3134f7757f73 --- /dev/null +++ b/101/replication_package/output_tables_reduced/ effects Boundness_social_models prior_0.99 .csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d24c643474a2b43f23db01b1b0cd6750b1b1319e4920107558cd796cb1ea8084 +size 3565 diff --git a/101/replication_package/output_tables_reduced/ effects Boundness_social_only_models .csv b/101/replication_package/output_tables_reduced/ effects Boundness_social_only_models .csv new file mode 100644 index 0000000000000000000000000000000000000000..1df216b69927271dfa2410c122eba8b5bd10099d --- /dev/null +++ b/101/replication_package/output_tables_reduced/ effects Boundness_social_only_models .csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0f3e075f5f49004c6bb8b58c1b06a0fa324bc52261761f1f564b25c4c05de85c +size 1357 diff --git a/101/replication_package/output_tables_reduced/ effects Informativity_social_models .csv b/101/replication_package/output_tables_reduced/ effects Informativity_social_models .csv new file mode 100644 index 0000000000000000000000000000000000000000..13afaf10a40cafdfea0f3a6805fefb2ba27e5ab2 --- /dev/null +++ b/101/replication_package/output_tables_reduced/ effects Informativity_social_models .csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1f3310811f444e73a5ccca7cdd09d245d025061834f5a2806616a8ee0ac66893 +size 3580 diff --git a/101/replication_package/output_tables_reduced/ effects Informativity_social_models prior_0.01 .csv b/101/replication_package/output_tables_reduced/ effects Informativity_social_models prior_0.01 .csv new file mode 100644 index 0000000000000000000000000000000000000000..b6663a0002e3e949f4b3c4fc5dff26f21ac59fe6 --- /dev/null +++ b/101/replication_package/output_tables_reduced/ effects Informativity_social_models prior_0.01 .csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:aab7a1ce2da308d4124e77a045783fb5a6e7bd027e59a3f7ad8ae11e547e7410 +size 3584 diff --git a/101/replication_package/output_tables_reduced/ effects Informativity_social_models prior_0.5 .csv b/101/replication_package/output_tables_reduced/ effects Informativity_social_models prior_0.5 .csv new file mode 100644 index 0000000000000000000000000000000000000000..9ece0dce8f035b1d19d8d7533917a8f716fe5a1b --- /dev/null +++ b/101/replication_package/output_tables_reduced/ effects Informativity_social_models prior_0.5 .csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5842c8d8fc3ff230931fc940b35e884420d8bc3113f76e4c6057481e2b785fd9 +size 3580 diff --git a/101/replication_package/output_tables_reduced/ effects Informativity_social_models prior_0.99 .csv b/101/replication_package/output_tables_reduced/ effects Informativity_social_models prior_0.99 .csv new file mode 100644 index 0000000000000000000000000000000000000000..a42e7c40cd1d276679a97c5e3b24b9bc69fabad8 --- /dev/null +++ b/101/replication_package/output_tables_reduced/ effects Informativity_social_models prior_0.99 .csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3db64acce43088c4cd14c560a4997d97b137ad6e1e8c7d919cb432b38d6968ec +size 3565 diff --git a/101/replication_package/output_tables_reduced/ effects Informativity_social_only_models .csv b/101/replication_package/output_tables_reduced/ effects Informativity_social_only_models .csv new file mode 100644 index 0000000000000000000000000000000000000000..2ddc6065ca217ca046a38238948a4a785643371f --- /dev/null +++ b/101/replication_package/output_tables_reduced/ effects Informativity_social_only_models .csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f4c36ba37e6d81e8ce64692c8f52e79ddeae653137f4b68c9a8c143b376327a5 +size 1356 diff --git a/101/replication_package/output_tables_reduced/ fitted_list Boundness_social_models .csv b/101/replication_package/output_tables_reduced/ fitted_list Boundness_social_models .csv new file mode 100644 index 0000000000000000000000000000000000000000..1328807ca0579c26136922c577b4c2cf4e178e92 --- /dev/null +++ b/101/replication_package/output_tables_reduced/ fitted_list Boundness_social_models .csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:90a43287c89b091f3e11f0fda7c795e6b7216af41742d08680e1535846b51d7b +size 1384023 diff --git a/101/replication_package/output_tables_reduced/ fitted_list Boundness_social_only_models .csv b/101/replication_package/output_tables_reduced/ fitted_list Boundness_social_only_models .csv new file mode 100644 index 0000000000000000000000000000000000000000..ef6b89dc355595b2578c5e4f5b71f83d26ef6cfd --- /dev/null +++ b/101/replication_package/output_tables_reduced/ fitted_list Boundness_social_only_models .csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:392cee639b479f32cefd787af90714a3f71b3086c5bdd269e9db007ca011a5f6 +size 1059703 diff --git a/101/replication_package/output_tables_reduced/ fitted_list Informativity_social_models .csv b/101/replication_package/output_tables_reduced/ fitted_list Informativity_social_models .csv new file mode 100644 index 0000000000000000000000000000000000000000..d53579fe1c04d09d97209a37b3eaa6429de585ea --- /dev/null +++ b/101/replication_package/output_tables_reduced/ fitted_list Informativity_social_models .csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fa205e06afeb03a7fbe9627bf53392daa32e46c1a56ee1dddd1bdc7815b9d91b +size 1383978 diff --git a/101/replication_package/output_tables_reduced/ fitted_list Informativity_social_only_models .csv b/101/replication_package/output_tables_reduced/ fitted_list Informativity_social_only_models .csv new file mode 100644 index 0000000000000000000000000000000000000000..54d9596c709f4c698c073c974488046f28694b1d --- /dev/null +++ b/101/replication_package/output_tables_reduced/ fitted_list Informativity_social_only_models .csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:223e742c3f4602fb43665d9d487684f9b98bcfbdba83124c59d8655e669013ea +size 1026393 diff --git a/101/replication_package/output_tables_reduced/ waics Boundness_social_models .csv b/101/replication_package/output_tables_reduced/ waics Boundness_social_models .csv new file mode 100644 index 0000000000000000000000000000000000000000..8a5a2489583617f8510515997d63c78056b35a1e --- /dev/null +++ b/101/replication_package/output_tables_reduced/ waics Boundness_social_models .csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:52965426c6265440044c1026efca405d8198a10b5803600e187ff36d260f2991 +size 575 diff --git a/101/replication_package/output_tables_reduced/ waics Boundness_social_models prior_0.01 .csv b/101/replication_package/output_tables_reduced/ waics Boundness_social_models prior_0.01 .csv new file mode 100644 index 0000000000000000000000000000000000000000..64547a51b70f36eadc389d7e81ff753c6853c87a --- /dev/null +++ b/101/replication_package/output_tables_reduced/ waics Boundness_social_models prior_0.01 .csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:12869df99863a60af822307cb546d437c33998b81d2eae427e474fb6510a340b +size 574 diff --git a/101/replication_package/output_tables_reduced/ waics Boundness_social_models prior_0.5 .csv b/101/replication_package/output_tables_reduced/ waics Boundness_social_models prior_0.5 .csv new file mode 100644 index 0000000000000000000000000000000000000000..b21a889d2e16ca598a908f40c8c599d7fab45793 --- /dev/null +++ b/101/replication_package/output_tables_reduced/ waics Boundness_social_models prior_0.5 .csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:efec9a306767c026b431dd10b93db330855760233ce6f7d5622f8706478ec9ad +size 574 diff --git a/101/replication_package/output_tables_reduced/ waics Boundness_social_models prior_0.99 .csv b/101/replication_package/output_tables_reduced/ waics Boundness_social_models prior_0.99 .csv new file mode 100644 index 0000000000000000000000000000000000000000..9fccc17d7656faa05d381383ba27830803bfd25d --- /dev/null +++ b/101/replication_package/output_tables_reduced/ waics Boundness_social_models prior_0.99 .csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:64bf5d1965b56d5c672324a93628a1606a3e633a036a0fccb15bae4b87a98aba +size 574 diff --git a/101/replication_package/output_tables_reduced/ waics Boundness_social_only_models .csv b/101/replication_package/output_tables_reduced/ waics Boundness_social_only_models .csv new file mode 100644 index 0000000000000000000000000000000000000000..fa9d994f2164ed5e3989fbc7525937bc2dc176c2 --- /dev/null +++ b/101/replication_package/output_tables_reduced/ waics Boundness_social_only_models .csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8d908447e162b56ca216d5d97a29a5fa55399e06f0e4da261afd221ddb5a7327 +size 319 diff --git a/101/replication_package/output_tables_reduced/ waics Informativity_social_models .csv b/101/replication_package/output_tables_reduced/ waics Informativity_social_models .csv new file mode 100644 index 0000000000000000000000000000000000000000..6ab74a92d45c48f86c2a9f7e1f0b4efdea835984 --- /dev/null +++ b/101/replication_package/output_tables_reduced/ waics Informativity_social_models .csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8139967f71207bac600961c178951fa65cc82036b1577d56398071aa4c9ec301 +size 575 diff --git a/101/replication_package/output_tables_reduced/ waics Informativity_social_models prior_0.01 .csv b/101/replication_package/output_tables_reduced/ waics Informativity_social_models prior_0.01 .csv new file mode 100644 index 0000000000000000000000000000000000000000..95af71c66f9546f8e1d70991e27ccca9c9bf995b --- /dev/null +++ b/101/replication_package/output_tables_reduced/ waics Informativity_social_models prior_0.01 .csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:eaff8a50f20ede5c6c89ddd41fc3c330c65d51d53afc71441ae1782b4c4604af +size 575 diff --git a/101/replication_package/output_tables_reduced/ waics Informativity_social_models prior_0.5 .csv b/101/replication_package/output_tables_reduced/ waics Informativity_social_models prior_0.5 .csv new file mode 100644 index 0000000000000000000000000000000000000000..287ba5cf7a6aa329ab59276d2c3d2da81dbcd908 --- /dev/null +++ b/101/replication_package/output_tables_reduced/ waics Informativity_social_models prior_0.5 .csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:009acc9191bc89311b9d8171f67ab04e8045bd838e40a04c08c698ee8a3710d1 +size 575 diff --git a/101/replication_package/output_tables_reduced/ waics Informativity_social_models prior_0.99 .csv b/101/replication_package/output_tables_reduced/ waics Informativity_social_models prior_0.99 .csv new file mode 100644 index 0000000000000000000000000000000000000000..06b4698e5d8a116d924d2cdb2236bd46995abe2d --- /dev/null +++ b/101/replication_package/output_tables_reduced/ waics Informativity_social_models prior_0.99 .csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:98aae857e1e9106e0c071a6d6e40e65eb6d21cc3da474f6e633233f77d618acd +size 571 diff --git a/101/replication_package/output_tables_reduced/ waics Informativity_social_only_models .csv b/101/replication_package/output_tables_reduced/ waics Informativity_social_only_models .csv new file mode 100644 index 0000000000000000000000000000000000000000..01faa4958f5c26bdc5d3ba0ceee472add7423a28 --- /dev/null +++ b/101/replication_package/output_tables_reduced/ waics Informativity_social_only_models .csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e669c748ccbcba928f412d564ae224760349c26a96d63e9848a9e07392f4182b +size 322 diff --git a/101/replication_package/output_tables_reduced/Boundness_social_models_marginals_hyperpar_gaussian.csv b/101/replication_package/output_tables_reduced/Boundness_social_models_marginals_hyperpar_gaussian.csv new file mode 100644 index 0000000000000000000000000000000000000000..b6321acda3a504a99c020f2e5ed042712cfd484e --- /dev/null +++ b/101/replication_package/output_tables_reduced/Boundness_social_models_marginals_hyperpar_gaussian.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:af016af11c9599e8e451c2f1a6228982688ae6b7c1cab504d3350f6e3ba7b599 +size 36904 diff --git a/101/replication_package/output_tables_reduced/Boundness_social_models_marginals_hyperpar_phylogenetic.csv b/101/replication_package/output_tables_reduced/Boundness_social_models_marginals_hyperpar_phylogenetic.csv new file mode 100644 index 0000000000000000000000000000000000000000..31e6454f5e8f5ed098300c554743848f7f1f3241 --- /dev/null +++ b/101/replication_package/output_tables_reduced/Boundness_social_models_marginals_hyperpar_phylogenetic.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:70da7734dd436e2615212a17674b94a9be9cc4357f7311cc2712dfcf5b0c5c26 +size 36862 diff --git a/101/replication_package/output_tables_reduced/Boundness_social_models_marginals_hyperpar_spatial.csv b/101/replication_package/output_tables_reduced/Boundness_social_models_marginals_hyperpar_spatial.csv new file mode 100644 index 0000000000000000000000000000000000000000..1aabdb46818940cb120a9d45cd9b606b930e4454 --- /dev/null +++ b/101/replication_package/output_tables_reduced/Boundness_social_models_marginals_hyperpar_spatial.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:a1fbadf33493590f7161a9e32d3a3a454ea3d317c4ffcf97eb424c6cfb3d33cf +size 36898 diff --git a/101/replication_package/output_tables_reduced/Boundness_social_models_summary_random_phy.csv b/101/replication_package/output_tables_reduced/Boundness_social_models_summary_random_phy.csv new file mode 100644 index 0000000000000000000000000000000000000000..9eb6746d2f231bedd8d290062deaac0e6c41c715 --- /dev/null +++ b/101/replication_package/output_tables_reduced/Boundness_social_models_summary_random_phy.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0d8fc88989d7149b5c1ac7861da161ca411c9e5e5d350456ea59d2c0eabf50d3 +size 2367127 diff --git a/101/replication_package/output_tables_reduced/Boundness_social_models_summary_random_spa.csv b/101/replication_package/output_tables_reduced/Boundness_social_models_summary_random_spa.csv new file mode 100644 index 0000000000000000000000000000000000000000..1a75ea90cd0e2b004f2df2070ff027c29b2c4fcd --- /dev/null +++ b/101/replication_package/output_tables_reduced/Boundness_social_models_summary_random_spa.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7adf9746872c23b8a5debc9dc7ebc6f05fabb045f3181d31ba3a697fe43a29ee +size 1170952 diff --git a/101/replication_package/output_tables_reduced/Boundness_social_only_models_marginals_hyperpar_gaussian.csv b/101/replication_package/output_tables_reduced/Boundness_social_only_models_marginals_hyperpar_gaussian.csv new file mode 100644 index 0000000000000000000000000000000000000000..2db85b3993062211995a7ba038171ec2e8a10775 --- /dev/null +++ b/101/replication_package/output_tables_reduced/Boundness_social_only_models_marginals_hyperpar_gaussian.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f087c4e77f476d4270723717e73d3aff0eb7e97855ba6b21aa9be7c26b7756db +size 25726 diff --git a/101/replication_package/output_tables_reduced/Informativity_social_models_marginals_hyperpar_gaussian.csv b/101/replication_package/output_tables_reduced/Informativity_social_models_marginals_hyperpar_gaussian.csv new file mode 100644 index 0000000000000000000000000000000000000000..92ba6881ab745e7d589ff436ca9d7cff35b76d00 --- /dev/null +++ b/101/replication_package/output_tables_reduced/Informativity_social_models_marginals_hyperpar_gaussian.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:02ea6598e912459c328a79f17dab0b3d3eb8cc029d3763fdb539e9e94c1fc294 +size 36557 diff --git a/101/replication_package/output_tables_reduced/Informativity_social_models_marginals_hyperpar_phylogenetic.csv b/101/replication_package/output_tables_reduced/Informativity_social_models_marginals_hyperpar_phylogenetic.csv new file mode 100644 index 0000000000000000000000000000000000000000..cab236588a155e12310ca44a83c3165c3861e329 --- /dev/null +++ b/101/replication_package/output_tables_reduced/Informativity_social_models_marginals_hyperpar_phylogenetic.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:910d907dc31bcc3cc1a0bd6d549e659b55db715be342b9ae39c90053cc8d56bb +size 36920 diff --git a/101/replication_package/output_tables_reduced/Informativity_social_models_marginals_hyperpar_spatial.csv b/101/replication_package/output_tables_reduced/Informativity_social_models_marginals_hyperpar_spatial.csv new file mode 100644 index 0000000000000000000000000000000000000000..2f1594f5a6195363bea6530e54212b97b741840e --- /dev/null +++ b/101/replication_package/output_tables_reduced/Informativity_social_models_marginals_hyperpar_spatial.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3781d90ef7af2bcc51bad4befb6ed27528d232e11e63da83dbeb4db82481e64e +size 36891 diff --git a/101/replication_package/output_tables_reduced/Informativity_social_models_summary_random_phy.csv b/101/replication_package/output_tables_reduced/Informativity_social_models_summary_random_phy.csv new file mode 100644 index 0000000000000000000000000000000000000000..018fcca3284e3b5e03b0c9dc8e3ba8969dae7ee7 --- /dev/null +++ b/101/replication_package/output_tables_reduced/Informativity_social_models_summary_random_phy.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:549f305c09ffea3c9a7d47ef1c3cd81d5b76a886ef7c57d17e5b03a26bf87379 +size 2372210 diff --git a/101/replication_package/output_tables_reduced/Informativity_social_models_summary_random_spa.csv b/101/replication_package/output_tables_reduced/Informativity_social_models_summary_random_spa.csv new file mode 100644 index 0000000000000000000000000000000000000000..759d81b8ab6bf7124b03f8f7675aa240943dedf4 --- /dev/null +++ b/101/replication_package/output_tables_reduced/Informativity_social_models_summary_random_spa.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7d1c8c178a47a559aaa731f43a8804e672840c6785b58bca6ea1fd9f23f58b55 +size 1174210 diff --git a/101/replication_package/output_tables_reduced/Informativity_social_only_models_marginals_hyperpar_gaussian.csv b/101/replication_package/output_tables_reduced/Informativity_social_only_models_marginals_hyperpar_gaussian.csv new file mode 100644 index 0000000000000000000000000000000000000000..221846946ff3c3e2427806d8577b89f5a060e78f --- /dev/null +++ b/101/replication_package/output_tables_reduced/Informativity_social_only_models_marginals_hyperpar_gaussian.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e412eda2f134c3b004a9695e6529790e91e1208c9d8b0caeb5c1867ee4065fcc +size 25787 diff --git a/101/replication_package/output_tables_reduced/Table_INLA_all_models.csv b/101/replication_package/output_tables_reduced/Table_INLA_all_models.csv new file mode 100644 index 0000000000000000000000000000000000000000..90e53a556baed97d30aa66035bbb4ddda3f307a1 --- /dev/null +++ b/101/replication_package/output_tables_reduced/Table_INLA_all_models.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:2d5d0cc28d3fb450f55075889ec2a84aeb3e1490f2b812c9c5dd8635f87c1f92 +size 14608 diff --git a/101/replication_package/output_tables_reduced/Table_sensitivity.csv b/101/replication_package/output_tables_reduced/Table_sensitivity.csv new file mode 100644 index 0000000000000000000000000000000000000000..055d84ec63f4efe58d0970adb48b7db717dd5575 --- /dev/null +++ b/101/replication_package/output_tables_reduced/Table_sensitivity.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:66247297052be5a9a3b82621e0d45f1d7083b7f4d24e0e7584f8d5722a982dd8 +size 6337 diff --git a/101/replication_package/output_tables_reduced/Table_variance_top_ranking_models.csv b/101/replication_package/output_tables_reduced/Table_variance_top_ranking_models.csv new file mode 100644 index 0000000000000000000000000000000000000000..c40866fc11e1836f8b3501cda9efb22e8512f638 --- /dev/null +++ b/101/replication_package/output_tables_reduced/Table_variance_top_ranking_models.csv @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:96d7646a4e40bfc66b4464c9dec28abc2eea1395a7bc5052ea840de0ff391e98 +size 402 diff --git a/101/replication_package/plot_heatmap_B_I.R b/101/replication_package/plot_heatmap_B_I.R new file mode 100644 index 0000000000000000000000000000000000000000..e509037a05115ebd66af49adb5961c63f2ebf30b --- /dev/null +++ b/101/replication_package/plot_heatmap_B_I.R @@ -0,0 +1,290 @@ +#heat map with a tree plot: boundness + informativity +source("set_up_inla.R") + +metrics_joined <- metrics_joined %>% + filter(!is.na(L1_log10_st)) %>% + rename(L1_log_st = L1_log10_st) %>% + mutate(L1_copy = L1_log_st) %>% + filter(!is.na(L2_prop)) %>% + dplyr::mutate(L2_prop = scale(L2_prop)[, 1]) %>% + mutate(L2_copy = L2_prop) %>% + filter(!is.na(neighboring_languages_st)) %>% + filter(!is.na(Official)) %>% + filter(!is.na(Education)) %>% + filter(!is.na(boundness_st)) %>% + filter(!is.na(informativity_st)) + +#dropping tips not in Grambank +metrics_joined <- + metrics_joined[metrics_joined$Language_ID %in% tree$tip.label,] +tree <- keep.tip(tree, metrics_joined$Language_ID) + +x <- + assert_that(all(tree$tip.label %in% metrics_joined$Language_ID), msg = "The data and phylogeny taxa do not match") + +metrics_joined <- + metrics_joined %>% mutate(Language_ID_2 = Language_ID) %>% column_to_rownames(var = "Language_ID_2") + +df1 <- + metrics_joined %>% dplyr::select(boundness_st) %>% rename(boundness = boundness_st) +df2 <- + metrics_joined %>% dplyr::select(informativity_st) %>% rename(informativity = informativity_st) + +### Adding colored branches of the biggest families in the dataset + +metrics_joined %>% + group_by(Family_ID) %>% + summarise(n = n()) %>% + mutate(freq = n / sum(n)) %>% + arrange(desc(n)) %>% + filter(!Family_ID == "") %>% + top_n(12, freq) -> table + +biggest_families <- table$Family_ID +metrics_joined$family_status <- NA +metrics_joined$family_status <- + ifelse(metrics_joined$Family_ID %in% biggest_families, + metrics_joined$Family_ID, + "other") + +#double-checking if all families indeed converted to names and none is left with "NA" +unique(metrics_joined$family_status) + +metrics_joined <- metrics_joined %>% + mutate( + family = + dplyr::recode( + family_status, + "aust1307" = "Austronesian", + "aust1305" = "Austroasiatic", + "indo1319" = "Indo-European", + "atla1278" = "Atlantic-Congo", + "utoa1244" = "Uto-Aztecan", + "sino1245" = "Sino-Tibetan", + "afro1255" = "Afro-Asiatic", + "nucl1709" = "Nuclear Trans New Guinea", + "maya1287" = "Mayan", + "pano1259" = "Pano-Tacanan", + "otom1299" = "Otomanguean", + "chib1249" = "Chibchan ", + "nakh1245" = "Nakh-Daghestanian", + "cent2225" = "Central Sudanic", + "drav1251" = "Dravidian", + "ural1272" = "Uralic", + "pama1250" = "Pama-Nyungan", + "other" = "other" + ) + ) + +#double-checking if all families indeed converted to names and none is left with "NA" +unique(metrics_joined$family) + +#ordering the families in the desired way +#metrics_joined$family <- factor(metrics_joined$family, order = TRUE, levels = c("other", "Austronesian", "Austroasiatic", "Sino-Tibetan", "Indo-European", "Atlantic-Congo", "Afro-Asiatic", "Uto-Aztecan", "Nuclear Trans New Guinea")) + +tips_lists <- vector(mode = "list", length = 12) + +for (f in 1:length(biggest_families)) { + tips_lists[[f]] <- + metrics_joined[metrics_joined$Family_ID == biggest_families[f], ]$Language_ID + tips_lists[[f]] <- na.omit(tips_lists[[f]]) + + } + +#the correct order within biggest families is preserved and the Glottocodes are replaced with suitable family name labels +biggest_families_verbose <- dplyr::recode( + biggest_families, + "aust1307" = "Austronesian", + "aust1305" = "Austroasiatic", + "indo1319" = "Indo-European", + "atla1278" = "Atlantic-Congo", + "utoa1244" = "Uto-Aztecan", + "sino1245" = "Sino-Tibetan", + "afro1255" = "Afro-Asiatic", + "nucl1709" = "Nuclear Trans New Guinea", + "maya1287" = "Mayan", + "pano1259" = "Pano-Tacanan", + "otom1299" = "Otomanguean", + "chib1249" = "Chibchan ", + "nakh1245" = "Nakh-Daghestanian", + "cent2225" = "Central Sudanic", + "drav1251" = "Dravidian", + "ural1272" = "Uralic", + "pama1250" = "Pama-Nyungan", + "other" = "other" +) + +names(tips_lists) <- biggest_families_verbose + +nodes <- vector(mode = "character", length = length(biggest_families)) + +for (tips in 1:length(tips_lists)) { + nodes[tips] <- getMRCA(tree, tips_lists[[tips]]) +} + +#test +#nodes <- vector(mode="character", length=1) +#nodes[1] <- getMRCA(tree, tips_lists[[4]]) + +nodes <- as.numeric(nodes) + +coloured_branches <- groupClade(tree, nodes) +coloured_branches <- + ggtree( + coloured_branches, + layout = 'rect', + branch.length = 'none', + size = 0.5 + ) + +p1 <- + gheatmap( + coloured_branches, + df1, + offset = -1, + width = .1, + colnames_angle = 0, + colnames_offset_y = 25, + colnames_position = "top", + colnames = F, + #removing column names + font.size = 20, + hjust = 0.5, + color = FALSE + ) + ylim(-5, 1480) + #ylim(-5, 1450) + scale_fill_viridis_c(option = "magma", direction = -1) + labs(fill = "fusion") + theme(legend.position = "bottom", + legend.key.size = unit(1.4, 'cm')) + + geom_cladelabel( + node = nodes[1], + label = biggest_families_verbose[1], + offset = 6, + align = TRUE, + fontsize = 13 + ) + + geom_cladelabel( + node = nodes[2], + label = biggest_families_verbose[2], + offset = 6, + align = TRUE, + fontsize = 13 + ) + + geom_cladelabel( + node = nodes[3], + label = biggest_families_verbose[3], + offset = 6, + align = TRUE, + fontsize = 13 + ) + + geom_cladelabel( + node = nodes[4], + label = biggest_families_verbose[4], + offset = 6, + align = TRUE, + fontsize = 13 + ) + + geom_cladelabel( + node = nodes[5], + label = biggest_families_verbose[5], + offset = 6, + align = TRUE, + fontsize = 13 + ) + + geom_cladelabel( + node = nodes[6], + label = biggest_families_verbose[6], + offset = 6, + align = TRUE, + fontsize = 13 + ) + + geom_cladelabel( + node = nodes[7], + label = biggest_families_verbose[7], + offset = 6, + align = TRUE, + fontsize = 13 + ) + + geom_cladelabel( + node = nodes[8], + label = biggest_families_verbose[8], + offset = 6, + align = TRUE, + fontsize = 13 + ) + + geom_cladelabel( + node = nodes[9], + label = biggest_families_verbose[9], + offset = 6, + align = TRUE, + fontsize = 13 + ) + + geom_cladelabel( + node = nodes[10], + label = biggest_families_verbose[10], + offset = 6, + align = TRUE, + fontsize = 13 + ) + + geom_cladelabel( + node = nodes[11], + label = biggest_families_verbose[11], + offset = 6, + align = TRUE, + fontsize = 13 + ) + + geom_cladelabel( + node = nodes[12], + label = biggest_families_verbose[12], + offset = 6, + align = TRUE, + fontsize = 13 + ) + labs(fill = "fusion") + +p2 <- p1 + new_scale_fill() + +p3 <- gheatmap( + p2, + df2, + offset = 2, + width = .1, + colnames_angle = 0, + colnames_offset_y = 25, + colnames_position = "top", + font.size = 20, + hjust = 0.5, + color = FALSE, + colnames = FALSE +) + ylim(-5, 1400) + + xlim(-1, 55) + + scale_fill_viridis_c(option = "viridis", direction = -1) + + labs(fill = "informativity") + + theme( + legend.box = "horizontal", + legend.position = "bottom", + text = element_text(size = 55), + legend.key.size = unit(1.6, 'cm') + ) +p3 + +ggsave( + file = "output/plot_heatmap_B_I.svg", + plot = p3, + width = 25, + height = 27, + dpi = 600 +) + +ggsave( + file = "output/plot_heatmap_B_I.pdf", + plot = p3, + width = 25, + height = 27, + dpi = 600 +) + +ggsave( + file = "output/plot_heatmap_B_I.jpeg", + plot = p3, + width = 25, + height = 27, + dpi = 600 +) diff --git a/101/replication_package/plot_heatmap_informativity_Uralic.R b/101/replication_package/plot_heatmap_informativity_Uralic.R new file mode 100644 index 0000000000000000000000000000000000000000..d4d0580b64aec4dab11bfcc466b5734a8df65ccb --- /dev/null +++ b/101/replication_package/plot_heatmap_informativity_Uralic.R @@ -0,0 +1,108 @@ +#heat map with a tree plot: boundness + +#first, obtaining the actual max and min values of informativity in the entire sample +source("set_up_inla.R") + +metrics_joined <- metrics_joined %>% + filter(!is.na(L1_log10_st)) %>% + rename(L1_log_st = L1_log10_st) %>% + mutate(L1_copy = L1_log_st) %>% + filter(!is.na(L2_prop)) %>% + dplyr::mutate(L2_prop = scale(L2_prop)[, 1]) %>% + mutate(L2_copy = L2_prop) %>% + filter(!is.na(neighboring_languages_st)) %>% + filter(!is.na(Official)) %>% + filter(!is.na(Education)) %>% + filter(!is.na(boundness_st)) %>% + filter(!is.na(informativity_st)) + +#dropping tips not in Grambank +metrics_joined <- + metrics_joined[metrics_joined$Language_ID %in% tree$tip.label,] + +max <- max(metrics_joined$informativity_st) +min <- min(metrics_joined$informativity_st) + +#now plotting Uralic languages only +source("set_up_inla.R") + +metrics_joined <- metrics_joined %>% + filter(!is.na(L1_log10_st)) %>% + rename(L1_log_st = L1_log10_st) %>% + mutate(L1_copy = L1_log_st) %>% + filter(!is.na(L2_prop)) %>% + dplyr::mutate(L2_prop = scale(L2_prop)[, 1]) %>% + mutate(L2_copy = L2_prop) %>% + filter(!is.na(neighboring_languages_st)) %>% + filter(!is.na(Official)) %>% + filter(!is.na(Education)) %>% + filter(!is.na(boundness_st)) %>% + filter(!is.na(informativity_st)) %>% + filter(Family_ID == "ural1272") + +#dropping tips not in Grambank +metrics_joined <- + metrics_joined[metrics_joined$Language_ID %in% tree$tip.label,] +tree <- keep.tip(tree, metrics_joined$Language_ID) + +x <- + assert_that(all(tree$tip.label %in% metrics_joined$Language_ID), msg = "The data and phylogeny taxa do not match") + +metrics_joined <- + metrics_joined %>% mutate(Language_ID_2 = Language_ID) %>% column_to_rownames(var = "Language_ID_2") + +df1 <- metrics_joined %>% + dplyr::select(informativity_st) %>% + rename(informativity = informativity_st) + +uralic_fam_tree <- + ggtree(tree, layout = 'rect', branch.length = 'none') +uralic_fam_tree <- + uralic_fam_tree %<+% metrics_joined + geom_tiplab(aes(label = Name), size = + 5) + +p1 <- + gheatmap( + uralic_fam_tree, + df1, + offset = 6, + width = .2, + colnames_angle = 0, + colnames_position = "top", + colnames = F, + #removing column names + font.size = 5, + hjust = 0.5, + color = FALSE + ) + #ylim(-5, 27) + #ylim(-5, 1450) + scale_fill_viridis_c( + option = "viridis", + direction = -1, + limits = c(min, max), + guide = "none" + ) + + theme(legend.position = c(1, 1)) + theme( + legend.position = "right", + legend.box = "vertical", + text = element_text(size = 50), + legend.key.size = unit(0.9, 'cm') + ) + +ggsave( + file = "output/heatmap_Uralic_informativity.svg", + plot = p1, + width = 7, + height = 7, + dpi=300 +) + +triple_plot <- + b_labelled / i_labelled | p1 #+ plot_annotation(tag_levels = '1') + +ggsave( + file = "output/triple_plot.svg", + plot = triple_plot, + width = 12, + height = 7, + dpi=300 +) diff --git a/101/replication_package/plot_map_Africa.R b/101/replication_package/plot_map_Africa.R new file mode 100644 index 0000000000000000000000000000000000000000..9269429008aa6b0c28d429a465aa91f57743b549 --- /dev/null +++ b/101/replication_package/plot_map_Africa.R @@ -0,0 +1,256 @@ +#plotting maps +source("set_up_inla.R") + +metrics_joined <- metrics_joined %>% + filter(!is.na(L1_log10_st)) %>% + rename(L1_log_st = L1_log10_st) %>% + mutate(L1_copy = L1_log_st) %>% + filter(!is.na(L2_prop)) %>% + dplyr::mutate(L2_prop = scale(L2_prop)[, 1]) %>% + mutate(L2_copy = L2_prop) %>% + filter(!is.na(neighboring_languages_st)) %>% + filter(!is.na(Official)) %>% + filter(!is.na(Education)) %>% + filter(!is.na(boundness_st)) %>% + filter(!is.na(informativity_st)) %>% + filter( + Macroarea == "Africa" | + Macroarea == "Papunesia" | + Macroarea == "Australia" | Macroarea == "Eurasia" + ) %>% + filter(180 > Longitude & Longitude > -24) %>% + filter(80 > Latitude & Latitude > -45) + +#an overview of area and family coverage +tab_areas <- as.data.frame(table(metrics_joined$AUTOTYP_area)) %>% + arrange(desc(Freq)) + +tab_families <- as.data.frame(table(metrics_joined$Family_ID)) %>% + arrange(desc(Freq)) + + +#dropping tips not in Grambank +metrics_joined <- + metrics_joined[metrics_joined$Language_ID %in% tree$tip.label,] +tree <- keep.tip(tree, metrics_joined$Language_ID) + +x <- + assert_that(all(tree$tip.label %in% metrics_joined$Language_ID), msg = "The data and phylogeny taxa do not match") + +lakes <- + map_data( + "lakes", + col = "white", + border = "gray", + margin = T, + ylim = c(-45, 80), + xlim = c(-30, 180), + wrap = c(-25, 335) + ) + +world <- + map_data( + "world", + wrap = c(-25, 335), + ylim = c(-45, 80), + xlim = c(-30, 180), + margin = T + ) + +world <- + subset(world,!( + region %in% c( + "USA", + "Brazil", + "Mexico", + "Colombia", + "Argentina", + "Canada", + "Peru", + "Venezuela", + "Chile", + "Guatemala", + "Ecuador", + "Bolivia", + "Cuba", + "Honduras", + "Paraguay", + "Nicaragua", + "El Salvador", + "Costa Rica", + "Panama", + "Uruguay", + "Jamaica", + "Trinidad and Tobago", + "Guyana", + "Suriname", + "Belize", + "Barbados", + "Saint Lucia", + "Grenada", + "Saint Vincent and the Grenadines", + "Antigua and Barbuda", + "Saint Kitts and Nevis", + "Greenland" + ) + )) + +#shifting the longlat of the dataframe to match the pacific centered map +combination <- metrics_joined %>% + mutate(Longitude = if_else(Longitude <= -25, Longitude + 360, Longitude)) + +#duplicates? + +combination %>% + group_by(Language_ID) %>% + mutate(dupe = n() > 1) -> combination_dup +dupes <- combination_dup[combination_dup$dupe == "TRUE", ] + +#Basemap +basemap <- ggplot(combination) + + geom_polygon( + data = world, + aes(x = long, y = lat, group = group), + colour = "gray87", + fill = "gray87", + size = 0.5 + ) + + geom_polygon( + data = lakes, + aes(x = long, y = lat, group = group), + colour = "gray87", + fill = "white", + size = 0.3 + ) + + theme( + panel.grid.major = element_blank(), + #all of these lines are just removing default things like grid lines, axises etc + panel.grid.minor = element_blank(), + axis.title.x = element_blank(), + axis.title.y = element_blank(), + axis.line = element_blank(), + panel.border = element_blank(), + panel.background = element_rect(fill = "white"), + axis.text.x = element_blank(), + axis.text.y = element_blank(), + axis.ticks = element_blank() + ) + + coord_map( + projection = "vandergrinten", + ylim = c(-45, 80), + xlim = c(-30, 180) + ) + + +#plotting boundness map with cumstom labels + +#tswa1253 is almost overlapping in the location with hoaa1235; plotting hoaa1235 for the purposes of the plot +combination_ordered_0 <- combination %>% + mutate(plotted_last = case_when(Language_ID == "hoaa1235" ~ 1, + Language_ID != "hoaa1235" ~ 0)) %>% + arrange(plotted_last) %>% + mutate( + langs_of_interest = case_when( + Language_ID == "hoaa1235" | + Language_ID == "huaa1248" | + Language_ID == "tswa1255" | + Language_ID == "tson1249" | + Language_ID == "sout2807" ~ 1, + Language_ID != "hoaa1235" & + Language_ID != "huaa1248" & + Language_ID != "tswa1255" & + Language_ID != "tson1249" & + Language_ID != "sout2807" ~ 0 + ) + ) %>% + mutate(langs_of_interest = as.factor(langs_of_interest)) %>% + filter(langs_of_interest == "0") + +combination_ordered_1 <- combination %>% + mutate(plotted_last = case_when(Language_ID == "hoaa1235" ~ 1, + Language_ID != "hoaa1235" ~ 0)) %>% + arrange(plotted_last) %>% + mutate( + langs_of_interest = case_when( + Language_ID == "hoaa1235" | + Language_ID == "huaa1248" | + Language_ID == "tswa1255" | + Language_ID == "tson1249" | + Language_ID == "sout2807" ~ 1, + Language_ID != "hoaa1235" & + Language_ID != "huaa1248" & + Language_ID != "tswa1255" & + Language_ID != "tson1249" & + Language_ID != "sout2807" ~ 0 + ) + ) %>% + mutate(langs_of_interest = as.factor(langs_of_interest)) %>% + filter(langs_of_interest != "0") + +b_labelled <- + basemap + geom_point( + data = combination_ordered_0, + aes( + x = Longitude, + y = Latitude, + color = boundness_st, + fill = boundness_st + ), + size = 1, + pch = 21, + # stroke=NA, + position = position_jitter( + width = 1, + height = 1, + seed = 123 + ) + ) + + geom_point( + data = combination_ordered_1, + aes(x = Longitude, y = Latitude, fill = boundness_st), + pch = 21, + size = 2.5, + colour = "black", + position = position_jitter( + width = 1, + height = 1, + seed = 123 + ) + ) + + #scale_fill_gradient2(low = muted("blue"), mid = "white", high = muted("red"), midpoint=0) + + #scale_color_gradient2(low = muted("blue"), mid = "white", high = muted("red"), midpoint=0, guide="none") + + scale_fill_viridis_c(option = "magma", direction = -1) + + scale_color_viridis_c(option = "magma", + guide = "none", + direction = -1) + + theme( + text = element_text(size = 20), + legend.key.size = unit(0.5, units = "cm"), + legend.position = "right" + ) + + guides(fill = guide_colourbar()) + + labs(fill = "fusion") + + geom_text_repel( + aes(x = Longitude, y = Latitude, label = Name), + #size=5, + data = subset( + combination, + AUTOTYP_area == "S Africa" & + Latitude < -23 & + boundness_st < 0 | + Language_ID == "sout2807" | Language_ID == "tswa1255" + ), + size = 5, + box.padding = 0.7, + max.overlaps = Inf, + point.padding = 0.1 + ) +b_labelled + +ggsave( + file = "output/map_boundness_labelled.svg", + plot = b_labelled, + width = 10, + height = 9, + dpi=300 +) diff --git a/101/replication_package/plot_map_Eurasia.R b/101/replication_package/plot_map_Eurasia.R new file mode 100644 index 0000000000000000000000000000000000000000..0f19105892f4d881920a3b9ac2ac95379b39c803 --- /dev/null +++ b/101/replication_package/plot_map_Eurasia.R @@ -0,0 +1,227 @@ +#plotting maps +source("set_up_inla.R") + +metrics_joined <- metrics_joined %>% + filter(!is.na(L1_log10_st)) %>% + rename(L1_log_st = L1_log10_st) %>% + mutate(L1_copy = L1_log_st) %>% + filter(!is.na(L2_prop)) %>% + dplyr::mutate(L2_prop = scale(L2_prop)[, 1]) %>% + mutate(L2_copy = L2_prop) %>% + filter(!is.na(neighboring_languages_st)) %>% + filter(!is.na(Official)) %>% + filter(!is.na(Education)) %>% + filter(!is.na(boundness_st)) %>% + filter(!is.na(informativity_st)) %>% + filter( + Macroarea == "Africa" | + Macroarea == "Papunesia" | + Macroarea == "Australia" | Macroarea == "Eurasia" + ) %>% + filter(180 > Longitude & Longitude > -24) %>% + filter(80 > Latitude & Latitude > -45) + +#an overview of area and family coverage +tab_areas <- as.data.frame(table(metrics_joined$AUTOTYP_area)) %>% + arrange(desc(Freq)) + +tab_families <- as.data.frame(table(metrics_joined$Family_ID)) %>% + arrange(desc(Freq)) + + +#dropping tips not in Grambank +metrics_joined <- + metrics_joined[metrics_joined$Language_ID %in% tree$tip.label,] +tree <- keep.tip(tree, metrics_joined$Language_ID) + +x <- + assert_that(all(tree$tip.label %in% metrics_joined$Language_ID), msg = "The data and phylogeny taxa do not match") + +lakes <- + map_data( + "lakes", + col = "white", + border = "gray", + margin = T, + ylim = c(-45, 80), + xlim = c(-30, 180), + wrap = c(-25, 335) + ) + +world <- + map_data( + "world", + wrap = c(-25, 335), + ylim = c(-45, 80), + xlim = c(-30, 180), + margin = T + ) + +world <- + subset(world,!( + region %in% c( + "USA", + "Brazil", + "Mexico", + "Colombia", + "Argentina", + "Canada", + "Peru", + "Venezuela", + "Chile", + "Guatemala", + "Ecuador", + "Bolivia", + "Cuba", + "Honduras", + "Paraguay", + "Nicaragua", + "El Salvador", + "Costa Rica", + "Panama", + "Uruguay", + "Jamaica", + "Trinidad and Tobago", + "Guyana", + "Suriname", + "Belize", + "Barbados", + "Saint Lucia", + "Grenada", + "Saint Vincent and the Grenadines", + "Antigua and Barbuda", + "Saint Kitts and Nevis", + "Greenland" + ) + )) + +#shifting the longlat of the dataframe to match the pacific centered map +combination <- metrics_joined %>% + mutate(Longitude = if_else(Longitude <= -25, Longitude + 360, Longitude)) + +#duplicates? + +combination %>% + group_by(Language_ID) %>% + mutate(dupe = n() > 1) -> combination_dup +dupes <- combination_dup[combination_dup$dupe == "TRUE", ] + +#Basemap +basemap <- ggplot(combination) + + geom_polygon( + data = world, + aes(x = long, y = lat, group = group), + colour = "gray87", + fill = "gray87", + size = 0.5 + ) + + geom_polygon( + data = lakes, + aes(x = long, y = lat, group = group), + colour = "gray87", + fill = "white", + size = 0.3 + ) + + theme( + panel.grid.major = element_blank(), + #all of these lines are just removing default things like grid lines, axises etc + panel.grid.minor = element_blank(), + axis.title.x = element_blank(), + axis.title.y = element_blank(), + axis.line = element_blank(), + panel.border = element_blank(), + panel.background = element_rect(fill = "white"), + axis.text.x = element_blank(), + axis.text.y = element_blank(), + axis.ticks = element_blank() + ) + + coord_map( + projection = "vandergrinten", + ylim = c(-45, 80), + xlim = c(-30, 180) + ) + + + + +#plotting informativity map with cumstom labels +combination_shaped_0 <- combination %>% + mutate(Uralic = case_when(Family_ID == "ural1272" ~ "yes", + Family_ID != "ural1272" ~ "no")) %>% + mutate(langs_of_interest = case_when(Family_ID == "ural1272" ~ 1, + Family_ID != "ural1272" ~ 0)) %>% + mutate(langs_of_interest = as.factor(langs_of_interest)) %>% + filter(langs_of_interest == "0") + +combination_shaped_1 <- combination %>% + mutate(Uralic = case_when(Family_ID == "ural1272" ~ "yes", + Family_ID != "ural1272" ~ "no")) %>% + mutate(langs_of_interest = case_when(Family_ID == "ural1272" ~ 1, + Family_ID != "ural1272" ~ 0)) %>% + mutate(langs_of_interest = as.factor(langs_of_interest)) %>% + filter(langs_of_interest == "1") + +i_labelled <- + basemap + geom_point( + data = combination_shaped_0, + aes( + x = Longitude, + y = Latitude, + color = informativity_st, + fill = informativity_st + ), + size = 1, + pch = 21, + # stroke=NA, + position = position_jitter( + width = 1, + height = 1, + seed = 123 + ) + ) + + geom_point( + data = combination_shaped_1, + aes(x = Longitude, y = Latitude, fill = informativity_st), + pch = 21, + size = 2.5, + colour = "black", + position = position_jitter( + width = 1, + height = 1, + seed = 123 + ) + ) + + #scale_fill_gradient2(low = muted("blue"), mid = "white", high = muted("red"), midpoint=0) + + #scale_color_gradient2(low = muted("blue"), mid = "white", high = muted("red"), midpoint=0, guide="none") + + scale_fill_viridis_c(option = "viridis", direction = -1) + + scale_color_viridis_c(option = "viridis", + guide = "none", + direction = -1) + + scale_shape_manual(values = c(21, 24)) + + theme( + text = element_text(size = 20), + legend.key.size = unit(0.5, units = "cm"), + legend.position = "right" + ) + + guides(fill = guide_colourbar()) + + labs(fill = "informativity") + + geom_text_repel( + aes(x = Longitude, y = Latitude, label = Name), + #size=5, + data = subset(combination, ( + Family_ID == "ural1272" & informativity_st > -0.5 + )), + size = 5, + box.padding = 0.7, + max.overlaps = Inf, + point.padding = 0.1 + ) +i_labelled + +ggsave( + file = "output/map_informativity_labelled.svg", + plot = i_labelled, + width = 10, + height = 9, + dpi=300 +) diff --git a/101/replication_package/plot_maps_main.R b/101/replication_package/plot_maps_main.R new file mode 100644 index 0000000000000000000000000000000000000000..4b9c3072b938f47f40225948a26a62aaa6daeb9c --- /dev/null +++ b/101/replication_package/plot_maps_main.R @@ -0,0 +1,310 @@ +#plotting maps +source("set_up_inla.R") + +metrics_joined <- metrics_joined %>% + filter(!is.na(L1_log10_st)) %>% + rename(L1_log_st = L1_log10_st) %>% + mutate(L1_copy = L1_log_st) %>% + filter(!is.na(L2_prop)) %>% + dplyr::mutate(L2_prop = scale(L2_prop)[, 1]) %>% + mutate(L2_copy = L2_prop) %>% + filter(!is.na(neighboring_languages_st)) %>% + filter(!is.na(Official)) %>% + filter(!is.na(Education)) %>% + filter(!is.na(boundness_st)) %>% + filter(!is.na(informativity_st)) + +#an overview of area and family coverage +tab_areas <- as.data.frame(table(metrics_joined$AUTOTYP_area)) %>% + arrange(desc(Freq)) + +tab_families <- as.data.frame(table(metrics_joined$Family_ID)) %>% + arrange(desc(Freq)) + + +#dropping tips not in Grambank +metrics_joined <- + metrics_joined[metrics_joined$Language_ID %in% tree$tip.label,] +tree <- keep.tip(tree, metrics_joined$Language_ID) + +x <- + assert_that(all(tree$tip.label %in% metrics_joined$Language_ID), msg = "The data and phylogeny taxa do not match") + +world <- + map_data( + 'world', + wrap = c(-25, 335), + ylim = c(-56, 80), + margin = T + ) + +lakes <- + map_data( + "lakes", + wrap = c(-25, 335), + col = "white", + border = "gray", + ylim = c(-55, 65), + margin = T + ) + +#shifting the longlat of the dataframe to match the pacific centered map +combination <- metrics_joined %>% + mutate(Longitude = if_else(Longitude <= -25, Longitude + 360, Longitude)) + +#duplicates? + +combination %>% + group_by(Language_ID) %>% + mutate(dupe = n() > 1) -> combination_dup +dupes <- combination_dup[combination_dup$dupe == "TRUE", ] + + +#Basemap +basemap <- ggplot(combination) + + geom_polygon( + data = world, + aes(x = long, y = lat, group = group), + colour = "gray87", + fill = "gray87", + size = 0.5 + ) + + geom_polygon( + data = lakes, + aes(x = long, y = lat, group = group), + colour = "gray87", + fill = "white", + size = 0.3 + ) + + theme( + panel.grid.major = element_blank(), + #all of these lines are just removing default things like grid lines, axises etc + panel.grid.minor = element_blank(), + axis.title.x = element_blank(), + axis.title.y = element_blank(), + axis.line = element_blank(), + panel.border = element_blank(), + panel.background = element_rect(fill = "white"), + axis.text.x = element_blank(), + axis.text.y = element_blank(), + axis.ticks = element_blank() + ) + + coord_map(projection = "vandergrinten", ylim = c(-56, 67)) + +#plotting informativity map +i <- + basemap + geom_point( + data = combination, + aes(x = Longitude, y = Latitude, colour = informativity_st, fill = informativity_st), + pch = 21, + size = 1.1, + alpha = 1, + position = position_jitter( + width = 1, + height = 1, + seed = 123 + ) + ) + + scale_fill_viridis_c(option = "viridis", direction = -1) + + scale_color_viridis_c(option = "viridis", + guide = "none", + direction = -1) + + theme( + plot.title = element_text(size = 15), + legend.title = element_text(size = 15), + legend.text = element_text(size = 15), + legend.key.size = unit(0.5, units = "cm"), + legend.direction = "horizontal", + legend.position = c(.4, .07) + ) + + guides(fill = guide_colourbar()) + + labs(title = "Informativity", fill = "score") +i + +ggsave( + file = "output/map_informativity.svg", + plot = i, + width = 10, + height = 9, + dpi=300 +) + +ggsave( + file = "output/map_informativity.tiff", + plot = i, + width = 10, + height = 9, + dpi=600 +) + + +#plotting boundness map +b <- + basemap + geom_point( + data = combination, + aes(x = Longitude, y = Latitude, colour = boundness_st, fill = boundness_st), + pch = 21, + size = 1.1, + alpha = 1, + position = position_jitter( + width = 1, + height = 1, + seed = 123 + ) + ) + + scale_fill_viridis_c(option = "magma", direction = -1) + + scale_color_viridis_c(option = "magma", + guide = "none", + direction = -1) + + theme( + plot.title = element_text(size = 15), + legend.title = element_text(size = 15), + legend.text = element_text(size = 15), + legend.key.size = unit(0.5, units = "cm"), + legend.direction = "horizontal", + legend.position = c(.4, .07) + ) + + guides(fill = guide_colourbar()) + + labs(title = "Boundness", fill = "score") + +ggsave( + file = "output/map_boundness.svg", + plot = b, + width = 10, + height = 9, + dpi=300 +) + +ggsave( + file = "output/map_boundness.tiff", + plot = b, + width = 10, + height = 9, + dpi=600 +) + + + +i <- + basemap + geom_point( + data = combination, + aes( + x = Longitude, + y = Latitude, + fill = informativity_st, + color = informativity_st + ), + pch = 21, + size = 1.1, + alpha = 1, + position = position_jitter( + width = 1, + height = 1, + seed = 123 + ) + ) + + scale_fill_viridis_c(option = "viridis", direction = -1) + + scale_color_viridis_c(option = "viridis", direction = -1) + + theme( + text = element_text(size = 15), + legend.text = element_text(size = 15), + legend.key.size = unit(0.5, units = "cm"), + legend.direction = "horizontal", + legend.position = c(.4, .07) + ) + + guides(fill = guide_colourbar(), color = "none") + + labs(fill = "informativity") + +b <- + basemap + geom_point( + data = combination, + aes( + x = Longitude, + y = Latitude, + fill = boundness_st, + color = boundness_st + ), + pch = 21, + size = 1.1, + alpha = 1, + position = position_jitter( + width = 1, + height = 1, + seed = 123 + ) + ) + + scale_fill_viridis_c(option = "magma", direction = -1) + + scale_color_viridis_c(option = "magma", direction = -1) + + theme( + text = element_text(size = 15), + legend.text = element_text(size = 15), + legend.key.size = unit(0.5, units = "cm"), + legend.direction = "horizontal", + legend.position = c(.4, .07) + ) + + guides(fill = guide_colourbar(), color = "none") + + labs(fill = "fusion") + +two_maps <- b / i + +ggsave( + file = "output/maps.tiff", + plot = two_maps, + width = 5, + height = 7, + dpi=800 +) + +ggsave( + file = "output/maps.svg", + plot = two_maps, + width = 5, + height = 7, + dpi=600 +) + +ggsave( + file = "output/maps.pdf", + plot = two_maps, + width = 5, + height = 7, + dpi=600 +) + +ggsave( + file = "output/maps.jpeg", + plot = two_maps, + width = 5, + height = 7, + dpi=600 +) + + + +#histograms +# hist_b <- ggplot(metrics_joined, aes(x = boundness_st)) + +# geom_histogram(color = "black", aes(fill = ..x..)) + +# scale_fill_viridis_c(option = "magma", direction = -1) + +# labs(x = "fusion", fill = "score") + +# theme_classic(base_size = 22) +# +# hist_i <- ggplot(metrics_joined, aes(x = informativity_st)) + +# geom_histogram(color = "black", aes(fill = ..x..)) + +# scale_fill_viridis_c(option = "viridis", direction = -1) + +# labs(x = "informativity", fill = "score") + +# theme_classic(base_size = 22) +# +# ggsave( +# file = "output/hist_boundness.svg", +# plot = hist_b, +# width = 7, +# height = 5, +# dpi=300 +# ) +# ggsave( +# file = "output/hist_informativity.svg", +# plot = hist_i, +# width = 7, +# height = 5, +# dpi=300 +# ) diff --git a/101/replication_package/plot_social_effects_combined.R b/101/replication_package/plot_social_effects_combined.R new file mode 100644 index 0000000000000000000000000000000000000000..0ffc0147bc23362ebda5c1bf9a99c5723809562e --- /dev/null +++ b/101/replication_package/plot_social_effects_combined.R @@ -0,0 +1,221 @@ +suppressPackageStartupMessages({ + library(dplyr) + library(ggplot2) +}) + +# script was written by Olena Shcherbakova and modified by Sam Passmore + +effs_I <- + read.csv("output_tables/ effects Informativity_social_models .csv") +effs_I$variable <- "informativity" + +effs_B <- + read.csv("output_tables/ effects Boundness_social_models .csv") +effs_B$variable <- "fusion" + +effs_B <- effs_B %>% + rename(lower = 2, + upper = 4, + mean = 3) + +effs_I <- effs_I %>% + rename(lower = 2, + upper = 4, + mean = 3) + +effs_1 <- as.data.frame(rbind(effs_B, effs_I)) + +effs_1$control <- "yes" + +effs_I <- + read.csv("output_tables/ effects Informativity_social_only_models .csv") +effs_I$variable <- "informativity" + +effs_B <- + read.csv("output_tables/ effects Boundness_social_only_models .csv") +effs_B$variable <- "fusion" + +effs_B <- effs_B %>% + rename(lower = 2, + upper = 4, + mean = 3) + +effs_I <- effs_I %>% + rename(lower = 2, + upper = 4, + mean = 3) + +effs_2 <- as.data.frame(rbind(effs_B, effs_I)) +effs_2$control <- "no" + +effs_1 <- effs_1 %>% + rename(lower = 2, + upper = 4, + mean = 3) + +effs_2 <- effs_2 %>% + rename(lower = 2, + upper = 4, + mean = 3) + +effs <- as.data.frame(rbind(effs_1, effs_2)) + +effs_main <- effs %>% + rename(lower = 2, + upper = 4, + mean = 3) %>% + filter(!grepl("nonlinear", model)) %>% + filter(!grepl("SD", effect)) %>% + filter(!grepl("Intercept", effect)) + + +#removing "(linear)" part within the model column +effs_main$model <- gsub("(\\s*\\(\\w+\\))", "", effs_main$model) + +#adding "combined" after L1/L1 proportion where applicable +effs_main$effect <- + ifelse( + grepl("L1 speakers\\+", effs_main$model), + paste(effs_main$effect, "(combined)"), + effs_main$effect + ) + +effs_main <- effs_main %>% + mutate( + effect = dplyr::recode( + effect, + "L2 proportion (combined)" = "L2 (combined)", + "L1*L2 proportion" = "L1*L2", + "L2 proportion" = "L2" + ) + ) + +eff_main_plot_df = effs_main %>% + as.data.frame() %>% + mutate_if(is.character, as.factor) %>% + mutate(effect = factor( + effect, + levels = c( + "Education", + "Neighbours", + "Official status", + "L1*L2", + "L2 (combined)", + "L1 (combined)", + "L2", + "L1" + ) + )) %>% + mutate(importance = case_when((lower < 0 & + upper < 0) ~ "negative", + (lower > 0 & + upper > 0) ~ "positive", + (lower < 0 & upper > 0) | + (lower < 0 & + upper == 0) | + (lower == 0 & upper > 0) ~ "no" + )) %>% + mutate(importance = as.factor(importance)) %>% + mutate(importance = factor( + importance, + levels = c("no", "positive", "negative"), + ordered = TRUE + )) %>% + mutate(control = if_else(control == "yes", "control", "no control")) %>% + mutate(control = factor(control, levels = c("control", "no control"), ordered = TRUE)) + +dodge_width <- 0.8 + +effs_main_plot_bw <- ggplot(eff_main_plot_df, + aes( + y = effect, + x = mean, + linetype = control, + color = importance + )) + + geom_errorbar( + aes(xmin = lower, xmax = upper), + width = 0.5, + linewidth = 3, + position = position_dodge(width = dodge_width) + ) + + geom_point(size = 10, + position = position_dodge(width = dodge_width)) + + geom_line(position = position_dodge(width = dodge_width)) + + geom_vline( + aes(xintercept = 0), + linetype = 2, + linewidth = 1, + alpha = 0.7 + ) + + scale_color_manual(values = c("black", "red3", "steelblue")) + + ylab("") + + xlab("Estimate: 95% credible interval") + +# theme_light() + + theme_minimal() + +facet_grid(. ~ variable, scales = "free_x", space = "free") + + theme( + text = element_text(size = 55), # face = "bold"), +# legend.text = element_text(size = 25), + axis.title = element_text(size = 50), +# legend.title = element_text(size = 25), +# strip.text.x = element_text(size = 25), + legend.spacing.y = unit(2.7, 'cm'), + legend.key.width = unit(2, 'cm'), + legend.direction = "horizontal", + legend.position = "top", + legend.title = element_blank(), + axis.line = element_line(linewidth = 1), + strip.background = element_rect(color = "black", linewidth = 2), + panel.spacing.x = unit(15, "mm"), + panel.grid = element_blank(), + panel.border = element_rect(color = "gray 50", fill = NA) + ) + + guides(color = "none") + + +effs_main_plot_bw + +ggsave( + file = "output/effects_plot.png", + plot = effs_main_plot_bw, + height = 24, + width = 30, + dpi = 400 +) + + +ggsave( + file = "output/effects_plot.tiff", + plot = effs_main_plot_bw, + height = 22, + width = 36, + dpi = 400 +) + +effs_main_plot_bw +ggsave( + file = "output/effects_plot.svg", + plot = effs_main_plot_bw, + height = 22, + width = 36, + dpi = 600 +) + +effs_main_plot_bw +ggsave( + file = "output/effects_plot.pdf", + plot = effs_main_plot_bw, + height = 22, + width = 36, + dpi = 600 +) + +effs_main_plot_bw +ggsave( + file = "output/effects_plot.jpeg", + plot = effs_main_plot_bw, + height = 22, + width = 36, + dpi = 600 +) diff --git a/101/replication_package/plot_spatial_parameters_linear_distances.R b/101/replication_package/plot_spatial_parameters_linear_distances.R new file mode 100644 index 0000000000000000000000000000000000000000..897d48b3120509bd21cb113db9d09fc559d30d8a --- /dev/null +++ b/101/replication_package/plot_spatial_parameters_linear_distances.R @@ -0,0 +1,119 @@ +#plotting the assumptions of different versions of spatial control and how their parameters relate to distances in km + +#script written by Sam Passmore and modified by Olena Shcherbakova + +#two sets +cols = c(brewer.pal(6, "Dark2")) + +# Assume these are kilometers +n_points = 2500 #with this many points (233) we achieve roughly the minimal distance that corresponds to the minimal distance in our small sample data +longitude = seq(from = -90, to = 90, length.out = n_points) #with this span we achieve roughly the maximum distance between points that corresponds to the one found in our data +latitude = rep(0, n_points) +df = data.frame(latitude = latitude, + longitude = longitude) + +parameters = data.frame(kappa = c(1, 1), + phi = c(1.25, 17)) + +parameters$name = c(sprintf("phi%.2fkappa%.2f", parameters$phi, parameters$kappa)) + +#parameters <- parameters %>% +# filter(kappa==0.5) + + +## Covariance matrix + +spatial_parameters = map2(parameters$kappa, parameters$phi,function(k, p){ + spatial_covar_mat = varcov.spatial(coords = df, + cov.pars = c(1, p), + kappa = k, + cov.model= "matern")$varcov + spatial_covar_mat +}) + +## Distance matrix (in km - so divide by 1000) +dist_data = as.matrix(df[,c("longitude", "latitude")], ncol = 2) +dist_matrix = distm(dist_data, fun = distHaversine) / 1000 + +euclidean_dist = geosphere::distm(df[,c("longitude", "latitude")], + fun = distHaversine) +dimnames(euclidean_dist) = list(c(1:n_points), c(1:n_points)) +# scale +euclidean_dist = scales::rescale(euclidean_dist) + + +diag(dist_matrix) + +distance = round(dist_matrix[lower.tri(dist_matrix)], 4) +transformed_dist = round(euclidean_dist[lower.tri(euclidean_dist)], 4) + +datafr <- as.data.frame(cbind(distance, transformed_dist)) +datafr$covariance <- rep(0,1) #a scale from 0 to 1 to make sure we have a "y axis" to which spatial parameter lines will later be plotted + +plot_n = 1000 + +sample_idx = ceiling(seq(1, nrow(datafr)-1, length.out = plot_n)) + +plot_ss = datafr[sample_idx,] +plot_ss$index = sample_idx +plot_ss = plot_ss[order(plot_ss$distance),] + +spatialkappa_lines = lapply(spatial_parameters, function(x) { + d = sort(c(x[lower.tri(x)]), decreasing = TRUE) + sample_idx = seq(1, length(d), length.out = plot_n) + d[sample_idx] +}) + +legend_text = c(bquote("local:" ~ kappa == .(parameters[1,1]) ~ "; " ~ phi == .(parameters[1,2])), + bquote("regional:" ~ kappa == .(parameters[2,1]) ~ "; " ~ phi == .(parameters[2,2]))) + +#final version: zoomed in on the distances of up to 10000 km +svg("output/plot_spatial_pars_km_zoomed.svg", width = 8, height = 8, dpi=300) +plot(x = plot_ss$distance, y = plot_ss$covariance, + type = "l", main = "Spatial parameters", col = "white", #not plotting these lines; just keeping to axis + ylim = c(0, 1), + xlim = c(0, 10000), + xlab = "Distance (km)", + ylab = "Covariance", + frame.plot = TRUE, + cex.main=1.7, + axes=FALSE, + cex.lab=1.5 +) +axis(1, at = seq(0,10000,by=2000), labels = seq(0,10000,by=2000), tick = TRUE, cex.axis=1.4) +axis(2, at = seq(0,1,by=0.2), labels = seq(0,1,by=0.2), tick = TRUE, cex.axis=1.4) + +for(i in seq_along(spatialkappa_lines)){ + lines(x = plot_ss$distance, y = spatialkappa_lines[[i]], col = cols[i], lwd = 2) +} + +legend("topright", + legend=legend_text, + col=cols, lty=1, cex=1.5, lwd = 3) +x <- dev.off() + + + +#full version +svg("output/plot_spatial_pars_km.svg", width = 8, height = 8, dpi=300) +plot(x = plot_ss$distance, y = plot_ss$covariance, + type = "l", main = "Spatial parameters", col = "white", #not plotting these lines; just keeping to axis + ylim = c(0, 1), + xlim = c(0, 15000), + xlab = "Distance (km)", + ylab = "Covariance", + frame.plot = TRUE, + cex.main=1.7, + axes=FALSE, + cex.lab=1.5) +axis(1, at = seq(0,15000,by=2500), labels = seq(0,15000,by=2500), tick = TRUE, cex.axis=1.4) +axis(2, at = seq(0,1,by=0.2), labels = seq(0,1,by=0.2), tick = TRUE, cex.axis=1.4) +for(i in seq_along(spatialkappa_lines)){ + lines(x = plot_ss$distance, y = spatialkappa_lines[[i]], col = cols[i], lwd = 2) +} + +legend("topright", + legend=legend_text, + col=cols, lty=1, cex=1.5, lwd = 3) +x <- dev.off() + diff --git a/101/replication_package/plots_social_effects_combined_on_reduced.R b/101/replication_package/plots_social_effects_combined_on_reduced.R new file mode 100644 index 0000000000000000000000000000000000000000..5f7f40a2b7397771aaafd28bb62b59e0ec06c315 --- /dev/null +++ b/101/replication_package/plots_social_effects_combined_on_reduced.R @@ -0,0 +1,183 @@ +suppressPackageStartupMessages({ + library(dplyr) + library(ggplot2) +}) + +# script was written by Olena Shcherbakova and modified by Sam Passmore + +effs_I <- + read.csv("output_tables_reduced/ effects Informativity_social_models .csv") +effs_I$variable <- "informativity" + +effs_B <- + read.csv("output_tables_reduced/ effects Boundness_social_models .csv") +effs_B$variable <- "fusion" + +effs_B <- effs_B %>% + rename(lower = 2, + upper = 4, + mean = 3) + +effs_I <- effs_I %>% + rename(lower = 2, + upper = 4, + mean = 3) + +effs_1 <- as.data.frame(rbind(effs_B, effs_I)) + +effs_1$control <- "yes" + +effs_I <- + read.csv("output_tables_reduced/ effects Informativity_social_only_models .csv") +effs_I$variable <- "informativity" + +effs_B <- + read.csv("output_tables_reduced/ effects Boundness_social_only_models .csv") +effs_B$variable <- "fusion" + +effs_B <- effs_B %>% + rename(lower = 2, + upper = 4, + mean = 3) + +effs_I <- effs_I %>% + rename(lower = 2, + upper = 4, + mean = 3) + +effs_2 <- as.data.frame(rbind(effs_B, effs_I)) +effs_2$control <- "no" + +effs <- as.data.frame(rbind(effs_1, effs_2)) + +effs_main <- effs %>% + rename(lower = 2, + upper = 4, + mean = 3) %>% + filter(!grepl("nonlinear", model)) %>% + filter(!grepl("SD", effect)) %>% + filter(!grepl("Intercept", effect)) + + +#removing "(linear)" part within the model column +effs_main$model <- gsub("(\\s*\\(\\w+\\))", "", effs_main$model) + +#adding "combined" after L1/L1 proportion where applicable +effs_main$effect <- + ifelse( + grepl("L1 speakers\\+", effs_main$model), + paste(effs_main$effect, "(combined)"), + effs_main$effect + ) + +effs_main <- effs_main %>% + mutate(effect = dplyr::recode( + effect, + "L2 proportion (combined)" = "L2 (combined)", + "L2 proportion" = "L2" + )) + +eff_main_plot_df = effs_main %>% + as.data.frame() %>% + mutate_if(is.character, as.factor) %>% + mutate(effect = factor( + effect, + levels = c( + "Education", + "Neighbours", + "Official status", + "L2 (combined)", + "L1 (combined)", + "L2", + "L1" + ) + )) %>% + mutate(importance = case_when((lower < 0 & + upper < 0) ~ "negative", + (lower > 0 & + upper > 0) ~ "positive", + (lower < 0 & upper > 0) | + (lower < 0 & + upper == 0) | (lower == 0 & upper > 0) ~ "no" + )) %>% + mutate(importance = as.factor(importance)) %>% + mutate(importance = factor( + importance, + levels = c("no", "positive", "negative"), + ordered = TRUE + )) %>% + mutate(control = factor(control, levels = c("yes", "no"), ordered = TRUE)) + +effs_main_plot_bw <- ggplot(eff_main_plot_df, + aes( + y = effect, + x = mean, + linetype = control, + color = importance + )) + + geom_errorbar( + aes(xmin = lower, xmax = upper), + width = 0.6, + size = 2.5, + position = position_dodge(width = 0.8) + ) + + geom_point(size = 10, + position = position_dodge(width = 0.8)) + + geom_line(position = position_dodge(width = 0.8)) + + geom_vline(aes(xintercept = 0), + linetype = 2, size = 1, alpha = 0.7) + + scale_color_manual(values = c("black", "red3", "steelblue")) + + ylab("") + + xlab("Estimate: 95% credible interval") + + theme_classic() + + facet_grid(. ~ variable, scales = "free_x", space = "free") + + theme( + axis.text = element_text(size = 65), + legend.text = element_text(size = 65), + axis.title = element_text(size = 65), + legend.title = element_text(size = 65), + strip.text.x = element_text(size = 65), + legend.spacing.y = unit(2.7, 'cm'), + legend.key.width = unit(2, 'cm'), + legend.direction = "horizontal", + legend.position = "top", + axis.line = element_line(linewidth = 1), + strip.background = element_rect(color = "black", linewidth = 1), + panel.spacing.x = unit(15, "mm") + ) + + guides(color = "none") + + +effs_main_plot_bw +ggsave( + file = "output_reduced/effects_plot.svg", + plot = effs_main_plot_bw, + height = 22, + width = 36, + dpi = 300 +) + +effs_main_plot_bw +ggsave( + file = "output_reduced/effects_plot.jpeg", + plot = effs_main_plot_bw, + height = 22, + width = 36, + dpi = 300 +) + +ggsave( + file = "output_reduced/effects_plot.tiff", + plot = effs_main_plot_bw, + height = 22, + width = 36, + dpi = 400 +) + +ggsave( + file = "output_reduced/effects_plot.pdf", + plot = effs_main_plot_bw, + height = 22, + width = 36, + dpi = 400 +) diff --git a/101/replication_package/requirements.R b/101/replication_package/requirements.R new file mode 100644 index 0000000000000000000000000000000000000000..6b68fc10e6546ef057ff214d2ff8d8a2a0502a0a --- /dev/null +++ b/101/replication_package/requirements.R @@ -0,0 +1,176 @@ +# Please run this script first to make sure you have all the necessary packages +# installed for running the rest of the scripts in this R project + +.libPaths(c("rlib/", .libPaths())) + +if (!suppressPackageStartupMessages(require("pacman"))) { install.packages("pacman") } + +pacman::p_load( + here, + tidyverse, + reshape2, + broom, + glue, + forcats, + magrittr, + stringr, + purrr, + rcompanion, + naniar, + readr, + tidyr, + dplyr, + openxlsx, + jsonlite, + readxl, + flextable, + officer, + + + #INLA - related + sp, + scico, + BiocManager, + foreach, + + MASS, + matrixStats, + + #brms +# brms, + + # imputation + missForest, + + #plotting graphs + scales, + RColorBrewer, + ggpubr, + ggplot2, + ggrepel, + gplots, + ggtree, + ggridges, + grid, + gridExtra, + scales, + ggmap, + psych, #for scatterplot matrix + viridis, + rlang, + devtools, + patchwork, + ggnewscale, + ggstance, + + #making maps + mapdata, + maptools, + maps, +# geoR, + geosphere, + fields, + + # phylogenetic packages + ape, + phytools, + nlme, + caper, + MCMCglmm, + + + # testing + assertthat, + beepr +) + +# quiet down, tidyverse: +options(tidyverse.quiet = TRUE) +options(warn.conflicts = FALSE) +options(stringsAsFactors = FALSE) + +GRAMBANK_LANGUAGES <- file.path("../..", "cldf", "languages.csv") +GRAMBANK_VALUES <- file.path("../..", "cldf", "values.csv") +GRAMBANK_PARAMETERS <- file.path("../..", "cldf", "parameters.csv") +GRAMBANK_CODES <- file.path("../..", "cldf", "codes.csv") + +# The columns specifier for readr to parse ../cldf/values.csv +VALUES_COLSPEC <- c( + ID = col_character(), + Language_ID = col_character(), + Parameter_ID = col_character(), + Value = col_character(), + Code_ID = col_character(), + Comment = col_character(), + Source = col_character() +) + +LANGUAGES_COLSPEC = c( + ID = col_character(), + Name = col_character(), + Macroarea = col_character(), + Latitude = col_double(), + Longitude = col_double(), + Glottocode = col_character(), + ISO639P3code = col_character(), + contributed_datapoints = col_character(), + provenance = col_character(), + Family_name = col_character(), + Family_id = col_character() +) + +PARAMETERS_COLSPEC = c( + ID = col_character(), + Name = col_character(), + Description = col_character(), + patron = col_character(), + name_in_french = col_character(), + Grambank_ID_desc = col_character(), + bound_morphology = col_character() +) + +CODES_COLSPEC = c( + ID = col_character(), + Parameter_ID = col_character(), + Name = col_character(), + Description = col_character() +) + +WIDE_COLSPEC = c( + .default = col_integer(), + Language_ID = col_character(), + na_prop = col_double() +) + +#creating folders +OUTPUTDIR_models <- here("output_models") +# create output dir if it does not exist. +if (!dir.exists(OUTPUTDIR_models)) { dir.create(OUTPUTDIR_models) } + +OUTPUTDIR_tables <- here("output_tables") +# create output dir if it does not exist. +if (!dir.exists(OUTPUTDIR_tables)) { dir.create(OUTPUTDIR_tables) } + +OUTPUTDIR_output <- here("output") +# create output dir if it does not exist. +if (!dir.exists(OUTPUTDIR_output)) { dir.create(OUTPUTDIR_output) } + +OUTPUTDIR_data_wrangling<- here("data_wrangling") +# create output dir if it does not exist. +if (!dir.exists(OUTPUTDIR_data_wrangling)) { dir.create(OUTPUTDIR_data_wrangling) } + +OUTPUTDIR_models_reduced <- here("output_models_reduced") +# create output dir if it does not exist. +if (!dir.exists(OUTPUTDIR_models_reduced)) { dir.create(OUTPUTDIR_models_reduced) } +OUTPUTDIR_tables_reduced <- here("output_tables_reduced") +# create output dir if it does not exist. +if (!dir.exists(OUTPUTDIR_tables_reduced)) { dir.create(OUTPUTDIR_tables_reduced) } +OUTPUTDIR_output_reduced <- here("output_reduced") +# create output dir if it does not exist. +if (!dir.exists(OUTPUTDIR_output_reduced)) { dir.create(OUTPUTDIR_output_reduced) } + +#source custom functions to have them at hand +source("varcov.spatial_function.R") + +#Adding a prior for modelling with INLA on precision/SD of random effects and likelihood: the probability of SD of each random effect and likelihood being > 1 is equal to 0.1 +pcprior_hyper = list(prec =list(prior="pc.prec", param = c(1, 0.1))) diff --git a/101/replication_package/runs_sensitivity.R b/101/replication_package/runs_sensitivity.R new file mode 100644 index 0000000000000000000000000000000000000000..02393e6eb2ccbf5b7f33b31ba972bb6ce44c046e --- /dev/null +++ b/101/replication_package/runs_sensitivity.R @@ -0,0 +1,52 @@ +source('sensitivity_testing_B_001.R') +source('sensitivity_testing_B_05.R') +source('sensitivity_testing_B_099.R') + +WAIC_0.1 <- read.csv("output_tables/ waics Boundness_social_models .csv") %>% + mutate(prior = "0.1") + +WAIC_0.01 <- read.csv("output_tables/ waics Boundness_social_models prior_0.01 .csv") %>% + mutate(prior = "0.01") + +WAIC_0.5 <- read.csv("output_tables/ waics Boundness_social_models prior_0.5 .csv") %>% + mutate(prior = "0.5") + +WAIC_0.99 <- read.csv("output_tables/ waics Boundness_social_models prior_0.99 .csv") %>% + mutate(prior = "0.99") + +sensitivity_B <- as.data.frame(rbind(WAIC_0.1, WAIC_0.01, WAIC_0.5, WAIC_0.99)) %>% + mutate(response="fusion") + + +source('sensitivity_testing_I_001.R') +source('sensitivity_testing_I_05.R') +source('sensitivity_testing_I_099.R') + +WAIC_0.1 <- read.csv("output_tables/ waics Informativity_social_models .csv") %>% + mutate(prior = "0.1") + +WAIC_0.01 <- read.csv("output_tables/ waics Informativity_social_models prior_0.01 .csv") %>% + mutate(prior = "0.01") + +WAIC_0.5 <- read.csv("output_tables/ waics Informativity_social_models prior_0.5 .csv") %>% + mutate(prior = "0.5") + +WAIC_0.99 <- read.csv("output_tables/ waics Informativity_social_models prior_0.99 .csv") %>% + mutate(prior = "0.99") + +sensitivity_I <- as.data.frame(rbind(WAIC_0.1, WAIC_0.01, WAIC_0.5, WAIC_0.99)) %>% + mutate(response="informativity") + +sensitivity_all <- as.data.frame(rbind(sensitivity_B, sensitivity_I)) + +write.csv(sensitivity_all, "output_tables/Table_sensitivity.csv") + +sensitivity_all <- sensitivity_all %>% + flextable() %>% + autofit() %>% + merge_v(j=c("response", "prior")) %>% + fix_border_issues() + +save_as_docx( + "Summary of sensitivity" = sensitivity_all, + path = "output_tables/Table_sensitivity.docx") diff --git a/101/replication_package/runs_sensitivity_on_reduced.R b/101/replication_package/runs_sensitivity_on_reduced.R new file mode 100644 index 0000000000000000000000000000000000000000..dcde19747a8c0281d6116787264ff161d9418cc2 --- /dev/null +++ b/101/replication_package/runs_sensitivity_on_reduced.R @@ -0,0 +1,52 @@ +source('sensitivity_testing_reduced_B_001.R') +source('sensitivity_testing_reduced_B_05.R') +source('sensitivity_testing_reduced_B_099.R') + +WAIC_0.1 <- read.csv("output_tables_reduced/ waics Boundness_social_models .csv") %>% + mutate(prior = "0.1") + +WAIC_0.01 <- read.csv("output_tables_reduced/ waics Boundness_social_models prior_0.01 .csv") %>% + mutate(prior = "0.01") + +WAIC_0.5 <- read.csv("output_tables_reduced/ waics Boundness_social_models prior_0.5 .csv") %>% + mutate(prior = "0.5") + +WAIC_0.99 <- read.csv("output_tables_reduced/ waics Boundness_social_models prior_0.99 .csv") %>% + mutate(prior = "0.99") + +sensitivity_B <- as.data.frame(rbind(WAIC_0.1, WAIC_0.01, WAIC_0.5, WAIC_0.99)) %>% + mutate(response="fusion") + + +source('sensitivity_testing_reduced_I_001.R') +source('sensitivity_testing_reduced_I_05.R') +source('sensitivity_testing_reduced_I_099.R') + +WAIC_0.1 <- read.csv("output_tables_reduced/ waics Informativity_social_models .csv") %>% + mutate(prior = "0.1") + +WAIC_0.01 <- read.csv("output_tables_reduced/ waics Informativity_social_models prior_0.01 .csv") %>% + mutate(prior = "0.01") + +WAIC_0.5 <- read.csv("output_tables_reduced/ waics Informativity_social_models prior_0.5 .csv") %>% + mutate(prior = "0.5") + +WAIC_0.99 <- read.csv("output_tables_reduced/ waics Informativity_social_models prior_0.99 .csv") %>% + mutate(prior = "0.99") + +sensitivity_I <- as.data.frame(rbind(WAIC_0.1, WAIC_0.01, WAIC_0.5, WAIC_0.99)) %>% + mutate(response="informativity") + +sensitivity_all <- as.data.frame(rbind(sensitivity_B, sensitivity_I)) + +write.csv(sensitivity_all, "output_tables_reduced/Table_sensitivity.csv") + +sensitivity_all <- sensitivity_all %>% + flextable() %>% + autofit() %>% + merge_v(j=c("response", "prior")) %>% + fix_border_issues() + +save_as_docx( + "Summary of sensitivity" = sensitivity_all, + path = "output_tables_reduced/Table_sensitivity.docx") diff --git a/101/replication_package/sensitivity_testing_B_001.R b/101/replication_package/sensitivity_testing_B_001.R new file mode 100644 index 0000000000000000000000000000000000000000..f385d468b53ccb7a869558c4d56d80e9e0510ffe --- /dev/null +++ b/101/replication_package/sensitivity_testing_B_001.R @@ -0,0 +1,441 @@ +#model fitting: Boundness predicted by social effects on top of random phylogenetic and spatial factors + +source("requirements.R") + +source("install_and_load_INLA.R") + +source("set_up_inla.R") + +metrics_joined <- metrics_joined %>% + filter(!is.na(L1_log10_st)) %>% + rename(L1_log_st = L1_log10_st) %>% + mutate(L1_copy = L1_log_st) %>% + filter(!is.na(L2_prop)) %>% + mutate(L2_copy = L2_prop) %>% + filter(!is.na(neighboring_languages_st)) %>% + filter(!is.na(Official)) %>% + filter(!is.na(Education)) %>% + filter(!is.na(boundness_st)) %>% + filter(!is.na(informativity_st)) + +#dropping tips not in Grambank +metrics_joined <- metrics_joined[metrics_joined$Language_ID %in% tree$tip.label, ] +tree <- keep.tip(tree, metrics_joined$Language_ID) + +x <- assert_that(all(tree$tip.label %in% metrics_joined$Language_ID), msg = "The data and phylogeny taxa do not match") + +## Building standardized phylogenetic precision matrix +tree_scaled <- tree + +tree_vcv = vcv.phylo(tree_scaled) +typical_phylogenetic_variance = exp(mean(log(diag(tree_vcv)))) + +tree_scaled$edge.length <- tree_scaled$edge.length/typical_phylogenetic_variance +phylo_prec_mat <- MCMCglmm::inverseA(tree_scaled, + nodes = "ALL", + scale = FALSE)$Ainv + +metrics_joined = metrics_joined[order(match(metrics_joined$Language_ID, rownames(phylo_prec_mat))),] + +#"local" set of parameters +## Create spatial covariance matrix using the matern covariance function +spatial_covar_mat_1 = varcov.spatial(metrics_joined[,c("Longitude", "Latitude")], + cov.pars = phi_1, kappa = kappa)$varcov +# Calculate and standardize by the typical variance +typical_variance_spatial_1 = exp(mean(log(diag(spatial_covar_mat_1)))) +spatial_cov_std_1 = spatial_covar_mat_1 / typical_variance_spatial_1 +spatial_prec_mat_1 = solve(spatial_cov_std_1) +dimnames(spatial_prec_mat_1) = list(metrics_joined$Language_ID, metrics_joined$Language_ID) + +## Since we are using a sparse phylogenetic matrix, we are matching taxa to rows in the matrix +phy_id = match(tree$tip.label, rownames(phylo_prec_mat)) +metrics_joined$phy_id = phy_id + +## Other effects are in the same order they appear in the dataset +metrics_joined$sp_id = 1:nrow(spatial_prec_mat_1) + +pcprior_hyper_0.01 = list(prec =list(prior="pc.prec", param = c(1, 0.01))) + +#Preparing the formulas for 10 competing models to be used in inla() call +listcombo <- list( + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.01)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.01)", "L1_log_st"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.01)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.01)", "f(inla.group(L1_copy), model='rw2', scale.model = TRUE)"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.01)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.01)", "L2_prop"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.01)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.01)", "f(inla.group(L2_copy), model='rw2', scale.model = TRUE)"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.01)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.01)", "f(inla.group(L1_copy), model='rw2', scale.model = TRUE)", "f(inla.group(L2_copy), model='rw2', scale.model = TRUE)"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.01)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.01)", "L1_log_st", "L2_prop"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.01)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.01)", "L1_log10:L2_prop"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.01)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.01)", "neighboring_languages_st"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.01)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.01)", "Official"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.01)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.01)", "Education")) + + +predterms <- lapply(listcombo, function(x) paste(x, collapse="+")) + +predterms <- t(as.data.frame(predterms)) + +predterms_short <- predterms + +predterms_short <- gsub("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.01)", "Phylogenetic", predterms_short, fixed=TRUE) +predterms_short <- gsub("f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.01)", "Spatial: local", predterms_short, fixed=TRUE) + +predterms_short <- gsub("f(inla.group(L1_copy), model='rw2', scale.model = TRUE)", "L1 speakers (nonlinear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("L1_log_st", "L1 speakers (linear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("f(inla.group(L2_copy), model='rw2', scale.model = TRUE)", "L2 proportion (nonlinear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("L2_prop", "L2 proportion (linear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("neighboring_languages_st", "Neighbours", predterms_short, fixed=TRUE) + + + +phylogenetic_element <- data.frame("judgement" = grepl("Phylogenetic", predterms_short), + number = 1:length(predterms_short)) +phylogenetic_element <- phylogenetic_element[phylogenetic_element$judgement == TRUE,]$number + +spatial_element_local <- data.frame("judgement" = grepl("local", predterms_short), + number = 1:length(predterms_short)) +spatial_element_local <- spatial_element_local[spatial_element_local$judgement == TRUE,]$number + +spatial_element_regional <- data.frame("judgement" = grepl("regional", predterms_short), + number = 1:length(predterms_short)) +spatial_element_regional <- spatial_element_regional[spatial_element_regional$judgement == TRUE,]$number + +spatial_element <- c(spatial_element_local, spatial_element_regional) + +L1_element <- data.frame("judgement" = grepl("L1 speakers (linear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L1_element <- L1_element[L1_element$judgement == TRUE,]$number + + +L1_nl_element <- data.frame("judgement" = grepl("L1 speakers (nonlinear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L1_nl_element <- L1_nl_element[L1_nl_element$judgement == TRUE,]$number + +L2_prop_element <- data.frame("judgement" = grepl("L2 proportion (linear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L2_prop_element <- L2_prop_element[L2_prop_element$judgement == TRUE,]$number +L2_prop_element <- L2_prop_element[-length(L2_prop_element)] #making sure that the interaction term (introduced below) is not treated as belonging to this isolated element + +L2_prop_nl_element <- data.frame("judgement" = grepl("L2 proportion (nonlinear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L2_prop_nl_element <- L2_prop_nl_element[L2_prop_nl_element$judgement == TRUE,]$number + +#can use only part of the interaction term within grepl() function +interaction_element <- data.frame("judgement" = grepl(":L2 proportion", predterms_short), + number = 1:length(predterms_short)) +interaction_element <- interaction_element[interaction_element$judgement == TRUE,]$number + +neighbour_element <- data.frame("judgement" = grepl("Neighbours", predterms_short), + number = 1:length(predterms_short)) +neighbour_element <- neighbour_element[neighbour_element$judgement == TRUE,]$number + +official_element <- data.frame("judgement" = grepl("Official", predterms_short), + number = 1:length(predterms_short)) +official_element <- official_element[official_element$judgement == TRUE,]$number + +education_element <- data.frame("judgement" = grepl("Education", predterms_short), + number = 1:length(predterms_short)) +education_element <- education_element[education_element$judgement == TRUE,]$number + + + +#preparing empty matrices to be filled with effect estimates (quantiles), model name, and WAIC value +phy_effects_matrix <- matrix(NA, 10, 5) +colnames(phy_effects_matrix) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +spa_effects_matrix <- matrix(NA, 10, 5) +colnames(spa_effects_matrix) <- c("2.5%", "50%", "97.5%", "model", "WAIC") + +intercept_matrix <- matrix(NA, 10, 5) +colnames(intercept_matrix) <- c("2.5%", "50%", "97.5%", "model", "WAIC") + +social_effects_matrix_L1 <- matrix(NA, 10, 5) +colnames(social_effects_matrix_L1) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L1_nl <- matrix(NA, 10, 5) +colnames(social_effects_matrix_L1_nl) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L2_prop <- matrix(NA, 10, 5) +colnames(social_effects_matrix_L2_prop) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L2_prop_nl <- matrix(NA, 10, 5) +colnames(social_effects_matrix_L2_prop_nl) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_N <- matrix(NA, 10, 5) +colnames(social_effects_matrix_N) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_O <- matrix(NA, 10, 5) +colnames(social_effects_matrix_O) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_E <- matrix(NA, 10, 5) +colnames(social_effects_matrix_E) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L1_L2_prop <- matrix(NA, 10, 5) +colnames(social_effects_matrix_L1_L2_prop) <- c("2.5%", "50%", "97.5%", "model", "WAIC") + +#fitted values +fitted_list <- vector("list", 10) +names(fitted_list) <- predterms_short + +#marginals of hyperparameters +marginals_hyperpar_list_gaussian <- vector("list", 10) +names(marginals_hyperpar_list_gaussian) <- predterms_short + +marginals_hyperpar_list_phy <- vector("list", 10) +names(marginals_hyperpar_list_phy) <- predterms_short + +marginals_hyperpar_list_spa <- vector("list", 10) +names(marginals_hyperpar_list_spa) <- predterms_short + +marginals_hyperpar_list_social_L1_nl <- vector("list", 10) +names(marginals_hyperpar_list_social_L1_nl) <- predterms_short + +marginals_hyperpar_list_social_L2_prop_nl <- vector("list", 10) +names(marginals_hyperpar_list_social_L2_prop_nl) <- predterms_short + + +#marginals of fixed effects +marginals_fixed_list_Intercept <- vector("list", 10) +names(marginals_fixed_list_Intercept) <- predterms_short + +marginals_fixed_list_L1 <- vector("list", 10) +names(marginals_fixed_list_L1) <- predterms_short + +marginals_fixed_list_L2_prop <- vector("list", 10) +names(marginals_fixed_list_L2_prop) <- predterms_short + +marginals_fixed_list_O <- vector("list", 10) +names(marginals_fixed_list_O) <- predterms_short + +marginals_fixed_list_N <- vector("list", 10) +names(marginals_fixed_list_N) <- predterms_short + +marginals_fixed_list_E <- vector("list", 10) +names(marginals_fixed_list_E) <- predterms_short + +marginals_fixed_list_L1_L2_prop <- vector("list", 10) +names(marginals_fixed_list_L1_L2_prop) <- predterms_short + + + + +#summary statistics of random effects +summary_random_list_phy <- vector("list", 10) +names(summary_random_list_phy) <- predterms_short + +summary_random_list_spa <- vector("list", 10) +names(summary_random_list_spa) <- predterms_short + +summary_random_list_social_L1_nl <- vector("list", 10) +names(summary_random_list_social_L1_nl) <- predterms_short + +summary_random_list_social_L2_prop_nl <- vector("list", 10) +names(summary_random_list_social_L2_prop_nl) <- predterms_short + + +coefm <- matrix(NA,10,1) +result <- vector("list",10) + +for(i in 1:10){ + formula <- as.formula(paste("boundness_st ~ ",predterms[[i]])) + result[[i]] <- inla(formula, family="gaussian", + control.family = list(hyper = pcprior_hyper_0.01), + #control.inla = list(tolerance = 1e-8, h = 0.0001), + #tolerance: the tolerance for the optimisation of the hyperparameters + #h: the step-length for the gradient calculations for the hyperparameters. + data=metrics_joined, control.compute=list(waic=TRUE)) + + coefm[i,1] <- round(result[[i]]$waic$waic, 2) + + intercept_matrix[i, 1:3] <- c(result[[i]]$summary.fixed[1,]$`0.025quant`, result[[i]]$summary.fixed[1,]$`0.5quant`, result[[i]]$summary.fixed[1,]$`0.975quant`) + intercept_matrix[i, 4] <- predterms_short[[i]] + intercept_matrix[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_Intercept[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["(Intercept)"]])) + colnames(marginals_fixed_list_Intercept[[i]]) <- c("x for Intercept", "y for Intercept") + + if(i %in% phylogenetic_element) { + phy_effects_matrix[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for phy_id`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + phy_effects_matrix[i, 4] <- predterms_short[[i]] + phy_effects_matrix[i, 5] <- result[[i]]$waic$waic + } + + if(i %in% spatial_element) { + spa_effects_matrix[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for sp_id`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + spa_effects_matrix[i, 4] <- predterms_short[[i]] + spa_effects_matrix[i, 5] <- result[[i]]$waic$waic + } + + + if(i %in% L1_nl_element){ + social_effects_matrix_L1_nl[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for inla.group(L1_copy)`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + social_effects_matrix_L1_nl[i, 4] <- predterms_short[[i]] + social_effects_matrix_L1_nl[i, 5] <- result[[i]]$waic$waic + } + + if(i %in% L2_prop_nl_element){ + social_effects_matrix_L2_prop_nl[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for inla.group(L2_copy)`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + social_effects_matrix_L2_prop_nl[i, 4] <- predterms_short[[i]] + social_effects_matrix_L2_prop_nl[i, 5] <- result[[i]]$waic$waic + } + + if(i %in% L1_element) { + social_effects_matrix_L1[i, 1:3] <- c(result[[i]]$summary.fixed["L1_log_st",]$`0.025quant`, result[[i]]$summary.fixed["L1_log_st",]$`0.5quant`, result[[i]]$summary.fixed["L1_log_st",]$`0.975quant`) + social_effects_matrix_L1[i, 4] <- predterms_short[[i]] + social_effects_matrix_L1[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_L1[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["L1_log_st"]])) + colnames(marginals_fixed_list_L1[[i]]) <- c("x for L1", "y for L1") + } + + if(i %in% L2_prop_element) { + social_effects_matrix_L2_prop[i, 1:3] <- c(result[[i]]$summary.fixed["L2_prop",]$`0.025quant`, result[[i]]$summary.fixed["L2_prop",]$`0.5quant`, result[[i]]$summary.fixed["L2_prop",]$`0.975quant`) + social_effects_matrix_L2_prop[i, 4] <- predterms_short[[i]] + social_effects_matrix_L2_prop[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_L2_prop[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["L2_prop"]])) + colnames(marginals_fixed_list_L2_prop[[i]]) <- c("x for L2 proportion", "y for L2 proportion") + } + + if(i %in% interaction_element) { + social_effects_matrix_L1_L2_prop[i, 1:3] <- c(result[[i]]$summary.fixed["L1_log10:L2_prop",]$`0.025quant`, result[[i]]$summary.fixed["L1_log10:L2_prop",]$`0.5quant`, result[[i]]$summary.fixed["L1_log10:L2_prop",]$`0.975quant`) + social_effects_matrix_L1_L2_prop[i, 4] <- predterms_short[[i]] + social_effects_matrix_L1_L2_prop[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_L1_L2_prop[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["L1_log10:L2_prop"]])) + colnames(marginals_fixed_list_L1_L2_prop[[i]]) <- c("x for L1*L2 proportion", "y for L1*L2 proportion") + } + + if(i %in% neighbour_element) { + social_effects_matrix_N[i, 1:3] <- c(result[[i]]$summary.fixed[2,]$`0.025quant`, result[[i]]$summary.fixed[2,]$`0.5quant`, result[[i]]$summary.fixed[2,]$`0.975quant`) + social_effects_matrix_N[i, 4] <- predterms_short[[i]] + social_effects_matrix_N[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_N[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][[2]])) + colnames(marginals_fixed_list_N[[i]]) <- c("x for Neighbours", "y for Neighbours") + } + + if(i %in% official_element) { + social_effects_matrix_O[i, 1:3] <- c(result[[i]]$summary.fixed[2,]$`0.025quant`, result[[i]]$summary.fixed[2,]$`0.5quant`, result[[i]]$summary.fixed[2,]$`0.975quant`) + social_effects_matrix_O[i, 4] <- predterms_short[[i]] + social_effects_matrix_O[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_O[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][[2]])) + colnames(marginals_fixed_list_O[[i]]) <- c("x for Official", "y for Official") + } + + if(i %in% education_element) { + social_effects_matrix_E[i, 1:3] <- c(result[[i]]$summary.fixed[2,]$`0.025quant`, result[[i]]$summary.fixed[2,]$`0.5quant`, result[[i]]$summary.fixed[2,]$`0.975quant`) + social_effects_matrix_E[i, 4] <- predterms_short[[i]] + social_effects_matrix_E[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_E[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][[2]])) + colnames(marginals_fixed_list_E[[i]]) <- c("x for Education", "y for Education") + } + + fitted_list[[i]] <- result[[i]]$summary.fitted.values + fitted_list[[i]] <- fitted_list[[i]] %>% + mutate(across(where(is.numeric), round, 2)) + + marginals_hyperpar_list_gaussian[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for the Gaussian observations"]])) + colnames(marginals_hyperpar_list_gaussian[[i]]) <- c("x for the Gaussian observations", "y for the Gaussian observations") + + if(i %in% phylogenetic_element){ + marginals_hyperpar_list_phy[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for phy_id"]])) + colnames(marginals_hyperpar_list_phy[[i]]) <- c("x for phy_id", "y for phy_id") + } + + if(i %in% spatial_element){ + marginals_hyperpar_list_spa[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for sp_id"]])) + colnames(marginals_hyperpar_list_spa[[i]]) <- c("x for sp_id", "y for sp_id") + } + + if(i %in% L1_nl_element){ + marginals_hyperpar_list_social_L1_nl[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for inla.group(L1_copy)"]])) + colnames(marginals_hyperpar_list_social_L1_nl[[i]]) <- c("x for inla.group(L1_copy)", "y for inla.group(L1_copy)") + } + + if(i %in% L2_prop_nl_element){ + marginals_hyperpar_list_social_L2_prop_nl[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for inla.group(L2_copy)"]])) + colnames(marginals_hyperpar_list_social_L2_prop_nl[[i]]) <- c("x for inla.group(L2_copy)", "y for inla.group(L2_copy)") + } + + if(i %in% phylogenetic_element){ + summary_random_list_phy[[i]] <- cbind(result[[i]]$summary.random$phy_id) %>% + rename(phy_id = ID) %>% + as.data.frame() %>% + mutate(across(where(is.numeric), round, 2)) + } + + if(i %in% spatial_element){ + summary_random_list_spa[[i]] <- cbind(result[[i]]$summary.random$sp_id) %>% + rename(sp_id = ID) %>% + as.data.frame() %>% + mutate(across(where(is.numeric), round, 2)) + } +} + +#beepr::beep(5) + +save(result, file = "output_models/models_Boundness_social_0.01.RData") + +coefm <- as.data.frame(cbind(predterms_short, coefm)) +colnames(coefm) <- c("model", "WAIC") +coefm <- coefm %>% + mutate(across(.cols=2, as.numeric)) %>% + mutate(across(where(is.numeric), round, 2)) %>% + arrange(WAIC) + +coefm$WAIC <- as.numeric(coefm$WAIC) +coefm <- coefm[order(coefm$WAIC),] + +coefm_path <- paste("output_tables/", "waics", "Boundness_social_models", "prior_0.01", ".csv", collapse = "") +write.csv(coefm, coefm_path, row.names=FALSE) + + +phy_effects<-as.data.frame(phy_effects_matrix) +spa_effects<-as.data.frame(spa_effects_matrix) +intercept_effects <- as.data.frame(intercept_matrix) +L1_effects <- as.data.frame(social_effects_matrix_L1) +L1_nl_effects <- as.data.frame(social_effects_matrix_L1_nl) +L2_prop_effects <- as.data.frame(social_effects_matrix_L2_prop) +L2_prop_nl_effects <- as.data.frame(social_effects_matrix_L2_prop_nl) +N_effects<-as.data.frame(social_effects_matrix_N) +E_effects<-as.data.frame(social_effects_matrix_E) +O_effects<-as.data.frame(social_effects_matrix_O) +interaction_effects <- as.data.frame(social_effects_matrix_L1_L2_prop) + +phy_effects$effect <- "phylogenetic SD" +spa_effects$effect <- "spatial SD" +intercept_effects$effect <- "Intercept" +L1_effects$effect <- "L1" +L1_nl_effects$effect <- "social SD:\nL1" +L2_prop_effects$effect <- "L2 proportion" +L2_prop_nl_effects$effect <- "social SD:\nL2 proportion" +N_effects$effect <- "Neighbours" +E_effects$effect <- "Education" +O_effects$effect <- "Official status" +interaction_effects$effect <- "L1*L2 proportion" + +effs <- as.data.frame(rbind(phy_effects, spa_effects, intercept_effects, L1_effects, L1_nl_effects, L2_prop_effects, L2_prop_nl_effects, N_effects, O_effects, E_effects, interaction_effects)) +effs <- effs %>% + mutate(across(.cols=c(1:3, 5), as.numeric)) %>% + mutate(across(where(is.numeric), round, 2)) %>% + na.omit() %>% + arrange(WAIC) %>% + relocate(model) + +effs_path <- paste("output_tables/", "effects", "Boundness_social_models", "prior_0.01", ".csv", collapse = "") +write.csv(effs, effs_path, row.names=FALSE) diff --git a/101/replication_package/sensitivity_testing_B_05.R b/101/replication_package/sensitivity_testing_B_05.R new file mode 100644 index 0000000000000000000000000000000000000000..5ec735ceaa83f7ed8099183758a9d2b6e1d4a21b --- /dev/null +++ b/101/replication_package/sensitivity_testing_B_05.R @@ -0,0 +1,442 @@ +#model fitting: Boundness predicted by social effects on top of random phylogenetic and spatial factors + +source("requirements.R") + +source("install_and_load_INLA.R") + +source("set_up_inla.R") + +metrics_joined <- metrics_joined %>% + filter(!is.na(L1_log10_st)) %>% + rename(L1_log_st = L1_log10_st) %>% + mutate(L1_copy = L1_log_st) %>% + filter(!is.na(L2_prop)) %>% + mutate(L2_copy = L2_prop) %>% + filter(!is.na(neighboring_languages_st)) %>% + filter(!is.na(Official)) %>% + filter(!is.na(Education)) %>% + filter(!is.na(boundness_st)) %>% + filter(!is.na(informativity_st)) + +#dropping tips not in Grambank +metrics_joined <- metrics_joined[metrics_joined$Language_ID %in% tree$tip.label, ] +tree <- keep.tip(tree, metrics_joined$Language_ID) + +x <- assert_that(all(tree$tip.label %in% metrics_joined$Language_ID), msg = "The data and phylogeny taxa do not match") + +## Building standardized phylogenetic precision matrix +tree_scaled <- tree + +tree_vcv = vcv.phylo(tree_scaled) +typical_phylogenetic_variance = exp(mean(log(diag(tree_vcv)))) + +tree_scaled$edge.length <- tree_scaled$edge.length/typical_phylogenetic_variance +phylo_prec_mat <- MCMCglmm::inverseA(tree_scaled, + nodes = "ALL", + scale = FALSE)$Ainv + +metrics_joined = metrics_joined[order(match(metrics_joined$Language_ID, rownames(phylo_prec_mat))),] + +#"local" set of parameters +## Create spatial covariance matrix using the matern covariance function +spatial_covar_mat_1 = varcov.spatial(metrics_joined[,c("Longitude", "Latitude")], + cov.pars = phi_1, kappa = kappa)$varcov +# Calculate and standardize by the typical variance +typical_variance_spatial_1 = exp(mean(log(diag(spatial_covar_mat_1)))) +spatial_cov_std_1 = spatial_covar_mat_1 / typical_variance_spatial_1 +spatial_prec_mat_1 = solve(spatial_cov_std_1) +dimnames(spatial_prec_mat_1) = list(metrics_joined$Language_ID, metrics_joined$Language_ID) + +## Since we are using a sparse phylogenetic matrix, we are matching taxa to rows in the matrix +phy_id = match(tree$tip.label, rownames(phylo_prec_mat)) +metrics_joined$phy_id = phy_id + +## Other effects are in the same order they appear in the dataset +metrics_joined$sp_id = 1:nrow(spatial_prec_mat_1) + +pcprior_hyper_0.5 = list(prec =list(prior="pc.prec", param = c(1, 0.5))) + +#Preparing the formulas for 10 competing models to be used in inla() call +listcombo <- list( + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.5)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.5)", "L1_log_st"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.5)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.5)", "f(inla.group(L1_copy), model='rw2', scale.model = TRUE)"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.5)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.5)", "L2_prop"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.5)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.5)", "f(inla.group(L2_copy), model='rw2', scale.model = TRUE)"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.5)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.5)", "f(inla.group(L1_copy), model='rw2', scale.model = TRUE)", "f(inla.group(L2_copy), model='rw2', scale.model = TRUE)"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.5)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.5)", "L1_log_st", "L2_prop"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.5)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.5)", "L1_log10:L2_prop"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.5)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.5)", "neighboring_languages_st"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.5)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.5)", "Official"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.5)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.5)", "Education")) + + +predterms <- lapply(listcombo, function(x) paste(x, collapse="+")) + +predterms <- t(as.data.frame(predterms)) + +predterms_short <- predterms + +predterms_short <- gsub("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.5)", "Phylogenetic", predterms_short, fixed=TRUE) +predterms_short <- gsub("f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.5)", "Spatial: local", predterms_short, fixed=TRUE) + +predterms_short <- gsub("f(inla.group(L1_copy), model='rw2', scale.model = TRUE)", "L1 speakers (nonlinear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("L1_log_st", "L1 speakers (linear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("f(inla.group(L2_copy), model='rw2', scale.model = TRUE)", "L2 proportion (nonlinear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("L2_prop", "L2 proportion (linear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("neighboring_languages_st", "Neighbours", predterms_short, fixed=TRUE) + + + +phylogenetic_element <- data.frame("judgement" = grepl("Phylogenetic", predterms_short), + number = 1:length(predterms_short)) +phylogenetic_element <- phylogenetic_element[phylogenetic_element$judgement == TRUE,]$number + +spatial_element_local <- data.frame("judgement" = grepl("local", predterms_short), + number = 1:length(predterms_short)) +spatial_element_local <- spatial_element_local[spatial_element_local$judgement == TRUE,]$number + +spatial_element_regional <- data.frame("judgement" = grepl("regional", predterms_short), + number = 1:length(predterms_short)) +spatial_element_regional <- spatial_element_regional[spatial_element_regional$judgement == TRUE,]$number + +spatial_element <- c(spatial_element_local, spatial_element_regional) + +L1_element <- data.frame("judgement" = grepl("L1 speakers (linear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L1_element <- L1_element[L1_element$judgement == TRUE,]$number + + +L1_nl_element <- data.frame("judgement" = grepl("L1 speakers (nonlinear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L1_nl_element <- L1_nl_element[L1_nl_element$judgement == TRUE,]$number + +L2_prop_element <- data.frame("judgement" = grepl("L2 proportion (linear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L2_prop_element <- L2_prop_element[L2_prop_element$judgement == TRUE,]$number +L2_prop_element <- L2_prop_element[-length(L2_prop_element)] #making sure that the interaction term (introduced below) is not treated as belonging to this isolated element + +L2_prop_nl_element <- data.frame("judgement" = grepl("L2 proportion (nonlinear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L2_prop_nl_element <- L2_prop_nl_element[L2_prop_nl_element$judgement == TRUE,]$number + +#can use only part of the interaction term within grepl() function +interaction_element <- data.frame("judgement" = grepl(":L2 proportion", predterms_short), + number = 1:length(predterms_short)) +interaction_element <- interaction_element[interaction_element$judgement == TRUE,]$number + +neighbour_element <- data.frame("judgement" = grepl("Neighbours", predterms_short), + number = 1:length(predterms_short)) +neighbour_element <- neighbour_element[neighbour_element$judgement == TRUE,]$number + +official_element <- data.frame("judgement" = grepl("Official", predterms_short), + number = 1:length(predterms_short)) +official_element <- official_element[official_element$judgement == TRUE,]$number + +education_element <- data.frame("judgement" = grepl("Education", predterms_short), + number = 1:length(predterms_short)) +education_element <- education_element[education_element$judgement == TRUE,]$number + + + +#preparing empty matrices to be filled with effect estimates (quantiles), model name, and WAIC value +phy_effects_matrix <- matrix(NA, 10, 5) +colnames(phy_effects_matrix) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +spa_effects_matrix <- matrix(NA, 10, 5) +colnames(spa_effects_matrix) <- c("2.5%", "50%", "97.5%", "model", "WAIC") + +intercept_matrix <- matrix(NA, 10, 5) +colnames(intercept_matrix) <- c("2.5%", "50%", "97.5%", "model", "WAIC") + +social_effects_matrix_L1 <- matrix(NA, 10, 5) +colnames(social_effects_matrix_L1) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L1_nl <- matrix(NA, 10, 5) +colnames(social_effects_matrix_L1_nl) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L2_prop <- matrix(NA, 10, 5) +colnames(social_effects_matrix_L2_prop) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L2_prop_nl <- matrix(NA, 10, 5) +colnames(social_effects_matrix_L2_prop_nl) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_N <- matrix(NA, 10, 5) +colnames(social_effects_matrix_N) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_O <- matrix(NA, 10, 5) +colnames(social_effects_matrix_O) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_E <- matrix(NA, 10, 5) +colnames(social_effects_matrix_E) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L1_L2_prop <- matrix(NA, 10, 5) +colnames(social_effects_matrix_L1_L2_prop) <- c("2.5%", "50%", "97.5%", "model", "WAIC") + +#fitted values +fitted_list <- vector("list", 10) +names(fitted_list) <- predterms_short + +#marginals of hyperparameters +marginals_hyperpar_list_gaussian <- vector("list", 10) +names(marginals_hyperpar_list_gaussian) <- predterms_short + +marginals_hyperpar_list_phy <- vector("list", 10) +names(marginals_hyperpar_list_phy) <- predterms_short + +marginals_hyperpar_list_spa <- vector("list", 10) +names(marginals_hyperpar_list_spa) <- predterms_short + +marginals_hyperpar_list_social_L1_nl <- vector("list", 10) +names(marginals_hyperpar_list_social_L1_nl) <- predterms_short + +marginals_hyperpar_list_social_L2_prop_nl <- vector("list", 10) +names(marginals_hyperpar_list_social_L2_prop_nl) <- predterms_short + + +#marginals of fixed effects +marginals_fixed_list_Intercept <- vector("list", 10) +names(marginals_fixed_list_Intercept) <- predterms_short + +marginals_fixed_list_L1 <- vector("list", 10) +names(marginals_fixed_list_L1) <- predterms_short + +marginals_fixed_list_L2_prop <- vector("list", 10) +names(marginals_fixed_list_L2_prop) <- predterms_short + +marginals_fixed_list_O <- vector("list", 10) +names(marginals_fixed_list_O) <- predterms_short + +marginals_fixed_list_N <- vector("list", 10) +names(marginals_fixed_list_N) <- predterms_short + +marginals_fixed_list_E <- vector("list", 10) +names(marginals_fixed_list_E) <- predterms_short + +marginals_fixed_list_L1_L2_prop <- vector("list", 10) +names(marginals_fixed_list_L1_L2_prop) <- predterms_short + + + + +#summary statistics of random effects +summary_random_list_phy <- vector("list", 10) +names(summary_random_list_phy) <- predterms_short + +summary_random_list_spa <- vector("list", 10) +names(summary_random_list_spa) <- predterms_short + +summary_random_list_social_L1_nl <- vector("list", 10) +names(summary_random_list_social_L1_nl) <- predterms_short + +summary_random_list_social_L2_prop_nl <- vector("list", 10) +names(summary_random_list_social_L2_prop_nl) <- predterms_short + + +coefm <- matrix(NA,10,1) +result <- vector("list",10) + +for(i in 1:10){ + formula <- as.formula(paste("boundness_st ~ ",predterms[[i]])) + result[[i]] <- inla(formula, family="gaussian", + control.family = list(hyper = pcprior_hyper_0.5), + #control.inla = list(tolerance = 1e-8, h = 0.0001), + #tolerance: the tolerance for the optimisation of the hyperparameters + #h: the step-length for the gradient calculations for the hyperparameters. + data=metrics_joined, control.compute=list(waic=TRUE)) + + coefm[i,1] <- round(result[[i]]$waic$waic, 2) + + intercept_matrix[i, 1:3] <- c(result[[i]]$summary.fixed[1,]$`0.025quant`, result[[i]]$summary.fixed[1,]$`0.5quant`, result[[i]]$summary.fixed[1,]$`0.975quant`) + intercept_matrix[i, 4] <- predterms_short[[i]] + intercept_matrix[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_Intercept[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["(Intercept)"]])) + colnames(marginals_fixed_list_Intercept[[i]]) <- c("x for Intercept", "y for Intercept") + + if(i %in% phylogenetic_element) { + phy_effects_matrix[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for phy_id`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + phy_effects_matrix[i, 4] <- predterms_short[[i]] + phy_effects_matrix[i, 5] <- result[[i]]$waic$waic + } + + if(i %in% spatial_element) { + spa_effects_matrix[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for sp_id`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + spa_effects_matrix[i, 4] <- predterms_short[[i]] + spa_effects_matrix[i, 5] <- result[[i]]$waic$waic + } + + + if(i %in% L1_nl_element){ + social_effects_matrix_L1_nl[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for inla.group(L1_copy)`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + social_effects_matrix_L1_nl[i, 4] <- predterms_short[[i]] + social_effects_matrix_L1_nl[i, 5] <- result[[i]]$waic$waic + } + + if(i %in% L2_prop_nl_element){ + social_effects_matrix_L2_prop_nl[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for inla.group(L2_copy)`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + social_effects_matrix_L2_prop_nl[i, 4] <- predterms_short[[i]] + social_effects_matrix_L2_prop_nl[i, 5] <- result[[i]]$waic$waic + } + + if(i %in% L1_element) { + social_effects_matrix_L1[i, 1:3] <- c(result[[i]]$summary.fixed["L1_log_st",]$`0.025quant`, result[[i]]$summary.fixed["L1_log_st",]$`0.5quant`, result[[i]]$summary.fixed["L1_log_st",]$`0.975quant`) + social_effects_matrix_L1[i, 4] <- predterms_short[[i]] + social_effects_matrix_L1[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_L1[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["L1_log_st"]])) + colnames(marginals_fixed_list_L1[[i]]) <- c("x for L1", "y for L1") + } + + if(i %in% L2_prop_element) { + social_effects_matrix_L2_prop[i, 1:3] <- c(result[[i]]$summary.fixed["L2_prop",]$`0.025quant`, result[[i]]$summary.fixed["L2_prop",]$`0.5quant`, result[[i]]$summary.fixed["L2_prop",]$`0.975quant`) + social_effects_matrix_L2_prop[i, 4] <- predterms_short[[i]] + social_effects_matrix_L2_prop[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_L2_prop[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["L2_prop"]])) + colnames(marginals_fixed_list_L2_prop[[i]]) <- c("x for L2 proportion", "y for L2 proportion") + } + + if(i %in% interaction_element) { + social_effects_matrix_L1_L2_prop[i, 1:3] <- c(result[[i]]$summary.fixed["L1_log10:L2_prop",]$`0.025quant`, result[[i]]$summary.fixed["L1_log10:L2_prop",]$`0.5quant`, result[[i]]$summary.fixed["L1_log10:L2_prop",]$`0.975quant`) + social_effects_matrix_L1_L2_prop[i, 4] <- predterms_short[[i]] + social_effects_matrix_L1_L2_prop[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_L1_L2_prop[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["L1_log10:L2_prop"]])) + colnames(marginals_fixed_list_L1_L2_prop[[i]]) <- c("x for L1*L2 proportion", "y for L1*L2 proportion") + } + + if(i %in% neighbour_element) { + social_effects_matrix_N[i, 1:3] <- c(result[[i]]$summary.fixed[2,]$`0.025quant`, result[[i]]$summary.fixed[2,]$`0.5quant`, result[[i]]$summary.fixed[2,]$`0.975quant`) + social_effects_matrix_N[i, 4] <- predterms_short[[i]] + social_effects_matrix_N[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_N[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][[2]])) + colnames(marginals_fixed_list_N[[i]]) <- c("x for Neighbours", "y for Neighbours") + } + + if(i %in% official_element) { + social_effects_matrix_O[i, 1:3] <- c(result[[i]]$summary.fixed[2,]$`0.025quant`, result[[i]]$summary.fixed[2,]$`0.5quant`, result[[i]]$summary.fixed[2,]$`0.975quant`) + social_effects_matrix_O[i, 4] <- predterms_short[[i]] + social_effects_matrix_O[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_O[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][[2]])) + colnames(marginals_fixed_list_O[[i]]) <- c("x for Official", "y for Official") + } + + if(i %in% education_element) { + social_effects_matrix_E[i, 1:3] <- c(result[[i]]$summary.fixed[2,]$`0.025quant`, result[[i]]$summary.fixed[2,]$`0.5quant`, result[[i]]$summary.fixed[2,]$`0.975quant`) + social_effects_matrix_E[i, 4] <- predterms_short[[i]] + social_effects_matrix_E[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_E[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][[2]])) + colnames(marginals_fixed_list_E[[i]]) <- c("x for Education", "y for Education") + } + + fitted_list[[i]] <- result[[i]]$summary.fitted.values + fitted_list[[i]] <- fitted_list[[i]] %>% + mutate(across(where(is.numeric), round, 2)) + + marginals_hyperpar_list_gaussian[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for the Gaussian observations"]])) + colnames(marginals_hyperpar_list_gaussian[[i]]) <- c("x for the Gaussian observations", "y for the Gaussian observations") + + if(i %in% phylogenetic_element){ + marginals_hyperpar_list_phy[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for phy_id"]])) + colnames(marginals_hyperpar_list_phy[[i]]) <- c("x for phy_id", "y for phy_id") + } + + if(i %in% spatial_element){ + marginals_hyperpar_list_spa[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for sp_id"]])) + colnames(marginals_hyperpar_list_spa[[i]]) <- c("x for sp_id", "y for sp_id") + } + + if(i %in% L1_nl_element){ + marginals_hyperpar_list_social_L1_nl[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for inla.group(L1_copy)"]])) + colnames(marginals_hyperpar_list_social_L1_nl[[i]]) <- c("x for inla.group(L1_copy)", "y for inla.group(L1_copy)") + } + + if(i %in% L2_prop_nl_element){ + marginals_hyperpar_list_social_L2_prop_nl[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for inla.group(L2_copy)"]])) + colnames(marginals_hyperpar_list_social_L2_prop_nl[[i]]) <- c("x for inla.group(L2_copy)", "y for inla.group(L2_copy)") + } + + if(i %in% phylogenetic_element){ + summary_random_list_phy[[i]] <- cbind(result[[i]]$summary.random$phy_id) %>% + rename(phy_id = ID) %>% + as.data.frame() %>% + mutate(across(where(is.numeric), round, 2)) + } + + if(i %in% spatial_element){ + summary_random_list_spa[[i]] <- cbind(result[[i]]$summary.random$sp_id) %>% + rename(sp_id = ID) %>% + as.data.frame() %>% + mutate(across(where(is.numeric), round, 2)) + } +} + +#beepr::beep(5) + +save(result, file = "output_models/models_Boundness_social_0.5.RData") + + +coefm <- as.data.frame(cbind(predterms_short, coefm)) +colnames(coefm) <- c("model", "WAIC") +coefm <- coefm %>% + mutate(across(.cols=2, as.numeric)) %>% + mutate(across(where(is.numeric), round, 2)) %>% + arrange(WAIC) + +coefm$WAIC <- as.numeric(coefm$WAIC) +coefm <- coefm[order(coefm$WAIC),] + +coefm_path <- paste("output_tables/", "waics", "Boundness_social_models", "prior_0.5", ".csv", collapse = "") +write.csv(coefm, coefm_path, row.names=FALSE) + + +phy_effects<-as.data.frame(phy_effects_matrix) +spa_effects<-as.data.frame(spa_effects_matrix) +intercept_effects <- as.data.frame(intercept_matrix) +L1_effects <- as.data.frame(social_effects_matrix_L1) +L1_nl_effects <- as.data.frame(social_effects_matrix_L1_nl) +L2_prop_effects <- as.data.frame(social_effects_matrix_L2_prop) +L2_prop_nl_effects <- as.data.frame(social_effects_matrix_L2_prop_nl) +N_effects<-as.data.frame(social_effects_matrix_N) +E_effects<-as.data.frame(social_effects_matrix_E) +O_effects<-as.data.frame(social_effects_matrix_O) +interaction_effects <- as.data.frame(social_effects_matrix_L1_L2_prop) + +phy_effects$effect <- "phylogenetic SD" +spa_effects$effect <- "spatial SD" +intercept_effects$effect <- "Intercept" +L1_effects$effect <- "L1" +L1_nl_effects$effect <- "social SD:\nL1" +L2_prop_effects$effect <- "L2 proportion" +L2_prop_nl_effects$effect <- "social SD:\nL2 proportion" +N_effects$effect <- "Neighbours" +E_effects$effect <- "Education" +O_effects$effect <- "Official status" +interaction_effects$effect <- "L1*L2 proportion" + +effs <- as.data.frame(rbind(phy_effects, spa_effects, intercept_effects, L1_effects, L1_nl_effects, L2_prop_effects, L2_prop_nl_effects, N_effects, O_effects, E_effects, interaction_effects)) +effs <- effs %>% + mutate(across(.cols=c(1:3, 5), as.numeric)) %>% + mutate(across(where(is.numeric), round, 2)) %>% + na.omit() %>% + arrange(WAIC) %>% + relocate(model) + +effs_path <- paste("output_tables/", "effects", "Boundness_social_models", "prior_0.5", ".csv", collapse = "") +write.csv(effs, effs_path, row.names=FALSE) diff --git a/101/replication_package/sensitivity_testing_B_099.R b/101/replication_package/sensitivity_testing_B_099.R new file mode 100644 index 0000000000000000000000000000000000000000..149cd891e8e03e83b80fe2f43b1be4c405f0fe21 --- /dev/null +++ b/101/replication_package/sensitivity_testing_B_099.R @@ -0,0 +1,442 @@ +#model fitting: Boundness predicted by social effects on top of random phylogenetic and spatial factors + +source("requirements.R") + +source("install_and_load_INLA.R") + +source("set_up_inla.R") + +metrics_joined <- metrics_joined %>% + filter(!is.na(L1_log10_st)) %>% + rename(L1_log_st = L1_log10_st) %>% + mutate(L1_copy = L1_log_st) %>% + filter(!is.na(L2_prop)) %>% + mutate(L2_copy = L2_prop) %>% + filter(!is.na(neighboring_languages_st)) %>% + filter(!is.na(Official)) %>% + filter(!is.na(Education)) %>% + filter(!is.na(boundness_st)) %>% + filter(!is.na(informativity_st)) + +#dropping tips not in Grambank +metrics_joined <- metrics_joined[metrics_joined$Language_ID %in% tree$tip.label, ] +tree <- keep.tip(tree, metrics_joined$Language_ID) + +x <- assert_that(all(tree$tip.label %in% metrics_joined$Language_ID), msg = "The data and phylogeny taxa do not match") + +## Building standardized phylogenetic precision matrix +tree_scaled <- tree + +tree_vcv = vcv.phylo(tree_scaled) +typical_phylogenetic_variance = exp(mean(log(diag(tree_vcv)))) + +tree_scaled$edge.length <- tree_scaled$edge.length/typical_phylogenetic_variance +phylo_prec_mat <- MCMCglmm::inverseA(tree_scaled, + nodes = "ALL", + scale = FALSE)$Ainv + +metrics_joined = metrics_joined[order(match(metrics_joined$Language_ID, rownames(phylo_prec_mat))),] + +#"local" set of parameters +## Create spatial covariance matrix using the matern covariance function +spatial_covar_mat_1 = varcov.spatial(metrics_joined[,c("Longitude", "Latitude")], + cov.pars = phi_1, kappa = kappa)$varcov +# Calculate and standardize by the typical variance +typical_variance_spatial_1 = exp(mean(log(diag(spatial_covar_mat_1)))) +spatial_cov_std_1 = spatial_covar_mat_1 / typical_variance_spatial_1 +spatial_prec_mat_1 = solve(spatial_cov_std_1) +dimnames(spatial_prec_mat_1) = list(metrics_joined$Language_ID, metrics_joined$Language_ID) + +## Since we are using a sparse phylogenetic matrix, we are matching taxa to rows in the matrix +phy_id = match(tree$tip.label, rownames(phylo_prec_mat)) +metrics_joined$phy_id = phy_id + +## Other effects are in the same order they appear in the dataset +metrics_joined$sp_id = 1:nrow(spatial_prec_mat_1) + +pcprior_hyper_0.99 = list(prec =list(prior="pc.prec", param = c(1, 0.99))) + +#Preparing the formulas for 10 competing models to be used in inla() call +listcombo <- list( + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.99)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.99)", "L1_log_st"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.99)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.99)", "f(inla.group(L1_copy), model='rw2', scale.model = TRUE)"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.99)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.99)", "L2_prop"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.99)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.99)", "f(inla.group(L2_copy), model='rw2', scale.model = TRUE)"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.99)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.99)", "f(inla.group(L1_copy), model='rw2', scale.model = TRUE)", "f(inla.group(L2_copy), model='rw2', scale.model = TRUE)"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.99)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.99)", "L1_log_st", "L2_prop"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.99)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.99)", "L1_log10:L2_prop"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.99)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.99)", "neighboring_languages_st"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.99)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.99)", "Official"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.99)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.99)", "Education")) + + +predterms <- lapply(listcombo, function(x) paste(x, collapse="+")) + +predterms <- t(as.data.frame(predterms)) + +predterms_short <- predterms + +predterms_short <- gsub("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.99)", "Phylogenetic", predterms_short, fixed=TRUE) +predterms_short <- gsub("f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.99)", "Spatial: local", predterms_short, fixed=TRUE) + +predterms_short <- gsub("f(inla.group(L1_copy), model='rw2', scale.model = TRUE)", "L1 speakers (nonlinear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("L1_log_st", "L1 speakers (linear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("f(inla.group(L2_copy), model='rw2', scale.model = TRUE)", "L2 proportion (nonlinear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("L2_prop", "L2 proportion (linear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("neighboring_languages_st", "Neighbours", predterms_short, fixed=TRUE) + + + +phylogenetic_element <- data.frame("judgement" = grepl("Phylogenetic", predterms_short), + number = 1:length(predterms_short)) +phylogenetic_element <- phylogenetic_element[phylogenetic_element$judgement == TRUE,]$number + +spatial_element_local <- data.frame("judgement" = grepl("local", predterms_short), + number = 1:length(predterms_short)) +spatial_element_local <- spatial_element_local[spatial_element_local$judgement == TRUE,]$number + +spatial_element_regional <- data.frame("judgement" = grepl("regional", predterms_short), + number = 1:length(predterms_short)) +spatial_element_regional <- spatial_element_regional[spatial_element_regional$judgement == TRUE,]$number + +spatial_element <- c(spatial_element_local, spatial_element_regional) + +L1_element <- data.frame("judgement" = grepl("L1 speakers (linear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L1_element <- L1_element[L1_element$judgement == TRUE,]$number + + +L1_nl_element <- data.frame("judgement" = grepl("L1 speakers (nonlinear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L1_nl_element <- L1_nl_element[L1_nl_element$judgement == TRUE,]$number + +L2_prop_element <- data.frame("judgement" = grepl("L2 proportion (linear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L2_prop_element <- L2_prop_element[L2_prop_element$judgement == TRUE,]$number +L2_prop_element <- L2_prop_element[-length(L2_prop_element)] #making sure that the interaction term (introduced below) is not treated as belonging to this isolated element + +L2_prop_nl_element <- data.frame("judgement" = grepl("L2 proportion (nonlinear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L2_prop_nl_element <- L2_prop_nl_element[L2_prop_nl_element$judgement == TRUE,]$number + +#can use only part of the interaction term within grepl() function +interaction_element <- data.frame("judgement" = grepl(":L2 proportion", predterms_short), + number = 1:length(predterms_short)) +interaction_element <- interaction_element[interaction_element$judgement == TRUE,]$number + +neighbour_element <- data.frame("judgement" = grepl("Neighbours", predterms_short), + number = 1:length(predterms_short)) +neighbour_element <- neighbour_element[neighbour_element$judgement == TRUE,]$number + +official_element <- data.frame("judgement" = grepl("Official", predterms_short), + number = 1:length(predterms_short)) +official_element <- official_element[official_element$judgement == TRUE,]$number + +education_element <- data.frame("judgement" = grepl("Education", predterms_short), + number = 1:length(predterms_short)) +education_element <- education_element[education_element$judgement == TRUE,]$number + + + +#preparing empty matrices to be filled with effect estimates (quantiles), model name, and WAIC value +phy_effects_matrix <- matrix(NA, 10, 5) +colnames(phy_effects_matrix) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +spa_effects_matrix <- matrix(NA, 10, 5) +colnames(spa_effects_matrix) <- c("2.5%", "50%", "97.5%", "model", "WAIC") + +intercept_matrix <- matrix(NA, 10, 5) +colnames(intercept_matrix) <- c("2.5%", "50%", "97.5%", "model", "WAIC") + +social_effects_matrix_L1 <- matrix(NA, 10, 5) +colnames(social_effects_matrix_L1) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L1_nl <- matrix(NA, 10, 5) +colnames(social_effects_matrix_L1_nl) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L2_prop <- matrix(NA, 10, 5) +colnames(social_effects_matrix_L2_prop) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L2_prop_nl <- matrix(NA, 10, 5) +colnames(social_effects_matrix_L2_prop_nl) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_N <- matrix(NA, 10, 5) +colnames(social_effects_matrix_N) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_O <- matrix(NA, 10, 5) +colnames(social_effects_matrix_O) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_E <- matrix(NA, 10, 5) +colnames(social_effects_matrix_E) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L1_L2_prop <- matrix(NA, 10, 5) +colnames(social_effects_matrix_L1_L2_prop) <- c("2.5%", "50%", "97.5%", "model", "WAIC") + +#fitted values +fitted_list <- vector("list", 10) +names(fitted_list) <- predterms_short + +#marginals of hyperparameters +marginals_hyperpar_list_gaussian <- vector("list", 10) +names(marginals_hyperpar_list_gaussian) <- predterms_short + +marginals_hyperpar_list_phy <- vector("list", 10) +names(marginals_hyperpar_list_phy) <- predterms_short + +marginals_hyperpar_list_spa <- vector("list", 10) +names(marginals_hyperpar_list_spa) <- predterms_short + +marginals_hyperpar_list_social_L1_nl <- vector("list", 10) +names(marginals_hyperpar_list_social_L1_nl) <- predterms_short + +marginals_hyperpar_list_social_L2_prop_nl <- vector("list", 10) +names(marginals_hyperpar_list_social_L2_prop_nl) <- predterms_short + + +#marginals of fixed effects +marginals_fixed_list_Intercept <- vector("list", 10) +names(marginals_fixed_list_Intercept) <- predterms_short + +marginals_fixed_list_L1 <- vector("list", 10) +names(marginals_fixed_list_L1) <- predterms_short + +marginals_fixed_list_L2_prop <- vector("list", 10) +names(marginals_fixed_list_L2_prop) <- predterms_short + +marginals_fixed_list_O <- vector("list", 10) +names(marginals_fixed_list_O) <- predterms_short + +marginals_fixed_list_N <- vector("list", 10) +names(marginals_fixed_list_N) <- predterms_short + +marginals_fixed_list_E <- vector("list", 10) +names(marginals_fixed_list_E) <- predterms_short + +marginals_fixed_list_L1_L2_prop <- vector("list", 10) +names(marginals_fixed_list_L1_L2_prop) <- predterms_short + + + + +#summary statistics of random effects +summary_random_list_phy <- vector("list", 10) +names(summary_random_list_phy) <- predterms_short + +summary_random_list_spa <- vector("list", 10) +names(summary_random_list_spa) <- predterms_short + +summary_random_list_social_L1_nl <- vector("list", 10) +names(summary_random_list_social_L1_nl) <- predterms_short + +summary_random_list_social_L2_prop_nl <- vector("list", 10) +names(summary_random_list_social_L2_prop_nl) <- predterms_short + + +coefm <- matrix(NA,10,1) +result <- vector("list",10) + +for(i in 1:10){ + formula <- as.formula(paste("boundness_st ~ ",predterms[[i]])) + result[[i]] <- inla(formula, family="gaussian", + control.family = list(hyper = pcprior_hyper_0.99), + #control.inla = list(tolerance = 1e-8, h = 0.0001), + #tolerance: the tolerance for the optimisation of the hyperparameters + #h: the step-length for the gradient calculations for the hyperparameters. + data=metrics_joined, control.compute=list(waic=TRUE)) + + coefm[i,1] <- round(result[[i]]$waic$waic, 2) + + intercept_matrix[i, 1:3] <- c(result[[i]]$summary.fixed[1,]$`0.025quant`, result[[i]]$summary.fixed[1,]$`0.5quant`, result[[i]]$summary.fixed[1,]$`0.975quant`) + intercept_matrix[i, 4] <- predterms_short[[i]] + intercept_matrix[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_Intercept[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["(Intercept)"]])) + colnames(marginals_fixed_list_Intercept[[i]]) <- c("x for Intercept", "y for Intercept") + + if(i %in% phylogenetic_element) { + phy_effects_matrix[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for phy_id`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + phy_effects_matrix[i, 4] <- predterms_short[[i]] + phy_effects_matrix[i, 5] <- result[[i]]$waic$waic + } + + if(i %in% spatial_element) { + spa_effects_matrix[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for sp_id`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + spa_effects_matrix[i, 4] <- predterms_short[[i]] + spa_effects_matrix[i, 5] <- result[[i]]$waic$waic + } + + + if(i %in% L1_nl_element){ + social_effects_matrix_L1_nl[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for inla.group(L1_copy)`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + social_effects_matrix_L1_nl[i, 4] <- predterms_short[[i]] + social_effects_matrix_L1_nl[i, 5] <- result[[i]]$waic$waic + } + + if(i %in% L2_prop_nl_element){ + social_effects_matrix_L2_prop_nl[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for inla.group(L2_copy)`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + social_effects_matrix_L2_prop_nl[i, 4] <- predterms_short[[i]] + social_effects_matrix_L2_prop_nl[i, 5] <- result[[i]]$waic$waic + } + + if(i %in% L1_element) { + social_effects_matrix_L1[i, 1:3] <- c(result[[i]]$summary.fixed["L1_log_st",]$`0.025quant`, result[[i]]$summary.fixed["L1_log_st",]$`0.5quant`, result[[i]]$summary.fixed["L1_log_st",]$`0.975quant`) + social_effects_matrix_L1[i, 4] <- predterms_short[[i]] + social_effects_matrix_L1[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_L1[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["L1_log_st"]])) + colnames(marginals_fixed_list_L1[[i]]) <- c("x for L1", "y for L1") + } + + if(i %in% L2_prop_element) { + social_effects_matrix_L2_prop[i, 1:3] <- c(result[[i]]$summary.fixed["L2_prop",]$`0.025quant`, result[[i]]$summary.fixed["L2_prop",]$`0.5quant`, result[[i]]$summary.fixed["L2_prop",]$`0.975quant`) + social_effects_matrix_L2_prop[i, 4] <- predterms_short[[i]] + social_effects_matrix_L2_prop[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_L2_prop[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["L2_prop"]])) + colnames(marginals_fixed_list_L2_prop[[i]]) <- c("x for L2 proportion", "y for L2 proportion") + } + + if(i %in% interaction_element) { + social_effects_matrix_L1_L2_prop[i, 1:3] <- c(result[[i]]$summary.fixed["L1_log10:L2_prop",]$`0.025quant`, result[[i]]$summary.fixed["L1_log10:L2_prop",]$`0.5quant`, result[[i]]$summary.fixed["L1_log10:L2_prop",]$`0.975quant`) + social_effects_matrix_L1_L2_prop[i, 4] <- predterms_short[[i]] + social_effects_matrix_L1_L2_prop[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_L1_L2_prop[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["L1_log10:L2_prop"]])) + colnames(marginals_fixed_list_L1_L2_prop[[i]]) <- c("x for L1*L2 proportion", "y for L1*L2 proportion") + } + + if(i %in% neighbour_element) { + social_effects_matrix_N[i, 1:3] <- c(result[[i]]$summary.fixed[2,]$`0.025quant`, result[[i]]$summary.fixed[2,]$`0.5quant`, result[[i]]$summary.fixed[2,]$`0.975quant`) + social_effects_matrix_N[i, 4] <- predterms_short[[i]] + social_effects_matrix_N[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_N[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][[2]])) + colnames(marginals_fixed_list_N[[i]]) <- c("x for Neighbours", "y for Neighbours") + } + + if(i %in% official_element) { + social_effects_matrix_O[i, 1:3] <- c(result[[i]]$summary.fixed[2,]$`0.025quant`, result[[i]]$summary.fixed[2,]$`0.5quant`, result[[i]]$summary.fixed[2,]$`0.975quant`) + social_effects_matrix_O[i, 4] <- predterms_short[[i]] + social_effects_matrix_O[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_O[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][[2]])) + colnames(marginals_fixed_list_O[[i]]) <- c("x for Official", "y for Official") + } + + if(i %in% education_element) { + social_effects_matrix_E[i, 1:3] <- c(result[[i]]$summary.fixed[2,]$`0.025quant`, result[[i]]$summary.fixed[2,]$`0.5quant`, result[[i]]$summary.fixed[2,]$`0.975quant`) + social_effects_matrix_E[i, 4] <- predterms_short[[i]] + social_effects_matrix_E[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_E[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][[2]])) + colnames(marginals_fixed_list_E[[i]]) <- c("x for Education", "y for Education") + } + + fitted_list[[i]] <- result[[i]]$summary.fitted.values + fitted_list[[i]] <- fitted_list[[i]] %>% + mutate(across(where(is.numeric), round, 2)) + + marginals_hyperpar_list_gaussian[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for the Gaussian observations"]])) + colnames(marginals_hyperpar_list_gaussian[[i]]) <- c("x for the Gaussian observations", "y for the Gaussian observations") + + if(i %in% phylogenetic_element){ + marginals_hyperpar_list_phy[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for phy_id"]])) + colnames(marginals_hyperpar_list_phy[[i]]) <- c("x for phy_id", "y for phy_id") + } + + if(i %in% spatial_element){ + marginals_hyperpar_list_spa[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for sp_id"]])) + colnames(marginals_hyperpar_list_spa[[i]]) <- c("x for sp_id", "y for sp_id") + } + + if(i %in% L1_nl_element){ + marginals_hyperpar_list_social_L1_nl[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for inla.group(L1_copy)"]])) + colnames(marginals_hyperpar_list_social_L1_nl[[i]]) <- c("x for inla.group(L1_copy)", "y for inla.group(L1_copy)") + } + + if(i %in% L2_prop_nl_element){ + marginals_hyperpar_list_social_L2_prop_nl[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for inla.group(L2_copy)"]])) + colnames(marginals_hyperpar_list_social_L2_prop_nl[[i]]) <- c("x for inla.group(L2_copy)", "y for inla.group(L2_copy)") + } + + if(i %in% phylogenetic_element){ + summary_random_list_phy[[i]] <- cbind(result[[i]]$summary.random$phy_id) %>% + rename(phy_id = ID) %>% + as.data.frame() %>% + mutate(across(where(is.numeric), round, 2)) + } + + if(i %in% spatial_element){ + summary_random_list_spa[[i]] <- cbind(result[[i]]$summary.random$sp_id) %>% + rename(sp_id = ID) %>% + as.data.frame() %>% + mutate(across(where(is.numeric), round, 2)) + } +} + +#beepr::beep(5) + +save(result, file = "output_models/models_Boundness_social_0.99.RData") + + +coefm <- as.data.frame(cbind(predterms_short, coefm)) +colnames(coefm) <- c("model", "WAIC") +coefm <- coefm %>% + mutate(across(.cols=2, as.numeric)) %>% + mutate(across(where(is.numeric), round, 2)) %>% + arrange(WAIC) + +coefm$WAIC <- as.numeric(coefm$WAIC) +coefm <- coefm[order(coefm$WAIC),] + +coefm_path <- paste("output_tables/", "waics", "Boundness_social_models", "prior_0.99", ".csv", collapse = "") +write.csv(coefm, coefm_path, row.names=FALSE) + + +phy_effects<-as.data.frame(phy_effects_matrix) +spa_effects<-as.data.frame(spa_effects_matrix) +intercept_effects <- as.data.frame(intercept_matrix) +L1_effects <- as.data.frame(social_effects_matrix_L1) +L1_nl_effects <- as.data.frame(social_effects_matrix_L1_nl) +L2_prop_effects <- as.data.frame(social_effects_matrix_L2_prop) +L2_prop_nl_effects <- as.data.frame(social_effects_matrix_L2_prop_nl) +N_effects<-as.data.frame(social_effects_matrix_N) +E_effects<-as.data.frame(social_effects_matrix_E) +O_effects<-as.data.frame(social_effects_matrix_O) +interaction_effects <- as.data.frame(social_effects_matrix_L1_L2_prop) + +phy_effects$effect <- "phylogenetic SD" +spa_effects$effect <- "spatial SD" +intercept_effects$effect <- "Intercept" +L1_effects$effect <- "L1" +L1_nl_effects$effect <- "social SD:\nL1" +L2_prop_effects$effect <- "L2 proportion" +L2_prop_nl_effects$effect <- "social SD:\nL2 proportion" +N_effects$effect <- "Neighbours" +E_effects$effect <- "Education" +O_effects$effect <- "Official status" +interaction_effects$effect <- "L1*L2 proportion" + +effs <- as.data.frame(rbind(phy_effects, spa_effects, intercept_effects, L1_effects, L1_nl_effects, L2_prop_effects, L2_prop_nl_effects, N_effects, O_effects, E_effects, interaction_effects)) +effs <- effs %>% + mutate(across(.cols=c(1:3, 5), as.numeric)) %>% + mutate(across(where(is.numeric), round, 2)) %>% + na.omit() %>% + arrange(WAIC) %>% + relocate(model) + +effs_path <- paste("output_tables/", "effects", "Boundness_social_models", "prior_0.99", ".csv", collapse = "") +write.csv(effs, effs_path, row.names=FALSE) diff --git a/101/replication_package/sensitivity_testing_I_001.R b/101/replication_package/sensitivity_testing_I_001.R new file mode 100644 index 0000000000000000000000000000000000000000..4626a9359c8b846c0e8e29f6fd2e9b554e2c97f1 --- /dev/null +++ b/101/replication_package/sensitivity_testing_I_001.R @@ -0,0 +1,441 @@ +#model fitting: Informativity predicted by social effects on top of random phylogenetic and spatial factors + +source("requirements.R") + +source("install_and_load_INLA.R") + +source("set_up_inla.R") + +metrics_joined <- metrics_joined %>% + filter(!is.na(L1_log10_st)) %>% + rename(L1_log_st = L1_log10_st) %>% + mutate(L1_copy = L1_log_st) %>% + filter(!is.na(L2_prop)) %>% + mutate(L2_copy = L2_prop) %>% + filter(!is.na(neighboring_languages_st)) %>% + filter(!is.na(Official)) %>% + filter(!is.na(Education)) %>% + filter(!is.na(boundness_st)) %>% + filter(!is.na(informativity_st)) + +#dropping tips not in Grambank +metrics_joined <- metrics_joined[metrics_joined$Language_ID %in% tree$tip.label, ] +tree <- keep.tip(tree, metrics_joined$Language_ID) + +x <- assert_that(all(tree$tip.label %in% metrics_joined$Language_ID), msg = "The data and phylogeny taxa do not match") + +## Building standardized phylogenetic precision matrix +tree_scaled <- tree + +tree_vcv = vcv.phylo(tree_scaled) +typical_phylogenetic_variance = exp(mean(log(diag(tree_vcv)))) + +tree_scaled$edge.length <- tree_scaled$edge.length/typical_phylogenetic_variance +phylo_prec_mat <- MCMCglmm::inverseA(tree_scaled, + nodes = "ALL", + scale = FALSE)$Ainv + +metrics_joined = metrics_joined[order(match(metrics_joined$Language_ID, rownames(phylo_prec_mat))),] + +#"local" set of parameters +## Create spatial covariance matrix using the matern covariance function +spatial_covar_mat_1 = varcov.spatial(metrics_joined[,c("Longitude", "Latitude")], + cov.pars = phi_1, kappa = kappa)$varcov +# Calculate and standardize by the typical variance +typical_variance_spatial_1 = exp(mean(log(diag(spatial_covar_mat_1)))) +spatial_cov_std_1 = spatial_covar_mat_1 / typical_variance_spatial_1 +spatial_prec_mat_1 = solve(spatial_cov_std_1) +dimnames(spatial_prec_mat_1) = list(metrics_joined$Language_ID, metrics_joined$Language_ID) + +## Since we are using a sparse phylogenetic matrix, we are matching taxa to rows in the matrix +phy_id = match(tree$tip.label, rownames(phylo_prec_mat)) +metrics_joined$phy_id = phy_id + +## Other effects are in the same order they appear in the dataset +metrics_joined$sp_id = 1:nrow(spatial_prec_mat_1) + +pcprior_hyper_0.01 = list(prec =list(prior="pc.prec", param = c(1, 0.01))) + +#Preparing the formulas for 10 competing models to be used in inla() call +listcombo <- list( + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.01)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.01)", "L1_log_st"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.01)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.01)", "f(inla.group(L1_copy), model='rw2', scale.model = TRUE)"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.01)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.01)", "L2_prop"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.01)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.01)", "f(inla.group(L2_copy), model='rw2', scale.model = TRUE)"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.01)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.01)", "f(inla.group(L1_copy), model='rw2', scale.model = TRUE)", "f(inla.group(L2_copy), model='rw2', scale.model = TRUE)"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.01)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.01)", "L1_log_st", "L2_prop"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.01)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.01)", "L1_log10:L2_prop"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.01)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.01)", "neighboring_languages_st"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.01)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.01)", "Official"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.01)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.01)", "Education")) + + +predterms <- lapply(listcombo, function(x) paste(x, collapse="+")) + +predterms <- t(as.data.frame(predterms)) + +predterms_short <- predterms +predterms_short <- gsub("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.01)", "Phylogenetic", predterms_short, fixed=TRUE) +predterms_short <- gsub("f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.01)", "Spatial: local", predterms_short, fixed=TRUE) + +predterms_short <- gsub("f(inla.group(L1_copy), model='rw2', scale.model = TRUE)", "L1 speakers (nonlinear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("L1_log_st", "L1 speakers (linear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("f(inla.group(L2_copy), model='rw2', scale.model = TRUE)", "L2 proportion (nonlinear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("L2_prop", "L2 proportion (linear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("neighboring_languages_st", "Neighbours", predterms_short, fixed=TRUE) + + +phylogenetic_element <- data.frame("judgement" = grepl("Phylogenetic", predterms_short), + number = 1:length(predterms_short)) +phylogenetic_element <- phylogenetic_element[phylogenetic_element$judgement == TRUE,]$number + +spatial_element_local <- data.frame("judgement" = grepl("local", predterms_short), + number = 1:length(predterms_short)) +spatial_element_local <- spatial_element_local[spatial_element_local$judgement == TRUE,]$number + +spatial_element_regional <- data.frame("judgement" = grepl("regional", predterms_short), + number = 1:length(predterms_short)) +spatial_element_regional <- spatial_element_regional[spatial_element_regional$judgement == TRUE,]$number + +spatial_element <- c(spatial_element_local, spatial_element_regional) + +L1_element <- data.frame("judgement" = grepl("L1 speakers (linear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L1_element <- L1_element[L1_element$judgement == TRUE,]$number + + +L1_nl_element <- data.frame("judgement" = grepl("L1 speakers (nonlinear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L1_nl_element <- L1_nl_element[L1_nl_element$judgement == TRUE,]$number + +L2_prop_element <- data.frame("judgement" = grepl("L2 proportion (linear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L2_prop_element <- L2_prop_element[L2_prop_element$judgement == TRUE,]$number +L2_prop_element <- L2_prop_element[-length(L2_prop_element)] #making sure that the interaction term (introduced below) is not treated as belonging to this isolated element + +L2_prop_nl_element <- data.frame("judgement" = grepl("L2 proportion (nonlinear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L2_prop_nl_element <- L2_prop_nl_element[L2_prop_nl_element$judgement == TRUE,]$number + +#can use only part of the interaction term within grepl() function +interaction_element <- data.frame("judgement" = grepl(":L2 proportion", predterms_short), + number = 1:length(predterms_short)) +interaction_element <- interaction_element[interaction_element$judgement == TRUE,]$number + +neighbour_element <- data.frame("judgement" = grepl("Neighbours", predterms_short), + number = 1:length(predterms_short)) +neighbour_element <- neighbour_element[neighbour_element$judgement == TRUE,]$number + +official_element <- data.frame("judgement" = grepl("Official", predterms_short), + number = 1:length(predterms_short)) +official_element <- official_element[official_element$judgement == TRUE,]$number + +education_element <- data.frame("judgement" = grepl("Education", predterms_short), + number = 1:length(predterms_short)) +education_element <- education_element[education_element$judgement == TRUE,]$number + + + +#preparing empty matrices to be filled with effect estimates (quantiles), model name, and WAIC value +phy_effects_matrix <- matrix(NA, 10, 5) +colnames(phy_effects_matrix) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +spa_effects_matrix <- matrix(NA, 10, 5) +colnames(spa_effects_matrix) <- c("2.5%", "50%", "97.5%", "model", "WAIC") + +intercept_matrix <- matrix(NA, 10, 5) +colnames(intercept_matrix) <- c("2.5%", "50%", "97.5%", "model", "WAIC") + +social_effects_matrix_L1 <- matrix(NA, 10, 5) +colnames(social_effects_matrix_L1) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L1_nl <- matrix(NA, 10, 5) +colnames(social_effects_matrix_L1_nl) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L2_prop <- matrix(NA, 10, 5) +colnames(social_effects_matrix_L2_prop) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L2_prop_nl <- matrix(NA, 10, 5) +colnames(social_effects_matrix_L2_prop_nl) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_N <- matrix(NA, 10, 5) +colnames(social_effects_matrix_N) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_O <- matrix(NA, 10, 5) +colnames(social_effects_matrix_O) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_E <- matrix(NA, 10, 5) +colnames(social_effects_matrix_E) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L1_L2_prop <- matrix(NA, 10, 5) +colnames(social_effects_matrix_L1_L2_prop) <- c("2.5%", "50%", "97.5%", "model", "WAIC") + +#fitted values +fitted_list <- vector("list", 10) +names(fitted_list) <- predterms_short + +#marginals of hyperparameters +marginals_hyperpar_list_gaussian <- vector("list", 10) +names(marginals_hyperpar_list_gaussian) <- predterms_short + +marginals_hyperpar_list_phy <- vector("list", 10) +names(marginals_hyperpar_list_phy) <- predterms_short + +marginals_hyperpar_list_spa <- vector("list", 10) +names(marginals_hyperpar_list_spa) <- predterms_short + +marginals_hyperpar_list_social_L1_nl <- vector("list", 10) +names(marginals_hyperpar_list_social_L1_nl) <- predterms_short + +marginals_hyperpar_list_social_L2_prop_nl <- vector("list", 10) +names(marginals_hyperpar_list_social_L2_prop_nl) <- predterms_short + + +#marginals of fixed effects +marginals_fixed_list_Intercept <- vector("list", 10) +names(marginals_fixed_list_Intercept) <- predterms_short + +marginals_fixed_list_L1 <- vector("list", 10) +names(marginals_fixed_list_L1) <- predterms_short + +marginals_fixed_list_L2_prop <- vector("list", 10) +names(marginals_fixed_list_L2_prop) <- predterms_short + +marginals_fixed_list_O <- vector("list", 10) +names(marginals_fixed_list_O) <- predterms_short + +marginals_fixed_list_N <- vector("list", 10) +names(marginals_fixed_list_N) <- predterms_short + +marginals_fixed_list_E <- vector("list", 10) +names(marginals_fixed_list_E) <- predterms_short + +marginals_fixed_list_L1_L2_prop <- vector("list", 10) +names(marginals_fixed_list_L1_L2_prop) <- predterms_short + + + + +#summary statistics of random effects +summary_random_list_phy <- vector("list", 10) +names(summary_random_list_phy) <- predterms_short + +summary_random_list_spa <- vector("list", 10) +names(summary_random_list_spa) <- predterms_short + +summary_random_list_social_L1_nl <- vector("list", 10) +names(summary_random_list_social_L1_nl) <- predterms_short + +summary_random_list_social_L2_prop_nl <- vector("list", 10) +names(summary_random_list_social_L2_prop_nl) <- predterms_short + + +coefm <- matrix(NA,10,1) +result <- vector("list",10) + +for(i in 1:10){ + formula <- as.formula(paste("informativity_st ~ ",predterms[[i]])) + result[[i]] <- inla(formula, family="gaussian", + control.family = list(hyper = pcprior_hyper_0.01), + #control.inla = list(tolerance = 1e-8, h = 0.0001), + #tolerance: the tolerance for the optimisation of the hyperparameters + #h: the step-length for the gradient calculations for the hyperparameters. + data=metrics_joined, control.compute=list(waic=TRUE)) + + coefm[i,1] <- round(result[[i]]$waic$waic, 2) + + intercept_matrix[i, 1:3] <- c(result[[i]]$summary.fixed[1,]$`0.025quant`, result[[i]]$summary.fixed[1,]$`0.5quant`, result[[i]]$summary.fixed[1,]$`0.975quant`) + intercept_matrix[i, 4] <- predterms_short[[i]] + intercept_matrix[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_Intercept[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["(Intercept)"]])) + colnames(marginals_fixed_list_Intercept[[i]]) <- c("x for Intercept", "y for Intercept") + + if(i %in% phylogenetic_element) { + phy_effects_matrix[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for phy_id`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + phy_effects_matrix[i, 4] <- predterms_short[[i]] + phy_effects_matrix[i, 5] <- result[[i]]$waic$waic + } + + if(i %in% spatial_element) { + spa_effects_matrix[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for sp_id`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + spa_effects_matrix[i, 4] <- predterms_short[[i]] + spa_effects_matrix[i, 5] <- result[[i]]$waic$waic + } + + + if(i %in% L1_nl_element){ + social_effects_matrix_L1_nl[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for inla.group(L1_copy)`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + social_effects_matrix_L1_nl[i, 4] <- predterms_short[[i]] + social_effects_matrix_L1_nl[i, 5] <- result[[i]]$waic$waic + } + + if(i %in% L2_prop_nl_element){ + social_effects_matrix_L2_prop_nl[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for inla.group(L2_copy)`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + social_effects_matrix_L2_prop_nl[i, 4] <- predterms_short[[i]] + social_effects_matrix_L2_prop_nl[i, 5] <- result[[i]]$waic$waic + } + + if(i %in% L1_element) { + social_effects_matrix_L1[i, 1:3] <- c(result[[i]]$summary.fixed["L1_log_st",]$`0.025quant`, result[[i]]$summary.fixed["L1_log_st",]$`0.5quant`, result[[i]]$summary.fixed["L1_log_st",]$`0.975quant`) + social_effects_matrix_L1[i, 4] <- predterms_short[[i]] + social_effects_matrix_L1[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_L1[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["L1_log_st"]])) + colnames(marginals_fixed_list_L1[[i]]) <- c("x for L1", "y for L1") + } + + if(i %in% L2_prop_element) { + social_effects_matrix_L2_prop[i, 1:3] <- c(result[[i]]$summary.fixed["L2_prop",]$`0.025quant`, result[[i]]$summary.fixed["L2_prop",]$`0.5quant`, result[[i]]$summary.fixed["L2_prop",]$`0.975quant`) + social_effects_matrix_L2_prop[i, 4] <- predterms_short[[i]] + social_effects_matrix_L2_prop[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_L2_prop[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["L2_prop"]])) + colnames(marginals_fixed_list_L2_prop[[i]]) <- c("x for L2 proportion", "y for L2 proportion") + } + + if(i %in% interaction_element) { + social_effects_matrix_L1_L2_prop[i, 1:3] <- c(result[[i]]$summary.fixed["L1_log10:L2_prop",]$`0.025quant`, result[[i]]$summary.fixed["L1_log10:L2_prop",]$`0.5quant`, result[[i]]$summary.fixed["L1_log10:L2_prop",]$`0.975quant`) + social_effects_matrix_L1_L2_prop[i, 4] <- predterms_short[[i]] + social_effects_matrix_L1_L2_prop[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_L1_L2_prop[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["L1_log10:L2_prop"]])) + colnames(marginals_fixed_list_L1_L2_prop[[i]]) <- c("x for L1*L2 proportion", "y for L1*L2 proportion") + } + + if(i %in% neighbour_element) { + social_effects_matrix_N[i, 1:3] <- c(result[[i]]$summary.fixed[2,]$`0.025quant`, result[[i]]$summary.fixed[2,]$`0.5quant`, result[[i]]$summary.fixed[2,]$`0.975quant`) + social_effects_matrix_N[i, 4] <- predterms_short[[i]] + social_effects_matrix_N[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_N[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][[2]])) + colnames(marginals_fixed_list_N[[i]]) <- c("x for Neighbours", "y for Neighbours") + } + + if(i %in% official_element) { + social_effects_matrix_O[i, 1:3] <- c(result[[i]]$summary.fixed[2,]$`0.025quant`, result[[i]]$summary.fixed[2,]$`0.5quant`, result[[i]]$summary.fixed[2,]$`0.975quant`) + social_effects_matrix_O[i, 4] <- predterms_short[[i]] + social_effects_matrix_O[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_O[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][[2]])) + colnames(marginals_fixed_list_O[[i]]) <- c("x for Official", "y for Official") + } + + if(i %in% education_element) { + social_effects_matrix_E[i, 1:3] <- c(result[[i]]$summary.fixed[2,]$`0.025quant`, result[[i]]$summary.fixed[2,]$`0.5quant`, result[[i]]$summary.fixed[2,]$`0.975quant`) + social_effects_matrix_E[i, 4] <- predterms_short[[i]] + social_effects_matrix_E[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_E[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][[2]])) + colnames(marginals_fixed_list_E[[i]]) <- c("x for Education", "y for Education") + } + + fitted_list[[i]] <- result[[i]]$summary.fitted.values + fitted_list[[i]] <- fitted_list[[i]] %>% + mutate(across(where(is.numeric), round, 2)) + + marginals_hyperpar_list_gaussian[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for the Gaussian observations"]])) + colnames(marginals_hyperpar_list_gaussian[[i]]) <- c("x for the Gaussian observations", "y for the Gaussian observations") + + if(i %in% phylogenetic_element){ + marginals_hyperpar_list_phy[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for phy_id"]])) + colnames(marginals_hyperpar_list_phy[[i]]) <- c("x for phy_id", "y for phy_id") + } + + if(i %in% spatial_element){ + marginals_hyperpar_list_spa[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for sp_id"]])) + colnames(marginals_hyperpar_list_spa[[i]]) <- c("x for sp_id", "y for sp_id") + } + + if(i %in% L1_nl_element){ + marginals_hyperpar_list_social_L1_nl[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for inla.group(L1_copy)"]])) + colnames(marginals_hyperpar_list_social_L1_nl[[i]]) <- c("x for inla.group(L1_copy)", "y for inla.group(L1_copy)") + } + + if(i %in% L2_prop_nl_element){ + marginals_hyperpar_list_social_L2_prop_nl[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for inla.group(L2_copy)"]])) + colnames(marginals_hyperpar_list_social_L2_prop_nl[[i]]) <- c("x for inla.group(L2_copy)", "y for inla.group(L2_copy)") + } + + if(i %in% phylogenetic_element){ + summary_random_list_phy[[i]] <- cbind(result[[i]]$summary.random$phy_id) %>% + rename(phy_id = ID) %>% + as.data.frame() %>% + mutate(across(where(is.numeric), round, 2)) + } + + if(i %in% spatial_element){ + summary_random_list_spa[[i]] <- cbind(result[[i]]$summary.random$sp_id) %>% + rename(sp_id = ID) %>% + as.data.frame() %>% + mutate(across(where(is.numeric), round, 2)) + } +} + +#beepr::beep(5) + +save(result, file = "output_models/models_Informativity_social_0.01.RData") + + +coefm <- as.data.frame(cbind(predterms_short, coefm)) +colnames(coefm) <- c("model", "WAIC") +coefm <- coefm %>% + mutate(across(.cols=2, as.numeric)) %>% + mutate(across(where(is.numeric), round, 2)) %>% + arrange(WAIC) + +coefm$WAIC <- as.numeric(coefm$WAIC) +coefm <- coefm[order(coefm$WAIC),] + +coefm_path <- paste("output_tables/", "waics", "Informativity_social_models", "prior_0.01", ".csv", collapse = "") +write.csv(coefm, coefm_path, row.names=FALSE) + + +phy_effects<-as.data.frame(phy_effects_matrix) +spa_effects<-as.data.frame(spa_effects_matrix) +intercept_effects <- as.data.frame(intercept_matrix) +L1_effects <- as.data.frame(social_effects_matrix_L1) +L1_nl_effects <- as.data.frame(social_effects_matrix_L1_nl) +L2_prop_effects <- as.data.frame(social_effects_matrix_L2_prop) +L2_prop_nl_effects <- as.data.frame(social_effects_matrix_L2_prop_nl) +N_effects<-as.data.frame(social_effects_matrix_N) +E_effects<-as.data.frame(social_effects_matrix_E) +O_effects<-as.data.frame(social_effects_matrix_O) +interaction_effects <- as.data.frame(social_effects_matrix_L1_L2_prop) + +phy_effects$effect <- "phylogenetic SD" +spa_effects$effect <- "spatial SD" +intercept_effects$effect <- "Intercept" +L1_effects$effect <- "L1" +L1_nl_effects$effect <- "social SD:\nL1" +L2_prop_effects$effect <- "L2 proportion" +L2_prop_nl_effects$effect <- "social SD:\nL2 proportion" +N_effects$effect <- "Neighbours" +E_effects$effect <- "Education" +O_effects$effect <- "Official status" +interaction_effects$effect <- "L1*L2 proportion" + +effs <- as.data.frame(rbind(phy_effects, spa_effects, intercept_effects, L1_effects, L1_nl_effects, L2_prop_effects, L2_prop_nl_effects, N_effects, O_effects, E_effects, interaction_effects)) +effs <- effs %>% + mutate(across(.cols=c(1:3, 5), as.numeric)) %>% + mutate(across(where(is.numeric), round, 2)) %>% + na.omit() %>% + arrange(WAIC) %>% + relocate(model) + +effs_path <- paste("output_tables/", "effects", "Informativity_social_models", "prior_0.01", ".csv", collapse = "") +write.csv(effs, effs_path, row.names=FALSE) + diff --git a/101/replication_package/sensitivity_testing_I_05.R b/101/replication_package/sensitivity_testing_I_05.R new file mode 100644 index 0000000000000000000000000000000000000000..20f4439043af277ee7656696d8f58be7da415c81 --- /dev/null +++ b/101/replication_package/sensitivity_testing_I_05.R @@ -0,0 +1,441 @@ +#model fitting: Informativity predicted by social effects on top of random phylogenetic and spatial factors + +source("requirements.R") + +source("install_and_load_INLA.R") + +source("set_up_inla.R") + +metrics_joined <- metrics_joined %>% + filter(!is.na(L1_log10_st)) %>% + rename(L1_log_st = L1_log10_st) %>% + mutate(L1_copy = L1_log_st) %>% + filter(!is.na(L2_prop)) %>% + mutate(L2_copy = L2_prop) %>% + filter(!is.na(neighboring_languages_st)) %>% + filter(!is.na(Official)) %>% + filter(!is.na(Education)) %>% + filter(!is.na(boundness_st)) %>% + filter(!is.na(informativity_st)) + +#dropping tips not in Grambank +metrics_joined <- metrics_joined[metrics_joined$Language_ID %in% tree$tip.label, ] +tree <- keep.tip(tree, metrics_joined$Language_ID) + +x <- assert_that(all(tree$tip.label %in% metrics_joined$Language_ID), msg = "The data and phylogeny taxa do not match") + +## Building standardized phylogenetic precision matrix +tree_scaled <- tree + +tree_vcv = vcv.phylo(tree_scaled) +typical_phylogenetic_variance = exp(mean(log(diag(tree_vcv)))) + +tree_scaled$edge.length <- tree_scaled$edge.length/typical_phylogenetic_variance +phylo_prec_mat <- MCMCglmm::inverseA(tree_scaled, + nodes = "ALL", + scale = FALSE)$Ainv + +metrics_joined = metrics_joined[order(match(metrics_joined$Language_ID, rownames(phylo_prec_mat))),] + +#"local" set of parameters +## Create spatial covariance matrix using the matern covariance function +spatial_covar_mat_1 = varcov.spatial(metrics_joined[,c("Longitude", "Latitude")], + cov.pars = phi_1, kappa = kappa)$varcov +# Calculate and standardize by the typical variance +typical_variance_spatial_1 = exp(mean(log(diag(spatial_covar_mat_1)))) +spatial_cov_std_1 = spatial_covar_mat_1 / typical_variance_spatial_1 +spatial_prec_mat_1 = solve(spatial_cov_std_1) +dimnames(spatial_prec_mat_1) = list(metrics_joined$Language_ID, metrics_joined$Language_ID) + +## Since we are using a sparse phylogenetic matrix, we are matching taxa to rows in the matrix +phy_id = match(tree$tip.label, rownames(phylo_prec_mat)) +metrics_joined$phy_id = phy_id + +## Other effects are in the same order they appear in the dataset +metrics_joined$sp_id = 1:nrow(spatial_prec_mat_1) + +pcprior_hyper_0.5 = list(prec =list(prior="pc.prec", param = c(1, 0.5))) + +#Preparing the formulas for 10 competing models to be used in inla() call +listcombo <- list( + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.5)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.5)", "L1_log_st"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.5)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.5)", "f(inla.group(L1_copy), model='rw2', scale.model = TRUE)"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.5)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.5)", "L2_prop"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.5)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.5)", "f(inla.group(L2_copy), model='rw2', scale.model = TRUE)"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.5)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.5)", "f(inla.group(L1_copy), model='rw2', scale.model = TRUE)", "f(inla.group(L2_copy), model='rw2', scale.model = TRUE)"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.5)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.5)", "L1_log_st", "L2_prop"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.5)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.5)", "L1_log10:L2_prop"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.5)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.5)", "neighboring_languages_st"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.5)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.5)", "Official"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.5)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.5)", "Education")) + + +predterms <- lapply(listcombo, function(x) paste(x, collapse="+")) + +predterms <- t(as.data.frame(predterms)) + +predterms_short <- predterms +predterms_short <- gsub("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.5)", "Phylogenetic", predterms_short, fixed=TRUE) +predterms_short <- gsub("f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.5)", "Spatial: local", predterms_short, fixed=TRUE) + +predterms_short <- gsub("f(inla.group(L1_copy), model='rw2', scale.model = TRUE)", "L1 speakers (nonlinear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("L1_log_st", "L1 speakers (linear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("f(inla.group(L2_copy), model='rw2', scale.model = TRUE)", "L2 proportion (nonlinear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("L2_prop", "L2 proportion (linear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("neighboring_languages_st", "Neighbours", predterms_short, fixed=TRUE) + + +phylogenetic_element <- data.frame("judgement" = grepl("Phylogenetic", predterms_short), + number = 1:length(predterms_short)) +phylogenetic_element <- phylogenetic_element[phylogenetic_element$judgement == TRUE,]$number + +spatial_element_local <- data.frame("judgement" = grepl("local", predterms_short), + number = 1:length(predterms_short)) +spatial_element_local <- spatial_element_local[spatial_element_local$judgement == TRUE,]$number + +spatial_element_regional <- data.frame("judgement" = grepl("regional", predterms_short), + number = 1:length(predterms_short)) +spatial_element_regional <- spatial_element_regional[spatial_element_regional$judgement == TRUE,]$number + +spatial_element <- c(spatial_element_local, spatial_element_regional) + +L1_element <- data.frame("judgement" = grepl("L1 speakers (linear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L1_element <- L1_element[L1_element$judgement == TRUE,]$number + + +L1_nl_element <- data.frame("judgement" = grepl("L1 speakers (nonlinear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L1_nl_element <- L1_nl_element[L1_nl_element$judgement == TRUE,]$number + +L2_prop_element <- data.frame("judgement" = grepl("L2 proportion (linear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L2_prop_element <- L2_prop_element[L2_prop_element$judgement == TRUE,]$number +L2_prop_element <- L2_prop_element[-length(L2_prop_element)] #making sure that the interaction term (introduced below) is not treated as belonging to this isolated element + +L2_prop_nl_element <- data.frame("judgement" = grepl("L2 proportion (nonlinear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L2_prop_nl_element <- L2_prop_nl_element[L2_prop_nl_element$judgement == TRUE,]$number + +#can use only part of the interaction term within grepl() function +interaction_element <- data.frame("judgement" = grepl(":L2 proportion", predterms_short), + number = 1:length(predterms_short)) +interaction_element <- interaction_element[interaction_element$judgement == TRUE,]$number + +neighbour_element <- data.frame("judgement" = grepl("Neighbours", predterms_short), + number = 1:length(predterms_short)) +neighbour_element <- neighbour_element[neighbour_element$judgement == TRUE,]$number + +official_element <- data.frame("judgement" = grepl("Official", predterms_short), + number = 1:length(predterms_short)) +official_element <- official_element[official_element$judgement == TRUE,]$number + +education_element <- data.frame("judgement" = grepl("Education", predterms_short), + number = 1:length(predterms_short)) +education_element <- education_element[education_element$judgement == TRUE,]$number + + + +#preparing empty matrices to be filled with effect estimates (quantiles), model name, and WAIC value +phy_effects_matrix <- matrix(NA, 10, 5) +colnames(phy_effects_matrix) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +spa_effects_matrix <- matrix(NA, 10, 5) +colnames(spa_effects_matrix) <- c("2.5%", "50%", "97.5%", "model", "WAIC") + +intercept_matrix <- matrix(NA, 10, 5) +colnames(intercept_matrix) <- c("2.5%", "50%", "97.5%", "model", "WAIC") + +social_effects_matrix_L1 <- matrix(NA, 10, 5) +colnames(social_effects_matrix_L1) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L1_nl <- matrix(NA, 10, 5) +colnames(social_effects_matrix_L1_nl) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L2_prop <- matrix(NA, 10, 5) +colnames(social_effects_matrix_L2_prop) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L2_prop_nl <- matrix(NA, 10, 5) +colnames(social_effects_matrix_L2_prop_nl) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_N <- matrix(NA, 10, 5) +colnames(social_effects_matrix_N) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_O <- matrix(NA, 10, 5) +colnames(social_effects_matrix_O) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_E <- matrix(NA, 10, 5) +colnames(social_effects_matrix_E) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L1_L2_prop <- matrix(NA, 10, 5) +colnames(social_effects_matrix_L1_L2_prop) <- c("2.5%", "50%", "97.5%", "model", "WAIC") + +#fitted values +fitted_list <- vector("list", 10) +names(fitted_list) <- predterms_short + +#marginals of hyperparameters +marginals_hyperpar_list_gaussian <- vector("list", 10) +names(marginals_hyperpar_list_gaussian) <- predterms_short + +marginals_hyperpar_list_phy <- vector("list", 10) +names(marginals_hyperpar_list_phy) <- predterms_short + +marginals_hyperpar_list_spa <- vector("list", 10) +names(marginals_hyperpar_list_spa) <- predterms_short + +marginals_hyperpar_list_social_L1_nl <- vector("list", 10) +names(marginals_hyperpar_list_social_L1_nl) <- predterms_short + +marginals_hyperpar_list_social_L2_prop_nl <- vector("list", 10) +names(marginals_hyperpar_list_social_L2_prop_nl) <- predterms_short + + +#marginals of fixed effects +marginals_fixed_list_Intercept <- vector("list", 10) +names(marginals_fixed_list_Intercept) <- predterms_short + +marginals_fixed_list_L1 <- vector("list", 10) +names(marginals_fixed_list_L1) <- predterms_short + +marginals_fixed_list_L2_prop <- vector("list", 10) +names(marginals_fixed_list_L2_prop) <- predterms_short + +marginals_fixed_list_O <- vector("list", 10) +names(marginals_fixed_list_O) <- predterms_short + +marginals_fixed_list_N <- vector("list", 10) +names(marginals_fixed_list_N) <- predterms_short + +marginals_fixed_list_E <- vector("list", 10) +names(marginals_fixed_list_E) <- predterms_short + +marginals_fixed_list_L1_L2_prop <- vector("list", 10) +names(marginals_fixed_list_L1_L2_prop) <- predterms_short + + + + +#summary statistics of random effects +summary_random_list_phy <- vector("list", 10) +names(summary_random_list_phy) <- predterms_short + +summary_random_list_spa <- vector("list", 10) +names(summary_random_list_spa) <- predterms_short + +summary_random_list_social_L1_nl <- vector("list", 10) +names(summary_random_list_social_L1_nl) <- predterms_short + +summary_random_list_social_L2_prop_nl <- vector("list", 10) +names(summary_random_list_social_L2_prop_nl) <- predterms_short + + +coefm <- matrix(NA,10,1) +result <- vector("list",10) + +for(i in 1:10){ + formula <- as.formula(paste("informativity_st ~ ",predterms[[i]])) + result[[i]] <- inla(formula, family="gaussian", + control.family = list(hyper = pcprior_hyper_0.5), + #control.inla = list(tolerance = 1e-8, h = 0.0001), + #tolerance: the tolerance for the optimisation of the hyperparameters + #h: the step-length for the gradient calculations for the hyperparameters. + data=metrics_joined, control.compute=list(waic=TRUE)) + + coefm[i,1] <- round(result[[i]]$waic$waic, 2) + + intercept_matrix[i, 1:3] <- c(result[[i]]$summary.fixed[1,]$`0.025quant`, result[[i]]$summary.fixed[1,]$`0.5quant`, result[[i]]$summary.fixed[1,]$`0.975quant`) + intercept_matrix[i, 4] <- predterms_short[[i]] + intercept_matrix[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_Intercept[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["(Intercept)"]])) + colnames(marginals_fixed_list_Intercept[[i]]) <- c("x for Intercept", "y for Intercept") + + if(i %in% phylogenetic_element) { + phy_effects_matrix[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for phy_id`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + phy_effects_matrix[i, 4] <- predterms_short[[i]] + phy_effects_matrix[i, 5] <- result[[i]]$waic$waic + } + + if(i %in% spatial_element) { + spa_effects_matrix[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for sp_id`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + spa_effects_matrix[i, 4] <- predterms_short[[i]] + spa_effects_matrix[i, 5] <- result[[i]]$waic$waic + } + + + if(i %in% L1_nl_element){ + social_effects_matrix_L1_nl[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for inla.group(L1_copy)`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + social_effects_matrix_L1_nl[i, 4] <- predterms_short[[i]] + social_effects_matrix_L1_nl[i, 5] <- result[[i]]$waic$waic + } + + if(i %in% L2_prop_nl_element){ + social_effects_matrix_L2_prop_nl[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for inla.group(L2_copy)`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + social_effects_matrix_L2_prop_nl[i, 4] <- predterms_short[[i]] + social_effects_matrix_L2_prop_nl[i, 5] <- result[[i]]$waic$waic + } + + if(i %in% L1_element) { + social_effects_matrix_L1[i, 1:3] <- c(result[[i]]$summary.fixed["L1_log_st",]$`0.025quant`, result[[i]]$summary.fixed["L1_log_st",]$`0.5quant`, result[[i]]$summary.fixed["L1_log_st",]$`0.975quant`) + social_effects_matrix_L1[i, 4] <- predterms_short[[i]] + social_effects_matrix_L1[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_L1[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["L1_log_st"]])) + colnames(marginals_fixed_list_L1[[i]]) <- c("x for L1", "y for L1") + } + + if(i %in% L2_prop_element) { + social_effects_matrix_L2_prop[i, 1:3] <- c(result[[i]]$summary.fixed["L2_prop",]$`0.025quant`, result[[i]]$summary.fixed["L2_prop",]$`0.5quant`, result[[i]]$summary.fixed["L2_prop",]$`0.975quant`) + social_effects_matrix_L2_prop[i, 4] <- predterms_short[[i]] + social_effects_matrix_L2_prop[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_L2_prop[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["L2_prop"]])) + colnames(marginals_fixed_list_L2_prop[[i]]) <- c("x for L2 proportion", "y for L2 proportion") + } + + if(i %in% interaction_element) { + social_effects_matrix_L1_L2_prop[i, 1:3] <- c(result[[i]]$summary.fixed["L1_log10:L2_prop",]$`0.025quant`, result[[i]]$summary.fixed["L1_log10:L2_prop",]$`0.5quant`, result[[i]]$summary.fixed["L1_log10:L2_prop",]$`0.975quant`) + social_effects_matrix_L1_L2_prop[i, 4] <- predterms_short[[i]] + social_effects_matrix_L1_L2_prop[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_L1_L2_prop[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["L1_log10:L2_prop"]])) + colnames(marginals_fixed_list_L1_L2_prop[[i]]) <- c("x for L1*L2 proportion", "y for L1*L2 proportion") + } + + if(i %in% neighbour_element) { + social_effects_matrix_N[i, 1:3] <- c(result[[i]]$summary.fixed[2,]$`0.025quant`, result[[i]]$summary.fixed[2,]$`0.5quant`, result[[i]]$summary.fixed[2,]$`0.975quant`) + social_effects_matrix_N[i, 4] <- predterms_short[[i]] + social_effects_matrix_N[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_N[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][[2]])) + colnames(marginals_fixed_list_N[[i]]) <- c("x for Neighbours", "y for Neighbours") + } + + if(i %in% official_element) { + social_effects_matrix_O[i, 1:3] <- c(result[[i]]$summary.fixed[2,]$`0.025quant`, result[[i]]$summary.fixed[2,]$`0.5quant`, result[[i]]$summary.fixed[2,]$`0.975quant`) + social_effects_matrix_O[i, 4] <- predterms_short[[i]] + social_effects_matrix_O[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_O[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][[2]])) + colnames(marginals_fixed_list_O[[i]]) <- c("x for Official", "y for Official") + } + + if(i %in% education_element) { + social_effects_matrix_E[i, 1:3] <- c(result[[i]]$summary.fixed[2,]$`0.025quant`, result[[i]]$summary.fixed[2,]$`0.5quant`, result[[i]]$summary.fixed[2,]$`0.975quant`) + social_effects_matrix_E[i, 4] <- predterms_short[[i]] + social_effects_matrix_E[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_E[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][[2]])) + colnames(marginals_fixed_list_E[[i]]) <- c("x for Education", "y for Education") + } + + fitted_list[[i]] <- result[[i]]$summary.fitted.values + fitted_list[[i]] <- fitted_list[[i]] %>% + mutate(across(where(is.numeric), round, 2)) + + marginals_hyperpar_list_gaussian[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for the Gaussian observations"]])) + colnames(marginals_hyperpar_list_gaussian[[i]]) <- c("x for the Gaussian observations", "y for the Gaussian observations") + + if(i %in% phylogenetic_element){ + marginals_hyperpar_list_phy[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for phy_id"]])) + colnames(marginals_hyperpar_list_phy[[i]]) <- c("x for phy_id", "y for phy_id") + } + + if(i %in% spatial_element){ + marginals_hyperpar_list_spa[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for sp_id"]])) + colnames(marginals_hyperpar_list_spa[[i]]) <- c("x for sp_id", "y for sp_id") + } + + if(i %in% L1_nl_element){ + marginals_hyperpar_list_social_L1_nl[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for inla.group(L1_copy)"]])) + colnames(marginals_hyperpar_list_social_L1_nl[[i]]) <- c("x for inla.group(L1_copy)", "y for inla.group(L1_copy)") + } + + if(i %in% L2_prop_nl_element){ + marginals_hyperpar_list_social_L2_prop_nl[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for inla.group(L2_copy)"]])) + colnames(marginals_hyperpar_list_social_L2_prop_nl[[i]]) <- c("x for inla.group(L2_copy)", "y for inla.group(L2_copy)") + } + + if(i %in% phylogenetic_element){ + summary_random_list_phy[[i]] <- cbind(result[[i]]$summary.random$phy_id) %>% + rename(phy_id = ID) %>% + as.data.frame() %>% + mutate(across(where(is.numeric), round, 2)) + } + + if(i %in% spatial_element){ + summary_random_list_spa[[i]] <- cbind(result[[i]]$summary.random$sp_id) %>% + rename(sp_id = ID) %>% + as.data.frame() %>% + mutate(across(where(is.numeric), round, 2)) + } +} + +#beepr::beep(5) + +save(result, file = "output_models/models_Informativity_social_0.5.RData") + + +coefm <- as.data.frame(cbind(predterms_short, coefm)) +colnames(coefm) <- c("model", "WAIC") +coefm <- coefm %>% + mutate(across(.cols=2, as.numeric)) %>% + mutate(across(where(is.numeric), round, 2)) %>% + arrange(WAIC) + +coefm$WAIC <- as.numeric(coefm$WAIC) +coefm <- coefm[order(coefm$WAIC),] + +coefm_path <- paste("output_tables/", "waics", "Informativity_social_models", "prior_0.5", ".csv", collapse = "") +write.csv(coefm, coefm_path, row.names=FALSE) + + +phy_effects<-as.data.frame(phy_effects_matrix) +spa_effects<-as.data.frame(spa_effects_matrix) +intercept_effects <- as.data.frame(intercept_matrix) +L1_effects <- as.data.frame(social_effects_matrix_L1) +L1_nl_effects <- as.data.frame(social_effects_matrix_L1_nl) +L2_prop_effects <- as.data.frame(social_effects_matrix_L2_prop) +L2_prop_nl_effects <- as.data.frame(social_effects_matrix_L2_prop_nl) +N_effects<-as.data.frame(social_effects_matrix_N) +E_effects<-as.data.frame(social_effects_matrix_E) +O_effects<-as.data.frame(social_effects_matrix_O) +interaction_effects <- as.data.frame(social_effects_matrix_L1_L2_prop) + +phy_effects$effect <- "phylogenetic SD" +spa_effects$effect <- "spatial SD" +intercept_effects$effect <- "Intercept" +L1_effects$effect <- "L1" +L1_nl_effects$effect <- "social SD:\nL1" +L2_prop_effects$effect <- "L2 proportion" +L2_prop_nl_effects$effect <- "social SD:\nL2 proportion" +N_effects$effect <- "Neighbours" +E_effects$effect <- "Education" +O_effects$effect <- "Official status" +interaction_effects$effect <- "L1*L2 proportion" + +effs <- as.data.frame(rbind(phy_effects, spa_effects, intercept_effects, L1_effects, L1_nl_effects, L2_prop_effects, L2_prop_nl_effects, N_effects, O_effects, E_effects, interaction_effects)) +effs <- effs %>% + mutate(across(.cols=c(1:3, 5), as.numeric)) %>% + mutate(across(where(is.numeric), round, 2)) %>% + na.omit() %>% + arrange(WAIC) %>% + relocate(model) + +effs_path <- paste("output_tables/", "effects", "Informativity_social_models", "prior_0.5", ".csv", collapse = "") +write.csv(effs, effs_path, row.names=FALSE) + diff --git a/101/replication_package/sensitivity_testing_I_099.R b/101/replication_package/sensitivity_testing_I_099.R new file mode 100644 index 0000000000000000000000000000000000000000..b0f2112e1421a1d3c90ccf5044d49d5f9bd2addc --- /dev/null +++ b/101/replication_package/sensitivity_testing_I_099.R @@ -0,0 +1,441 @@ +#model fitting: Informativity predicted by social effects on top of random phylogenetic and spatial factors + +source("requirements.R") + +source("install_and_load_INLA.R") + +source("set_up_inla.R") + +metrics_joined <- metrics_joined %>% + filter(!is.na(L1_log10_st)) %>% + rename(L1_log_st = L1_log10_st) %>% + mutate(L1_copy = L1_log_st) %>% + filter(!is.na(L2_prop)) %>% + mutate(L2_copy = L2_prop) %>% + filter(!is.na(neighboring_languages_st)) %>% + filter(!is.na(Official)) %>% + filter(!is.na(Education)) %>% + filter(!is.na(boundness_st)) %>% + filter(!is.na(informativity_st)) + +#dropping tips not in Grambank +metrics_joined <- metrics_joined[metrics_joined$Language_ID %in% tree$tip.label, ] +tree <- keep.tip(tree, metrics_joined$Language_ID) + +x <- assert_that(all(tree$tip.label %in% metrics_joined$Language_ID), msg = "The data and phylogeny taxa do not match") + +## Building standardized phylogenetic precision matrix +tree_scaled <- tree + +tree_vcv = vcv.phylo(tree_scaled) +typical_phylogenetic_variance = exp(mean(log(diag(tree_vcv)))) + +tree_scaled$edge.length <- tree_scaled$edge.length/typical_phylogenetic_variance +phylo_prec_mat <- MCMCglmm::inverseA(tree_scaled, + nodes = "ALL", + scale = FALSE)$Ainv + +metrics_joined = metrics_joined[order(match(metrics_joined$Language_ID, rownames(phylo_prec_mat))),] + +#"local" set of parameters +## Create spatial covariance matrix using the matern covariance function +spatial_covar_mat_1 = varcov.spatial(metrics_joined[,c("Longitude", "Latitude")], + cov.pars = phi_1, kappa = kappa)$varcov +# Calculate and standardize by the typical variance +typical_variance_spatial_1 = exp(mean(log(diag(spatial_covar_mat_1)))) +spatial_cov_std_1 = spatial_covar_mat_1 / typical_variance_spatial_1 +spatial_prec_mat_1 = solve(spatial_cov_std_1) +dimnames(spatial_prec_mat_1) = list(metrics_joined$Language_ID, metrics_joined$Language_ID) + +## Since we are using a sparse phylogenetic matrix, we are matching taxa to rows in the matrix +phy_id = match(tree$tip.label, rownames(phylo_prec_mat)) +metrics_joined$phy_id = phy_id + +## Other effects are in the same order they appear in the dataset +metrics_joined$sp_id = 1:nrow(spatial_prec_mat_1) + +pcprior_hyper_0.99 = list(prec =list(prior="pc.prec", param = c(1, 0.99))) + +#Preparing the formulas for 10 competing models to be used in inla() call +listcombo <- list( + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.99)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.99)", "L1_log_st"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.99)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.99)", "f(inla.group(L1_copy), model='rw2', scale.model = TRUE)"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.99)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.99)", "L2_prop"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.99)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.99)", "f(inla.group(L2_copy), model='rw2', scale.model = TRUE)"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.99)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.99)", "f(inla.group(L1_copy), model='rw2', scale.model = TRUE)", "f(inla.group(L2_copy), model='rw2', scale.model = TRUE)"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.99)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.99)", "L1_log_st", "L2_prop"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.99)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.99)", "L1_log10:L2_prop"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.99)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.99)", "neighboring_languages_st"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.99)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.99)", "Official"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.99)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.99)", "Education")) + + +predterms <- lapply(listcombo, function(x) paste(x, collapse="+")) + +predterms <- t(as.data.frame(predterms)) + +predterms_short <- predterms +predterms_short <- gsub("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.99)", "Phylogenetic", predterms_short, fixed=TRUE) +predterms_short <- gsub("f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.99)", "Spatial: local", predterms_short, fixed=TRUE) + +predterms_short <- gsub("f(inla.group(L1_copy), model='rw2', scale.model = TRUE)", "L1 speakers (nonlinear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("L1_log_st", "L1 speakers (linear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("f(inla.group(L2_copy), model='rw2', scale.model = TRUE)", "L2 proportion (nonlinear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("L2_prop", "L2 proportion (linear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("neighboring_languages_st", "Neighbours", predterms_short, fixed=TRUE) + + +phylogenetic_element <- data.frame("judgement" = grepl("Phylogenetic", predterms_short), + number = 1:length(predterms_short)) +phylogenetic_element <- phylogenetic_element[phylogenetic_element$judgement == TRUE,]$number + +spatial_element_local <- data.frame("judgement" = grepl("local", predterms_short), + number = 1:length(predterms_short)) +spatial_element_local <- spatial_element_local[spatial_element_local$judgement == TRUE,]$number + +spatial_element_regional <- data.frame("judgement" = grepl("regional", predterms_short), + number = 1:length(predterms_short)) +spatial_element_regional <- spatial_element_regional[spatial_element_regional$judgement == TRUE,]$number + +spatial_element <- c(spatial_element_local, spatial_element_regional) + +L1_element <- data.frame("judgement" = grepl("L1 speakers (linear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L1_element <- L1_element[L1_element$judgement == TRUE,]$number + + +L1_nl_element <- data.frame("judgement" = grepl("L1 speakers (nonlinear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L1_nl_element <- L1_nl_element[L1_nl_element$judgement == TRUE,]$number + +L2_prop_element <- data.frame("judgement" = grepl("L2 proportion (linear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L2_prop_element <- L2_prop_element[L2_prop_element$judgement == TRUE,]$number +L2_prop_element <- L2_prop_element[-length(L2_prop_element)] #making sure that the interaction term (introduced below) is not treated as belonging to this isolated element + +L2_prop_nl_element <- data.frame("judgement" = grepl("L2 proportion (nonlinear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L2_prop_nl_element <- L2_prop_nl_element[L2_prop_nl_element$judgement == TRUE,]$number + +#can use only part of the interaction term within grepl() function +interaction_element <- data.frame("judgement" = grepl(":L2 proportion", predterms_short), + number = 1:length(predterms_short)) +interaction_element <- interaction_element[interaction_element$judgement == TRUE,]$number + +neighbour_element <- data.frame("judgement" = grepl("Neighbours", predterms_short), + number = 1:length(predterms_short)) +neighbour_element <- neighbour_element[neighbour_element$judgement == TRUE,]$number + +official_element <- data.frame("judgement" = grepl("Official", predterms_short), + number = 1:length(predterms_short)) +official_element <- official_element[official_element$judgement == TRUE,]$number + +education_element <- data.frame("judgement" = grepl("Education", predterms_short), + number = 1:length(predterms_short)) +education_element <- education_element[education_element$judgement == TRUE,]$number + + + +#preparing empty matrices to be filled with effect estimates (quantiles), model name, and WAIC value +phy_effects_matrix <- matrix(NA, 10, 5) +colnames(phy_effects_matrix) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +spa_effects_matrix <- matrix(NA, 10, 5) +colnames(spa_effects_matrix) <- c("2.5%", "50%", "97.5%", "model", "WAIC") + +intercept_matrix <- matrix(NA, 10, 5) +colnames(intercept_matrix) <- c("2.5%", "50%", "97.5%", "model", "WAIC") + +social_effects_matrix_L1 <- matrix(NA, 10, 5) +colnames(social_effects_matrix_L1) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L1_nl <- matrix(NA, 10, 5) +colnames(social_effects_matrix_L1_nl) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L2_prop <- matrix(NA, 10, 5) +colnames(social_effects_matrix_L2_prop) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L2_prop_nl <- matrix(NA, 10, 5) +colnames(social_effects_matrix_L2_prop_nl) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_N <- matrix(NA, 10, 5) +colnames(social_effects_matrix_N) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_O <- matrix(NA, 10, 5) +colnames(social_effects_matrix_O) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_E <- matrix(NA, 10, 5) +colnames(social_effects_matrix_E) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L1_L2_prop <- matrix(NA, 10, 5) +colnames(social_effects_matrix_L1_L2_prop) <- c("2.5%", "50%", "97.5%", "model", "WAIC") + +#fitted values +fitted_list <- vector("list", 10) +names(fitted_list) <- predterms_short + +#marginals of hyperparameters +marginals_hyperpar_list_gaussian <- vector("list", 10) +names(marginals_hyperpar_list_gaussian) <- predterms_short + +marginals_hyperpar_list_phy <- vector("list", 10) +names(marginals_hyperpar_list_phy) <- predterms_short + +marginals_hyperpar_list_spa <- vector("list", 10) +names(marginals_hyperpar_list_spa) <- predterms_short + +marginals_hyperpar_list_social_L1_nl <- vector("list", 10) +names(marginals_hyperpar_list_social_L1_nl) <- predterms_short + +marginals_hyperpar_list_social_L2_prop_nl <- vector("list", 10) +names(marginals_hyperpar_list_social_L2_prop_nl) <- predterms_short + + +#marginals of fixed effects +marginals_fixed_list_Intercept <- vector("list", 10) +names(marginals_fixed_list_Intercept) <- predterms_short + +marginals_fixed_list_L1 <- vector("list", 10) +names(marginals_fixed_list_L1) <- predterms_short + +marginals_fixed_list_L2_prop <- vector("list", 10) +names(marginals_fixed_list_L2_prop) <- predterms_short + +marginals_fixed_list_O <- vector("list", 10) +names(marginals_fixed_list_O) <- predterms_short + +marginals_fixed_list_N <- vector("list", 10) +names(marginals_fixed_list_N) <- predterms_short + +marginals_fixed_list_E <- vector("list", 10) +names(marginals_fixed_list_E) <- predterms_short + +marginals_fixed_list_L1_L2_prop <- vector("list", 10) +names(marginals_fixed_list_L1_L2_prop) <- predterms_short + + + + +#summary statistics of random effects +summary_random_list_phy <- vector("list", 10) +names(summary_random_list_phy) <- predterms_short + +summary_random_list_spa <- vector("list", 10) +names(summary_random_list_spa) <- predterms_short + +summary_random_list_social_L1_nl <- vector("list", 10) +names(summary_random_list_social_L1_nl) <- predterms_short + +summary_random_list_social_L2_prop_nl <- vector("list", 10) +names(summary_random_list_social_L2_prop_nl) <- predterms_short + + +coefm <- matrix(NA,10,1) +result <- vector("list",10) + +for(i in 1:10){ + formula <- as.formula(paste("informativity_st ~ ",predterms[[i]])) + result[[i]] <- inla(formula, family="gaussian", + control.family = list(hyper = pcprior_hyper_0.99), + #control.inla = list(tolerance = 1e-8, h = 0.0001), + #tolerance: the tolerance for the optimisation of the hyperparameters + #h: the step-length for the gradient calculations for the hyperparameters. + data=metrics_joined, control.compute=list(waic=TRUE)) + + coefm[i,1] <- round(result[[i]]$waic$waic, 2) + + intercept_matrix[i, 1:3] <- c(result[[i]]$summary.fixed[1,]$`0.025quant`, result[[i]]$summary.fixed[1,]$`0.5quant`, result[[i]]$summary.fixed[1,]$`0.975quant`) + intercept_matrix[i, 4] <- predterms_short[[i]] + intercept_matrix[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_Intercept[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["(Intercept)"]])) + colnames(marginals_fixed_list_Intercept[[i]]) <- c("x for Intercept", "y for Intercept") + + if(i %in% phylogenetic_element) { + phy_effects_matrix[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for phy_id`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + phy_effects_matrix[i, 4] <- predterms_short[[i]] + phy_effects_matrix[i, 5] <- result[[i]]$waic$waic + } + + if(i %in% spatial_element) { + spa_effects_matrix[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for sp_id`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + spa_effects_matrix[i, 4] <- predterms_short[[i]] + spa_effects_matrix[i, 5] <- result[[i]]$waic$waic + } + + + if(i %in% L1_nl_element){ + social_effects_matrix_L1_nl[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for inla.group(L1_copy)`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + social_effects_matrix_L1_nl[i, 4] <- predterms_short[[i]] + social_effects_matrix_L1_nl[i, 5] <- result[[i]]$waic$waic + } + + if(i %in% L2_prop_nl_element){ + social_effects_matrix_L2_prop_nl[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for inla.group(L2_copy)`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + social_effects_matrix_L2_prop_nl[i, 4] <- predterms_short[[i]] + social_effects_matrix_L2_prop_nl[i, 5] <- result[[i]]$waic$waic + } + + if(i %in% L1_element) { + social_effects_matrix_L1[i, 1:3] <- c(result[[i]]$summary.fixed["L1_log_st",]$`0.025quant`, result[[i]]$summary.fixed["L1_log_st",]$`0.5quant`, result[[i]]$summary.fixed["L1_log_st",]$`0.975quant`) + social_effects_matrix_L1[i, 4] <- predterms_short[[i]] + social_effects_matrix_L1[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_L1[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["L1_log_st"]])) + colnames(marginals_fixed_list_L1[[i]]) <- c("x for L1", "y for L1") + } + + if(i %in% L2_prop_element) { + social_effects_matrix_L2_prop[i, 1:3] <- c(result[[i]]$summary.fixed["L2_prop",]$`0.025quant`, result[[i]]$summary.fixed["L2_prop",]$`0.5quant`, result[[i]]$summary.fixed["L2_prop",]$`0.975quant`) + social_effects_matrix_L2_prop[i, 4] <- predterms_short[[i]] + social_effects_matrix_L2_prop[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_L2_prop[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["L2_prop"]])) + colnames(marginals_fixed_list_L2_prop[[i]]) <- c("x for L2 proportion", "y for L2 proportion") + } + + if(i %in% interaction_element) { + social_effects_matrix_L1_L2_prop[i, 1:3] <- c(result[[i]]$summary.fixed["L1_log10:L2_prop",]$`0.025quant`, result[[i]]$summary.fixed["L1_log10:L2_prop",]$`0.5quant`, result[[i]]$summary.fixed["L1_log10:L2_prop",]$`0.975quant`) + social_effects_matrix_L1_L2_prop[i, 4] <- predterms_short[[i]] + social_effects_matrix_L1_L2_prop[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_L1_L2_prop[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["L1_log10:L2_prop"]])) + colnames(marginals_fixed_list_L1_L2_prop[[i]]) <- c("x for L1*L2 proportion", "y for L1*L2 proportion") + } + + if(i %in% neighbour_element) { + social_effects_matrix_N[i, 1:3] <- c(result[[i]]$summary.fixed[2,]$`0.025quant`, result[[i]]$summary.fixed[2,]$`0.5quant`, result[[i]]$summary.fixed[2,]$`0.975quant`) + social_effects_matrix_N[i, 4] <- predterms_short[[i]] + social_effects_matrix_N[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_N[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][[2]])) + colnames(marginals_fixed_list_N[[i]]) <- c("x for Neighbours", "y for Neighbours") + } + + if(i %in% official_element) { + social_effects_matrix_O[i, 1:3] <- c(result[[i]]$summary.fixed[2,]$`0.025quant`, result[[i]]$summary.fixed[2,]$`0.5quant`, result[[i]]$summary.fixed[2,]$`0.975quant`) + social_effects_matrix_O[i, 4] <- predterms_short[[i]] + social_effects_matrix_O[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_O[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][[2]])) + colnames(marginals_fixed_list_O[[i]]) <- c("x for Official", "y for Official") + } + + if(i %in% education_element) { + social_effects_matrix_E[i, 1:3] <- c(result[[i]]$summary.fixed[2,]$`0.025quant`, result[[i]]$summary.fixed[2,]$`0.5quant`, result[[i]]$summary.fixed[2,]$`0.975quant`) + social_effects_matrix_E[i, 4] <- predterms_short[[i]] + social_effects_matrix_E[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_E[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][[2]])) + colnames(marginals_fixed_list_E[[i]]) <- c("x for Education", "y for Education") + } + + fitted_list[[i]] <- result[[i]]$summary.fitted.values + fitted_list[[i]] <- fitted_list[[i]] %>% + mutate(across(where(is.numeric), round, 2)) + + marginals_hyperpar_list_gaussian[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for the Gaussian observations"]])) + colnames(marginals_hyperpar_list_gaussian[[i]]) <- c("x for the Gaussian observations", "y for the Gaussian observations") + + if(i %in% phylogenetic_element){ + marginals_hyperpar_list_phy[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for phy_id"]])) + colnames(marginals_hyperpar_list_phy[[i]]) <- c("x for phy_id", "y for phy_id") + } + + if(i %in% spatial_element){ + marginals_hyperpar_list_spa[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for sp_id"]])) + colnames(marginals_hyperpar_list_spa[[i]]) <- c("x for sp_id", "y for sp_id") + } + + if(i %in% L1_nl_element){ + marginals_hyperpar_list_social_L1_nl[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for inla.group(L1_copy)"]])) + colnames(marginals_hyperpar_list_social_L1_nl[[i]]) <- c("x for inla.group(L1_copy)", "y for inla.group(L1_copy)") + } + + if(i %in% L2_prop_nl_element){ + marginals_hyperpar_list_social_L2_prop_nl[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for inla.group(L2_copy)"]])) + colnames(marginals_hyperpar_list_social_L2_prop_nl[[i]]) <- c("x for inla.group(L2_copy)", "y for inla.group(L2_copy)") + } + + if(i %in% phylogenetic_element){ + summary_random_list_phy[[i]] <- cbind(result[[i]]$summary.random$phy_id) %>% + rename(phy_id = ID) %>% + as.data.frame() %>% + mutate(across(where(is.numeric), round, 2)) + } + + if(i %in% spatial_element){ + summary_random_list_spa[[i]] <- cbind(result[[i]]$summary.random$sp_id) %>% + rename(sp_id = ID) %>% + as.data.frame() %>% + mutate(across(where(is.numeric), round, 2)) + } +} + +#beepr::beep(5) + +save(result, file = "output_models/models_Informativity_social_0.99.RData") + + +coefm <- as.data.frame(cbind(predterms_short, coefm)) +colnames(coefm) <- c("model", "WAIC") +coefm <- coefm %>% + mutate(across(.cols=2, as.numeric)) %>% + mutate(across(where(is.numeric), round, 2)) %>% + arrange(WAIC) + +coefm$WAIC <- as.numeric(coefm$WAIC) +coefm <- coefm[order(coefm$WAIC),] + +coefm_path <- paste("output_tables/", "waics", "Informativity_social_models", "prior_0.99", ".csv", collapse = "") +write.csv(coefm, coefm_path, row.names=FALSE) + + +phy_effects<-as.data.frame(phy_effects_matrix) +spa_effects<-as.data.frame(spa_effects_matrix) +intercept_effects <- as.data.frame(intercept_matrix) +L1_effects <- as.data.frame(social_effects_matrix_L1) +L1_nl_effects <- as.data.frame(social_effects_matrix_L1_nl) +L2_prop_effects <- as.data.frame(social_effects_matrix_L2_prop) +L2_prop_nl_effects <- as.data.frame(social_effects_matrix_L2_prop_nl) +N_effects<-as.data.frame(social_effects_matrix_N) +E_effects<-as.data.frame(social_effects_matrix_E) +O_effects<-as.data.frame(social_effects_matrix_O) +interaction_effects <- as.data.frame(social_effects_matrix_L1_L2_prop) + +phy_effects$effect <- "phylogenetic SD" +spa_effects$effect <- "spatial SD" +intercept_effects$effect <- "Intercept" +L1_effects$effect <- "L1" +L1_nl_effects$effect <- "social SD:\nL1" +L2_prop_effects$effect <- "L2 proportion" +L2_prop_nl_effects$effect <- "social SD:\nL2 proportion" +N_effects$effect <- "Neighbours" +E_effects$effect <- "Education" +O_effects$effect <- "Official status" +interaction_effects$effect <- "L1*L2 proportion" + +effs <- as.data.frame(rbind(phy_effects, spa_effects, intercept_effects, L1_effects, L1_nl_effects, L2_prop_effects, L2_prop_nl_effects, N_effects, O_effects, E_effects, interaction_effects)) +effs <- effs %>% + mutate(across(.cols=c(1:3, 5), as.numeric)) %>% + mutate(across(where(is.numeric), round, 2)) %>% + na.omit() %>% + arrange(WAIC) %>% + relocate(model) + +effs_path <- paste("output_tables/", "effects", "Informativity_social_models", "prior_0.99", ".csv", collapse = "") +write.csv(effs, effs_path, row.names=FALSE) + diff --git a/101/replication_package/sensitivity_testing_reduced_B_001.R b/101/replication_package/sensitivity_testing_reduced_B_001.R new file mode 100644 index 0000000000000000000000000000000000000000..044346818712f924c426a1a4f8782341611a42d0 --- /dev/null +++ b/101/replication_package/sensitivity_testing_reduced_B_001.R @@ -0,0 +1,422 @@ +#model fitting: Boundness predicted by social effects on top of random phylogenetic and spatial factors + +source("requirements.R") + +source("install_and_load_INLA.R") + +source("set_up_inla.R") + +metrics_joined <- metrics_joined %>% + filter(!is.na(L1_log10_st)) %>% + rename(L1_log_st = L1_log10_st) %>% + mutate(L1_copy = L1_log_st) %>% + filter(!is.na(L2_prop)) %>% + mutate(L2_copy = L2_prop) %>% + filter(!is.na(neighboring_languages_st)) %>% + filter(!is.na(Official)) %>% + filter(!is.na(Education)) %>% + filter(!is.na(boundness_st)) %>% + filter(!is.na(informativity_st)) + +#dropping tips not in Grambank +metrics_joined <- metrics_joined[metrics_joined$Language_ID %in% tree$tip.label, ] +tree <- keep.tip(tree, metrics_joined$Language_ID) + +x <- assert_that(all(tree$tip.label %in% metrics_joined$Language_ID), msg = "The data and phylogeny taxa do not match") + +## Building standardized phylogenetic precision matrix +tree_scaled <- tree + +tree_vcv = vcv.phylo(tree_scaled) +typical_phylogenetic_variance = exp(mean(log(diag(tree_vcv)))) + +tree_scaled$edge.length <- tree_scaled$edge.length/typical_phylogenetic_variance +phylo_prec_mat <- MCMCglmm::inverseA(tree_scaled, + nodes = "ALL", + scale = FALSE)$Ainv + +metrics_joined = metrics_joined[order(match(metrics_joined$Language_ID, rownames(phylo_prec_mat))),] + +#"local" set of parameters +## Create spatial covariance matrix using the matern covariance function +spatial_covar_mat_1 = varcov.spatial(metrics_joined[,c("Longitude", "Latitude")], + cov.pars = phi_1, kappa = kappa)$varcov +# Calculate and standardize by the typical variance +typical_variance_spatial_1 = exp(mean(log(diag(spatial_covar_mat_1)))) +spatial_cov_std_1 = spatial_covar_mat_1 / typical_variance_spatial_1 +spatial_prec_mat_1 = solve(spatial_cov_std_1) +dimnames(spatial_prec_mat_1) = list(metrics_joined$Language_ID, metrics_joined$Language_ID) + +## Since we are using a sparse phylogenetic matrix, we are matching taxa to rows in the matrix +phy_id = match(tree$tip.label, rownames(phylo_prec_mat)) +metrics_joined$phy_id = phy_id + +## Other effects are in the same order they appear in the dataset +metrics_joined$sp_id = 1:nrow(spatial_prec_mat_1) + +pcprior_hyper_0.01 = list(prec =list(prior="pc.prec", param = c(1, 0.01))) + +#Preparing the formulas for 10 competing models to be used in inla() call +listcombo <- list( + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.01)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.01)", "L1_log_st"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.01)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.01)", "f(inla.group(L1_copy), model='rw2', scale.model = TRUE)"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.01)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.01)", "L2_prop"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.01)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.01)", "f(inla.group(L2_copy), model='rw2', scale.model = TRUE)"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.01)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.01)", "f(inla.group(L1_copy), model='rw2', scale.model = TRUE)", "f(inla.group(L2_copy), model='rw2', scale.model = TRUE)"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.01)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.01)", "L1_log_st", "L2_prop"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.01)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.01)", "neighboring_languages_st"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.01)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.01)", "Official"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.01)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.01)", "Education")) + + +predterms <- lapply(listcombo, function(x) paste(x, collapse="+")) + +predterms <- t(as.data.frame(predterms)) + +predterms_short <- predterms + +predterms_short <- gsub("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.01)", "Phylogenetic", predterms_short, fixed=TRUE) +predterms_short <- gsub("f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.01)", "Spatial: local", predterms_short, fixed=TRUE) + +predterms_short <- gsub("f(inla.group(L1_copy), model='rw2', scale.model = TRUE)", "L1 speakers (nonlinear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("L1_log_st", "L1 speakers (linear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("f(inla.group(L2_copy), model='rw2', scale.model = TRUE)", "L2 proportion (nonlinear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("L2_prop", "L2 proportion (linear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("neighboring_languages_st", "Neighbours", predterms_short, fixed=TRUE) + + + +phylogenetic_element <- data.frame("judgement" = grepl("Phylogenetic", predterms_short), + number = 1:length(predterms_short)) +phylogenetic_element <- phylogenetic_element[phylogenetic_element$judgement == TRUE,]$number + +spatial_element_local <- data.frame("judgement" = grepl("local", predterms_short), + number = 1:length(predterms_short)) +spatial_element_local <- spatial_element_local[spatial_element_local$judgement == TRUE,]$number + +spatial_element_regional <- data.frame("judgement" = grepl("regional", predterms_short), + number = 1:length(predterms_short)) +spatial_element_regional <- spatial_element_regional[spatial_element_regional$judgement == TRUE,]$number + +spatial_element <- c(spatial_element_local, spatial_element_regional) + +L1_element <- data.frame("judgement" = grepl("L1 speakers (linear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L1_element <- L1_element[L1_element$judgement == TRUE,]$number + + +L1_nl_element <- data.frame("judgement" = grepl("L1 speakers (nonlinear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L1_nl_element <- L1_nl_element[L1_nl_element$judgement == TRUE,]$number + +L2_prop_element <- data.frame("judgement" = grepl("L2 proportion (linear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L2_prop_element <- L2_prop_element[L2_prop_element$judgement == TRUE,]$number + +L2_prop_nl_element <- data.frame("judgement" = grepl("L2 proportion (nonlinear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L2_prop_nl_element <- L2_prop_nl_element[L2_prop_nl_element$judgement == TRUE,]$number + +neighbour_element <- data.frame("judgement" = grepl("Neighbours", predterms_short), + number = 1:length(predterms_short)) +neighbour_element <- neighbour_element[neighbour_element$judgement == TRUE,]$number + +official_element <- data.frame("judgement" = grepl("Official", predterms_short), + number = 1:length(predterms_short)) +official_element <- official_element[official_element$judgement == TRUE,]$number + +education_element <- data.frame("judgement" = grepl("Education", predterms_short), + number = 1:length(predterms_short)) +education_element <- education_element[education_element$judgement == TRUE,]$number + +models_number <- length(predterms_short) + +#preparing empty matrices to be filled with effect estimates (quantiles), model name, and WAIC value +phy_effects_matrix <- matrix(NA, models_number, 5) +colnames(phy_effects_matrix) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +spa_effects_matrix <- matrix(NA, models_number, 5) +colnames(spa_effects_matrix) <- c("2.5%", "50%", "97.5%", "model", "WAIC") + +intercept_matrix <- matrix(NA, models_number, 5) +colnames(intercept_matrix) <- c("2.5%", "50%", "97.5%", "model", "WAIC") + +social_effects_matrix_L1 <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_L1) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L1_nl <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_L1_nl) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L2_prop <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_L2_prop) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L2_prop_nl <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_L2_prop_nl) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_N <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_N) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_O <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_O) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_E <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_E) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L1_L2_prop <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_L1_L2_prop) <- c("2.5%", "50%", "97.5%", "model", "WAIC") + +#fitted values +fitted_list <- vector("list", models_number) +names(fitted_list) <- predterms_short + +#marginals of hyperparameters +marginals_hyperpar_list_gaussian <- vector("list", models_number) +names(marginals_hyperpar_list_gaussian) <- predterms_short + +marginals_hyperpar_list_phy <- vector("list", models_number) +names(marginals_hyperpar_list_phy) <- predterms_short + +marginals_hyperpar_list_spa <- vector("list", models_number) +names(marginals_hyperpar_list_spa) <- predterms_short + +marginals_hyperpar_list_social_L1_nl <- vector("list", models_number) +names(marginals_hyperpar_list_social_L1_nl) <- predterms_short + +marginals_hyperpar_list_social_L2_prop_nl <- vector("list", models_number) +names(marginals_hyperpar_list_social_L2_prop_nl) <- predterms_short + + +#marginals of fixed effects +marginals_fixed_list_Intercept <- vector("list", models_number) +names(marginals_fixed_list_Intercept) <- predterms_short + +marginals_fixed_list_L1 <- vector("list", models_number) +names(marginals_fixed_list_L1) <- predterms_short + +marginals_fixed_list_L2_prop <- vector("list", models_number) +names(marginals_fixed_list_L2_prop) <- predterms_short + +marginals_fixed_list_O <- vector("list", models_number) +names(marginals_fixed_list_O) <- predterms_short + +marginals_fixed_list_N <- vector("list", models_number) +names(marginals_fixed_list_N) <- predterms_short + +marginals_fixed_list_E <- vector("list", models_number) +names(marginals_fixed_list_E) <- predterms_short + +marginals_fixed_list_L1_L2_prop <- vector("list", models_number) +names(marginals_fixed_list_L1_L2_prop) <- predterms_short + + + + +#summary statistics of random effects +summary_random_list_phy <- vector("list", models_number) +names(summary_random_list_phy) <- predterms_short + +summary_random_list_spa <- vector("list", models_number) +names(summary_random_list_spa) <- predterms_short + +summary_random_list_social_L1_nl <- vector("list", models_number) +names(summary_random_list_social_L1_nl) <- predterms_short + +summary_random_list_social_L2_prop_nl <- vector("list", models_number) +names(summary_random_list_social_L2_prop_nl) <- predterms_short + + +coefm <- matrix(NA,models_number,1) +result <- vector("list",models_number) + +for(i in 1:models_number){ + formula <- as.formula(paste("boundness_st ~ ",predterms[[i]])) + result[[i]] <- inla(formula, family="gaussian", + control.family = list(hyper = pcprior_hyper_0.01), + #control.inla = list(tolerance = 1e-8, h = 0.0001), + #tolerance: the tolerance for the optimisation of the hyperparameters + #h: the step-length for the gradient calculations for the hyperparameters. + data=metrics_joined, control.compute=list(waic=TRUE)) + + coefm[i,1] <- round(result[[i]]$waic$waic, 2) + + intercept_matrix[i, 1:3] <- c(result[[i]]$summary.fixed[1,]$`0.025quant`, result[[i]]$summary.fixed[1,]$`0.5quant`, result[[i]]$summary.fixed[1,]$`0.975quant`) + intercept_matrix[i, 4] <- predterms_short[[i]] + intercept_matrix[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_Intercept[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["(Intercept)"]])) + colnames(marginals_fixed_list_Intercept[[i]]) <- c("x for Intercept", "y for Intercept") + + if(i %in% phylogenetic_element) { + phy_effects_matrix[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for phy_id`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + phy_effects_matrix[i, 4] <- predterms_short[[i]] + phy_effects_matrix[i, 5] <- result[[i]]$waic$waic + } + + if(i %in% spatial_element) { + spa_effects_matrix[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for sp_id`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + spa_effects_matrix[i, 4] <- predterms_short[[i]] + spa_effects_matrix[i, 5] <- result[[i]]$waic$waic + } + + + if(i %in% L1_nl_element){ + social_effects_matrix_L1_nl[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for inla.group(L1_copy)`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + social_effects_matrix_L1_nl[i, 4] <- predterms_short[[i]] + social_effects_matrix_L1_nl[i, 5] <- result[[i]]$waic$waic + } + + if(i %in% L2_prop_nl_element){ + social_effects_matrix_L2_prop_nl[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for inla.group(L2_copy)`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + social_effects_matrix_L2_prop_nl[i, 4] <- predterms_short[[i]] + social_effects_matrix_L2_prop_nl[i, 5] <- result[[i]]$waic$waic + } + + if(i %in% L1_element) { + social_effects_matrix_L1[i, 1:3] <- c(result[[i]]$summary.fixed["L1_log_st",]$`0.025quant`, result[[i]]$summary.fixed["L1_log_st",]$`0.5quant`, result[[i]]$summary.fixed["L1_log_st",]$`0.975quant`) + social_effects_matrix_L1[i, 4] <- predterms_short[[i]] + social_effects_matrix_L1[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_L1[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["L1_log_st"]])) + colnames(marginals_fixed_list_L1[[i]]) <- c("x for L1", "y for L1") + } + + if(i %in% L2_prop_element) { + social_effects_matrix_L2_prop[i, 1:3] <- c(result[[i]]$summary.fixed["L2_prop",]$`0.025quant`, result[[i]]$summary.fixed["L2_prop",]$`0.5quant`, result[[i]]$summary.fixed["L2_prop",]$`0.975quant`) + social_effects_matrix_L2_prop[i, 4] <- predterms_short[[i]] + social_effects_matrix_L2_prop[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_L2_prop[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["L2_prop"]])) + colnames(marginals_fixed_list_L2_prop[[i]]) <- c("x for L2 proportion", "y for L2 proportion") + } + + if(i %in% neighbour_element) { + social_effects_matrix_N[i, 1:3] <- c(result[[i]]$summary.fixed[2,]$`0.025quant`, result[[i]]$summary.fixed[2,]$`0.5quant`, result[[i]]$summary.fixed[2,]$`0.975quant`) + social_effects_matrix_N[i, 4] <- predterms_short[[i]] + social_effects_matrix_N[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_N[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][[2]])) + colnames(marginals_fixed_list_N[[i]]) <- c("x for Neighbours", "y for Neighbours") + } + + if(i %in% official_element) { + social_effects_matrix_O[i, 1:3] <- c(result[[i]]$summary.fixed[2,]$`0.025quant`, result[[i]]$summary.fixed[2,]$`0.5quant`, result[[i]]$summary.fixed[2,]$`0.975quant`) + social_effects_matrix_O[i, 4] <- predterms_short[[i]] + social_effects_matrix_O[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_O[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][[2]])) + colnames(marginals_fixed_list_O[[i]]) <- c("x for Official", "y for Official") + } + + if(i %in% education_element) { + social_effects_matrix_E[i, 1:3] <- c(result[[i]]$summary.fixed[2,]$`0.025quant`, result[[i]]$summary.fixed[2,]$`0.5quant`, result[[i]]$summary.fixed[2,]$`0.975quant`) + social_effects_matrix_E[i, 4] <- predterms_short[[i]] + social_effects_matrix_E[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_E[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][[2]])) + colnames(marginals_fixed_list_E[[i]]) <- c("x for Education", "y for Education") + } + + fitted_list[[i]] <- result[[i]]$summary.fitted.values + fitted_list[[i]] <- fitted_list[[i]] %>% + mutate(across(where(is.numeric), round, 2)) + + marginals_hyperpar_list_gaussian[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for the Gaussian observations"]])) + colnames(marginals_hyperpar_list_gaussian[[i]]) <- c("x for the Gaussian observations", "y for the Gaussian observations") + + if(i %in% phylogenetic_element){ + marginals_hyperpar_list_phy[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for phy_id"]])) + colnames(marginals_hyperpar_list_phy[[i]]) <- c("x for phy_id", "y for phy_id") + } + + if(i %in% spatial_element){ + marginals_hyperpar_list_spa[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for sp_id"]])) + colnames(marginals_hyperpar_list_spa[[i]]) <- c("x for sp_id", "y for sp_id") + } + + if(i %in% L1_nl_element){ + marginals_hyperpar_list_social_L1_nl[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for inla.group(L1_copy)"]])) + colnames(marginals_hyperpar_list_social_L1_nl[[i]]) <- c("x for inla.group(L1_copy)", "y for inla.group(L1_copy)") + } + + if(i %in% L2_prop_nl_element){ + marginals_hyperpar_list_social_L2_prop_nl[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for inla.group(L2_copy)"]])) + colnames(marginals_hyperpar_list_social_L2_prop_nl[[i]]) <- c("x for inla.group(L2_copy)", "y for inla.group(L2_copy)") + } + + if(i %in% phylogenetic_element){ + summary_random_list_phy[[i]] <- cbind(result[[i]]$summary.random$phy_id) %>% + rename(phy_id = ID) %>% + as.data.frame() %>% + mutate(across(where(is.numeric), round, 2)) + } + + if(i %in% spatial_element){ + summary_random_list_spa[[i]] <- cbind(result[[i]]$summary.random$sp_id) %>% + rename(sp_id = ID) %>% + as.data.frame() %>% + mutate(across(where(is.numeric), round, 2)) + } +} + +#beepr::beep(5) + +save(result, file = "output_models_reduced/models_Boundness_social_0.01.RData") + +coefm <- as.data.frame(cbind(predterms_short, coefm)) +colnames(coefm) <- c("model", "WAIC") +coefm <- coefm %>% + mutate(across(.cols=2, as.numeric)) %>% + mutate(across(where(is.numeric), round, 2)) %>% + arrange(WAIC) + +coefm$WAIC <- as.numeric(coefm$WAIC) +coefm <- coefm[order(coefm$WAIC),] + +coefm_path <- paste("output_tables_reduced/", "waics", "Boundness_social_models", "prior_0.01", ".csv", collapse = "") +write.csv(coefm, coefm_path, row.names=FALSE) + + +phy_effects<-as.data.frame(phy_effects_matrix) +spa_effects<-as.data.frame(spa_effects_matrix) +intercept_effects <- as.data.frame(intercept_matrix) +L1_effects <- as.data.frame(social_effects_matrix_L1) +L1_nl_effects <- as.data.frame(social_effects_matrix_L1_nl) +L2_prop_effects <- as.data.frame(social_effects_matrix_L2_prop) +L2_prop_nl_effects <- as.data.frame(social_effects_matrix_L2_prop_nl) +N_effects<-as.data.frame(social_effects_matrix_N) +E_effects<-as.data.frame(social_effects_matrix_E) +O_effects<-as.data.frame(social_effects_matrix_O) + +phy_effects$effect <- "phylogenetic SD" +spa_effects$effect <- "spatial SD" +intercept_effects$effect <- "Intercept" +L1_effects$effect <- "L1" +L1_nl_effects$effect <- "social SD:\nL1" +L2_prop_effects$effect <- "L2 proportion" +L2_prop_nl_effects$effect <- "social SD:\nL2 proportion" +N_effects$effect <- "Neighbours" +E_effects$effect <- "Education" +O_effects$effect <- "Official status" + +effs <- as.data.frame(rbind(phy_effects, spa_effects, intercept_effects, L1_effects, L1_nl_effects, L2_prop_effects, L2_prop_nl_effects, N_effects, O_effects, E_effects)) +effs <- effs %>% + mutate(across(.cols=c(1:3, 5), as.numeric)) %>% + mutate(across(where(is.numeric), round, 2)) %>% + na.omit() %>% + arrange(WAIC) %>% + relocate(model) + +effs_path <- paste("output_tables_reduced/", "effects", "Boundness_social_models", "prior_0.01", ".csv", collapse = "") +write.csv(effs, effs_path, row.names=FALSE) diff --git a/101/replication_package/sensitivity_testing_reduced_B_05.R b/101/replication_package/sensitivity_testing_reduced_B_05.R new file mode 100644 index 0000000000000000000000000000000000000000..130953726bbd8c3901007015f775654fd0d3b10f --- /dev/null +++ b/101/replication_package/sensitivity_testing_reduced_B_05.R @@ -0,0 +1,423 @@ +#model fitting: Boundness predicted by social effects on top of random phylogenetic and spatial factors + +source("requirements.R") + +source("install_and_load_INLA.R") + +source("set_up_inla.R") + +metrics_joined <- metrics_joined %>% + filter(!is.na(L1_log10_st)) %>% + rename(L1_log_st = L1_log10_st) %>% + mutate(L1_copy = L1_log_st) %>% + filter(!is.na(L2_prop)) %>% + mutate(L2_copy = L2_prop) %>% + filter(!is.na(neighboring_languages_st)) %>% + filter(!is.na(Official)) %>% + filter(!is.na(Education)) %>% + filter(!is.na(boundness_st)) %>% + filter(!is.na(informativity_st)) + +#dropping tips not in Grambank +metrics_joined <- metrics_joined[metrics_joined$Language_ID %in% tree$tip.label, ] +tree <- keep.tip(tree, metrics_joined$Language_ID) + +x <- assert_that(all(tree$tip.label %in% metrics_joined$Language_ID), msg = "The data and phylogeny taxa do not match") + +## Building standardized phylogenetic precision matrix +tree_scaled <- tree + +tree_vcv = vcv.phylo(tree_scaled) +typical_phylogenetic_variance = exp(mean(log(diag(tree_vcv)))) + +tree_scaled$edge.length <- tree_scaled$edge.length/typical_phylogenetic_variance +phylo_prec_mat <- MCMCglmm::inverseA(tree_scaled, + nodes = "ALL", + scale = FALSE)$Ainv + +metrics_joined = metrics_joined[order(match(metrics_joined$Language_ID, rownames(phylo_prec_mat))),] + +#"local" set of parameters +## Create spatial covariance matrix using the matern covariance function +spatial_covar_mat_1 = varcov.spatial(metrics_joined[,c("Longitude", "Latitude")], + cov.pars = phi_1, kappa = kappa)$varcov +# Calculate and standardize by the typical variance +typical_variance_spatial_1 = exp(mean(log(diag(spatial_covar_mat_1)))) +spatial_cov_std_1 = spatial_covar_mat_1 / typical_variance_spatial_1 +spatial_prec_mat_1 = solve(spatial_cov_std_1) +dimnames(spatial_prec_mat_1) = list(metrics_joined$Language_ID, metrics_joined$Language_ID) + +## Since we are using a sparse phylogenetic matrix, we are matching taxa to rows in the matrix +phy_id = match(tree$tip.label, rownames(phylo_prec_mat)) +metrics_joined$phy_id = phy_id + +## Other effects are in the same order they appear in the dataset +metrics_joined$sp_id = 1:nrow(spatial_prec_mat_1) + +pcprior_hyper_0.5 = list(prec =list(prior="pc.prec", param = c(1, 0.5))) + +#Preparing the formulas for 10 competing models to be used in inla() call +listcombo <- list( + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.5)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.5)", "L1_log_st"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.5)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.5)", "f(inla.group(L1_copy), model='rw2', scale.model = TRUE)"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.5)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.5)", "L2_prop"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.5)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.5)", "f(inla.group(L2_copy), model='rw2', scale.model = TRUE)"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.5)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.5)", "f(inla.group(L1_copy), model='rw2', scale.model = TRUE)", "f(inla.group(L2_copy), model='rw2', scale.model = TRUE)"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.5)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.5)", "L1_log_st", "L2_prop"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.5)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.5)", "neighboring_languages_st"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.5)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.5)", "Official"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.5)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.5)", "Education")) + + +predterms <- lapply(listcombo, function(x) paste(x, collapse="+")) + +predterms <- t(as.data.frame(predterms)) + +predterms_short <- predterms + +predterms_short <- gsub("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.5)", "Phylogenetic", predterms_short, fixed=TRUE) +predterms_short <- gsub("f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.5)", "Spatial: local", predterms_short, fixed=TRUE) + +predterms_short <- gsub("f(inla.group(L1_copy), model='rw2', scale.model = TRUE)", "L1 speakers (nonlinear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("L1_log_st", "L1 speakers (linear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("f(inla.group(L2_copy), model='rw2', scale.model = TRUE)", "L2 proportion (nonlinear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("L2_prop", "L2 proportion (linear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("neighboring_languages_st", "Neighbours", predterms_short, fixed=TRUE) + + + +phylogenetic_element <- data.frame("judgement" = grepl("Phylogenetic", predterms_short), + number = 1:length(predterms_short)) +phylogenetic_element <- phylogenetic_element[phylogenetic_element$judgement == TRUE,]$number + +spatial_element_local <- data.frame("judgement" = grepl("local", predterms_short), + number = 1:length(predterms_short)) +spatial_element_local <- spatial_element_local[spatial_element_local$judgement == TRUE,]$number + +spatial_element_regional <- data.frame("judgement" = grepl("regional", predterms_short), + number = 1:length(predterms_short)) +spatial_element_regional <- spatial_element_regional[spatial_element_regional$judgement == TRUE,]$number + +spatial_element <- c(spatial_element_local, spatial_element_regional) + +L1_element <- data.frame("judgement" = grepl("L1 speakers (linear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L1_element <- L1_element[L1_element$judgement == TRUE,]$number + + +L1_nl_element <- data.frame("judgement" = grepl("L1 speakers (nonlinear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L1_nl_element <- L1_nl_element[L1_nl_element$judgement == TRUE,]$number + +L2_prop_element <- data.frame("judgement" = grepl("L2 proportion (linear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L2_prop_element <- L2_prop_element[L2_prop_element$judgement == TRUE,]$number + +L2_prop_nl_element <- data.frame("judgement" = grepl("L2 proportion (nonlinear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L2_prop_nl_element <- L2_prop_nl_element[L2_prop_nl_element$judgement == TRUE,]$number + +neighbour_element <- data.frame("judgement" = grepl("Neighbours", predterms_short), + number = 1:length(predterms_short)) +neighbour_element <- neighbour_element[neighbour_element$judgement == TRUE,]$number + +official_element <- data.frame("judgement" = grepl("Official", predterms_short), + number = 1:length(predterms_short)) +official_element <- official_element[official_element$judgement == TRUE,]$number + +education_element <- data.frame("judgement" = grepl("Education", predterms_short), + number = 1:length(predterms_short)) +education_element <- education_element[education_element$judgement == TRUE,]$number + +models_number <- length(predterms_short) + +#preparing empty matrices to be filled with effect estimates (quantiles), model name, and WAIC value +phy_effects_matrix <- matrix(NA, models_number, 5) +colnames(phy_effects_matrix) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +spa_effects_matrix <- matrix(NA, models_number, 5) +colnames(spa_effects_matrix) <- c("2.5%", "50%", "97.5%", "model", "WAIC") + +intercept_matrix <- matrix(NA, models_number, 5) +colnames(intercept_matrix) <- c("2.5%", "50%", "97.5%", "model", "WAIC") + +social_effects_matrix_L1 <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_L1) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L1_nl <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_L1_nl) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L2_prop <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_L2_prop) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L2_prop_nl <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_L2_prop_nl) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_N <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_N) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_O <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_O) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_E <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_E) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L1_L2_prop <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_L1_L2_prop) <- c("2.5%", "50%", "97.5%", "model", "WAIC") + +#fitted values +fitted_list <- vector("list", models_number) +names(fitted_list) <- predterms_short + +#marginals of hyperparameters +marginals_hyperpar_list_gaussian <- vector("list", models_number) +names(marginals_hyperpar_list_gaussian) <- predterms_short + +marginals_hyperpar_list_phy <- vector("list", models_number) +names(marginals_hyperpar_list_phy) <- predterms_short + +marginals_hyperpar_list_spa <- vector("list", models_number) +names(marginals_hyperpar_list_spa) <- predterms_short + +marginals_hyperpar_list_social_L1_nl <- vector("list", models_number) +names(marginals_hyperpar_list_social_L1_nl) <- predterms_short + +marginals_hyperpar_list_social_L2_prop_nl <- vector("list", models_number) +names(marginals_hyperpar_list_social_L2_prop_nl) <- predterms_short + + +#marginals of fixed effects +marginals_fixed_list_Intercept <- vector("list", models_number) +names(marginals_fixed_list_Intercept) <- predterms_short + +marginals_fixed_list_L1 <- vector("list", models_number) +names(marginals_fixed_list_L1) <- predterms_short + +marginals_fixed_list_L2_prop <- vector("list", models_number) +names(marginals_fixed_list_L2_prop) <- predterms_short + +marginals_fixed_list_O <- vector("list", models_number) +names(marginals_fixed_list_O) <- predterms_short + +marginals_fixed_list_N <- vector("list", models_number) +names(marginals_fixed_list_N) <- predterms_short + +marginals_fixed_list_E <- vector("list", models_number) +names(marginals_fixed_list_E) <- predterms_short + +marginals_fixed_list_L1_L2_prop <- vector("list", models_number) +names(marginals_fixed_list_L1_L2_prop) <- predterms_short + + + + +#summary statistics of random effects +summary_random_list_phy <- vector("list", models_number) +names(summary_random_list_phy) <- predterms_short + +summary_random_list_spa <- vector("list", models_number) +names(summary_random_list_spa) <- predterms_short + +summary_random_list_social_L1_nl <- vector("list", models_number) +names(summary_random_list_social_L1_nl) <- predterms_short + +summary_random_list_social_L2_prop_nl <- vector("list", models_number) +names(summary_random_list_social_L2_prop_nl) <- predterms_short + + +coefm <- matrix(NA,models_number,1) +result <- vector("list",models_number) + +for(i in 1:models_number){ + formula <- as.formula(paste("boundness_st ~ ",predterms[[i]])) + result[[i]] <- inla(formula, family="gaussian", + control.family = list(hyper = pcprior_hyper_0.5), + #control.inla = list(tolerance = 1e-8, h = 0.0001), + #tolerance: the tolerance for the optimisation of the hyperparameters + #h: the step-length for the gradient calculations for the hyperparameters. + data=metrics_joined, control.compute=list(waic=TRUE)) + + coefm[i,1] <- round(result[[i]]$waic$waic, 2) + + intercept_matrix[i, 1:3] <- c(result[[i]]$summary.fixed[1,]$`0.025quant`, result[[i]]$summary.fixed[1,]$`0.5quant`, result[[i]]$summary.fixed[1,]$`0.975quant`) + intercept_matrix[i, 4] <- predterms_short[[i]] + intercept_matrix[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_Intercept[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["(Intercept)"]])) + colnames(marginals_fixed_list_Intercept[[i]]) <- c("x for Intercept", "y for Intercept") + + if(i %in% phylogenetic_element) { + phy_effects_matrix[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for phy_id`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + phy_effects_matrix[i, 4] <- predterms_short[[i]] + phy_effects_matrix[i, 5] <- result[[i]]$waic$waic + } + + if(i %in% spatial_element) { + spa_effects_matrix[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for sp_id`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + spa_effects_matrix[i, 4] <- predterms_short[[i]] + spa_effects_matrix[i, 5] <- result[[i]]$waic$waic + } + + + if(i %in% L1_nl_element){ + social_effects_matrix_L1_nl[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for inla.group(L1_copy)`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + social_effects_matrix_L1_nl[i, 4] <- predterms_short[[i]] + social_effects_matrix_L1_nl[i, 5] <- result[[i]]$waic$waic + } + + if(i %in% L2_prop_nl_element){ + social_effects_matrix_L2_prop_nl[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for inla.group(L2_copy)`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + social_effects_matrix_L2_prop_nl[i, 4] <- predterms_short[[i]] + social_effects_matrix_L2_prop_nl[i, 5] <- result[[i]]$waic$waic + } + + if(i %in% L1_element) { + social_effects_matrix_L1[i, 1:3] <- c(result[[i]]$summary.fixed["L1_log_st",]$`0.025quant`, result[[i]]$summary.fixed["L1_log_st",]$`0.5quant`, result[[i]]$summary.fixed["L1_log_st",]$`0.975quant`) + social_effects_matrix_L1[i, 4] <- predterms_short[[i]] + social_effects_matrix_L1[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_L1[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["L1_log_st"]])) + colnames(marginals_fixed_list_L1[[i]]) <- c("x for L1", "y for L1") + } + + if(i %in% L2_prop_element) { + social_effects_matrix_L2_prop[i, 1:3] <- c(result[[i]]$summary.fixed["L2_prop",]$`0.025quant`, result[[i]]$summary.fixed["L2_prop",]$`0.5quant`, result[[i]]$summary.fixed["L2_prop",]$`0.975quant`) + social_effects_matrix_L2_prop[i, 4] <- predterms_short[[i]] + social_effects_matrix_L2_prop[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_L2_prop[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["L2_prop"]])) + colnames(marginals_fixed_list_L2_prop[[i]]) <- c("x for L2 proportion", "y for L2 proportion") + } + + if(i %in% neighbour_element) { + social_effects_matrix_N[i, 1:3] <- c(result[[i]]$summary.fixed[2,]$`0.025quant`, result[[i]]$summary.fixed[2,]$`0.5quant`, result[[i]]$summary.fixed[2,]$`0.975quant`) + social_effects_matrix_N[i, 4] <- predterms_short[[i]] + social_effects_matrix_N[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_N[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][[2]])) + colnames(marginals_fixed_list_N[[i]]) <- c("x for Neighbours", "y for Neighbours") + } + + if(i %in% official_element) { + social_effects_matrix_O[i, 1:3] <- c(result[[i]]$summary.fixed[2,]$`0.025quant`, result[[i]]$summary.fixed[2,]$`0.5quant`, result[[i]]$summary.fixed[2,]$`0.975quant`) + social_effects_matrix_O[i, 4] <- predterms_short[[i]] + social_effects_matrix_O[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_O[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][[2]])) + colnames(marginals_fixed_list_O[[i]]) <- c("x for Official", "y for Official") + } + + if(i %in% education_element) { + social_effects_matrix_E[i, 1:3] <- c(result[[i]]$summary.fixed[2,]$`0.025quant`, result[[i]]$summary.fixed[2,]$`0.5quant`, result[[i]]$summary.fixed[2,]$`0.975quant`) + social_effects_matrix_E[i, 4] <- predterms_short[[i]] + social_effects_matrix_E[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_E[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][[2]])) + colnames(marginals_fixed_list_E[[i]]) <- c("x for Education", "y for Education") + } + + fitted_list[[i]] <- result[[i]]$summary.fitted.values + fitted_list[[i]] <- fitted_list[[i]] %>% + mutate(across(where(is.numeric), round, 2)) + + marginals_hyperpar_list_gaussian[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for the Gaussian observations"]])) + colnames(marginals_hyperpar_list_gaussian[[i]]) <- c("x for the Gaussian observations", "y for the Gaussian observations") + + if(i %in% phylogenetic_element){ + marginals_hyperpar_list_phy[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for phy_id"]])) + colnames(marginals_hyperpar_list_phy[[i]]) <- c("x for phy_id", "y for phy_id") + } + + if(i %in% spatial_element){ + marginals_hyperpar_list_spa[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for sp_id"]])) + colnames(marginals_hyperpar_list_spa[[i]]) <- c("x for sp_id", "y for sp_id") + } + + if(i %in% L1_nl_element){ + marginals_hyperpar_list_social_L1_nl[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for inla.group(L1_copy)"]])) + colnames(marginals_hyperpar_list_social_L1_nl[[i]]) <- c("x for inla.group(L1_copy)", "y for inla.group(L1_copy)") + } + + if(i %in% L2_prop_nl_element){ + marginals_hyperpar_list_social_L2_prop_nl[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for inla.group(L2_copy)"]])) + colnames(marginals_hyperpar_list_social_L2_prop_nl[[i]]) <- c("x for inla.group(L2_copy)", "y for inla.group(L2_copy)") + } + + if(i %in% phylogenetic_element){ + summary_random_list_phy[[i]] <- cbind(result[[i]]$summary.random$phy_id) %>% + rename(phy_id = ID) %>% + as.data.frame() %>% + mutate(across(where(is.numeric), round, 2)) + } + + if(i %in% spatial_element){ + summary_random_list_spa[[i]] <- cbind(result[[i]]$summary.random$sp_id) %>% + rename(sp_id = ID) %>% + as.data.frame() %>% + mutate(across(where(is.numeric), round, 2)) + } +} + +#beepr::beep(5) + +save(result, file = "output_models_reduced/models_Boundness_social_0.5.RData") + + +coefm <- as.data.frame(cbind(predterms_short, coefm)) +colnames(coefm) <- c("model", "WAIC") +coefm <- coefm %>% + mutate(across(.cols=2, as.numeric)) %>% + mutate(across(where(is.numeric), round, 2)) %>% + arrange(WAIC) + +coefm$WAIC <- as.numeric(coefm$WAIC) +coefm <- coefm[order(coefm$WAIC),] + +coefm_path <- paste("output_tables_reduced/", "waics", "Boundness_social_models", "prior_0.5", ".csv", collapse = "") +write.csv(coefm, coefm_path, row.names=FALSE) + + +phy_effects<-as.data.frame(phy_effects_matrix) +spa_effects<-as.data.frame(spa_effects_matrix) +intercept_effects <- as.data.frame(intercept_matrix) +L1_effects <- as.data.frame(social_effects_matrix_L1) +L1_nl_effects <- as.data.frame(social_effects_matrix_L1_nl) +L2_prop_effects <- as.data.frame(social_effects_matrix_L2_prop) +L2_prop_nl_effects <- as.data.frame(social_effects_matrix_L2_prop_nl) +N_effects<-as.data.frame(social_effects_matrix_N) +E_effects<-as.data.frame(social_effects_matrix_E) +O_effects<-as.data.frame(social_effects_matrix_O) + +phy_effects$effect <- "phylogenetic SD" +spa_effects$effect <- "spatial SD" +intercept_effects$effect <- "Intercept" +L1_effects$effect <- "L1" +L1_nl_effects$effect <- "social SD:\nL1" +L2_prop_effects$effect <- "L2 proportion" +L2_prop_nl_effects$effect <- "social SD:\nL2 proportion" +N_effects$effect <- "Neighbours" +E_effects$effect <- "Education" +O_effects$effect <- "Official status" + +effs <- as.data.frame(rbind(phy_effects, spa_effects, intercept_effects, L1_effects, L1_nl_effects, L2_prop_effects, L2_prop_nl_effects, N_effects, O_effects, E_effects)) +effs <- effs %>% + mutate(across(.cols=c(1:3, 5), as.numeric)) %>% + mutate(across(where(is.numeric), round, 2)) %>% + na.omit() %>% + arrange(WAIC) %>% + relocate(model) + +effs_path <- paste("output_tables_reduced/", "effects", "Boundness_social_models", "prior_0.5", ".csv", collapse = "") +write.csv(effs, effs_path, row.names=FALSE) diff --git a/101/replication_package/sensitivity_testing_reduced_B_099.R b/101/replication_package/sensitivity_testing_reduced_B_099.R new file mode 100644 index 0000000000000000000000000000000000000000..949d60a1e2c2545a641470d477f1e93a44b8aae6 --- /dev/null +++ b/101/replication_package/sensitivity_testing_reduced_B_099.R @@ -0,0 +1,423 @@ +#model fitting: Boundness predicted by social effects on top of random phylogenetic and spatial factors + +source("requirements.R") + +source("install_and_load_INLA.R") + +source("set_up_inla.R") + +metrics_joined <- metrics_joined %>% + filter(!is.na(L1_log10_st)) %>% + rename(L1_log_st = L1_log10_st) %>% + mutate(L1_copy = L1_log_st) %>% + filter(!is.na(L2_prop)) %>% + mutate(L2_copy = L2_prop) %>% + filter(!is.na(neighboring_languages_st)) %>% + filter(!is.na(Official)) %>% + filter(!is.na(Education)) %>% + filter(!is.na(boundness_st)) %>% + filter(!is.na(informativity_st)) + +#dropping tips not in Grambank +metrics_joined <- metrics_joined[metrics_joined$Language_ID %in% tree$tip.label, ] +tree <- keep.tip(tree, metrics_joined$Language_ID) + +x <- assert_that(all(tree$tip.label %in% metrics_joined$Language_ID), msg = "The data and phylogeny taxa do not match") + +## Building standardized phylogenetic precision matrix +tree_scaled <- tree + +tree_vcv = vcv.phylo(tree_scaled) +typical_phylogenetic_variance = exp(mean(log(diag(tree_vcv)))) + +tree_scaled$edge.length <- tree_scaled$edge.length/typical_phylogenetic_variance +phylo_prec_mat <- MCMCglmm::inverseA(tree_scaled, + nodes = "ALL", + scale = FALSE)$Ainv + +metrics_joined = metrics_joined[order(match(metrics_joined$Language_ID, rownames(phylo_prec_mat))),] + +#"local" set of parameters +## Create spatial covariance matrix using the matern covariance function +spatial_covar_mat_1 = varcov.spatial(metrics_joined[,c("Longitude", "Latitude")], + cov.pars = phi_1, kappa = kappa)$varcov +# Calculate and standardize by the typical variance +typical_variance_spatial_1 = exp(mean(log(diag(spatial_covar_mat_1)))) +spatial_cov_std_1 = spatial_covar_mat_1 / typical_variance_spatial_1 +spatial_prec_mat_1 = solve(spatial_cov_std_1) +dimnames(spatial_prec_mat_1) = list(metrics_joined$Language_ID, metrics_joined$Language_ID) + +## Since we are using a sparse phylogenetic matrix, we are matching taxa to rows in the matrix +phy_id = match(tree$tip.label, rownames(phylo_prec_mat)) +metrics_joined$phy_id = phy_id + +## Other effects are in the same order they appear in the dataset +metrics_joined$sp_id = 1:nrow(spatial_prec_mat_1) + +pcprior_hyper_0.99 = list(prec =list(prior="pc.prec", param = c(1, 0.99))) + +#Preparing the formulas for 10 competing models to be used in inla() call +listcombo <- list( + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.99)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.99)", "L1_log_st"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.99)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.99)", "f(inla.group(L1_copy), model='rw2', scale.model = TRUE)"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.99)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.99)", "L2_prop"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.99)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.99)", "f(inla.group(L2_copy), model='rw2', scale.model = TRUE)"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.99)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.99)", "f(inla.group(L1_copy), model='rw2', scale.model = TRUE)", "f(inla.group(L2_copy), model='rw2', scale.model = TRUE)"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.99)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.99)", "L1_log_st", "L2_prop"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.99)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.99)", "neighboring_languages_st"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.99)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.99)", "Official"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.99)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.99)", "Education")) + + +predterms <- lapply(listcombo, function(x) paste(x, collapse="+")) + +predterms <- t(as.data.frame(predterms)) + +predterms_short <- predterms + +predterms_short <- gsub("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.99)", "Phylogenetic", predterms_short, fixed=TRUE) +predterms_short <- gsub("f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.99)", "Spatial: local", predterms_short, fixed=TRUE) + +predterms_short <- gsub("f(inla.group(L1_copy), model='rw2', scale.model = TRUE)", "L1 speakers (nonlinear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("L1_log_st", "L1 speakers (linear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("f(inla.group(L2_copy), model='rw2', scale.model = TRUE)", "L2 proportion (nonlinear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("L2_prop", "L2 proportion (linear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("neighboring_languages_st", "Neighbours", predterms_short, fixed=TRUE) + + + +phylogenetic_element <- data.frame("judgement" = grepl("Phylogenetic", predterms_short), + number = 1:length(predterms_short)) +phylogenetic_element <- phylogenetic_element[phylogenetic_element$judgement == TRUE,]$number + +spatial_element_local <- data.frame("judgement" = grepl("local", predterms_short), + number = 1:length(predterms_short)) +spatial_element_local <- spatial_element_local[spatial_element_local$judgement == TRUE,]$number + +spatial_element_regional <- data.frame("judgement" = grepl("regional", predterms_short), + number = 1:length(predterms_short)) +spatial_element_regional <- spatial_element_regional[spatial_element_regional$judgement == TRUE,]$number + +spatial_element <- c(spatial_element_local, spatial_element_regional) + +L1_element <- data.frame("judgement" = grepl("L1 speakers (linear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L1_element <- L1_element[L1_element$judgement == TRUE,]$number + + +L1_nl_element <- data.frame("judgement" = grepl("L1 speakers (nonlinear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L1_nl_element <- L1_nl_element[L1_nl_element$judgement == TRUE,]$number + +L2_prop_element <- data.frame("judgement" = grepl("L2 proportion (linear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L2_prop_element <- L2_prop_element[L2_prop_element$judgement == TRUE,]$number + +L2_prop_nl_element <- data.frame("judgement" = grepl("L2 proportion (nonlinear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L2_prop_nl_element <- L2_prop_nl_element[L2_prop_nl_element$judgement == TRUE,]$number + +neighbour_element <- data.frame("judgement" = grepl("Neighbours", predterms_short), + number = 1:length(predterms_short)) +neighbour_element <- neighbour_element[neighbour_element$judgement == TRUE,]$number + +official_element <- data.frame("judgement" = grepl("Official", predterms_short), + number = 1:length(predterms_short)) +official_element <- official_element[official_element$judgement == TRUE,]$number + +education_element <- data.frame("judgement" = grepl("Education", predterms_short), + number = 1:length(predterms_short)) +education_element <- education_element[education_element$judgement == TRUE,]$number + +models_number <- length(predterms_short) + +#preparing empty matrices to be filled with effect estimates (quantiles), model name, and WAIC value +phy_effects_matrix <- matrix(NA, models_number, 5) +colnames(phy_effects_matrix) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +spa_effects_matrix <- matrix(NA, models_number, 5) +colnames(spa_effects_matrix) <- c("2.5%", "50%", "97.5%", "model", "WAIC") + +intercept_matrix <- matrix(NA, models_number, 5) +colnames(intercept_matrix) <- c("2.5%", "50%", "97.5%", "model", "WAIC") + +social_effects_matrix_L1 <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_L1) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L1_nl <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_L1_nl) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L2_prop <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_L2_prop) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L2_prop_nl <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_L2_prop_nl) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_N <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_N) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_O <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_O) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_E <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_E) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L1_L2_prop <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_L1_L2_prop) <- c("2.5%", "50%", "97.5%", "model", "WAIC") + +#fitted values +fitted_list <- vector("list", models_number) +names(fitted_list) <- predterms_short + +#marginals of hyperparameters +marginals_hyperpar_list_gaussian <- vector("list", models_number) +names(marginals_hyperpar_list_gaussian) <- predterms_short + +marginals_hyperpar_list_phy <- vector("list", models_number) +names(marginals_hyperpar_list_phy) <- predterms_short + +marginals_hyperpar_list_spa <- vector("list", models_number) +names(marginals_hyperpar_list_spa) <- predterms_short + +marginals_hyperpar_list_social_L1_nl <- vector("list", models_number) +names(marginals_hyperpar_list_social_L1_nl) <- predterms_short + +marginals_hyperpar_list_social_L2_prop_nl <- vector("list", models_number) +names(marginals_hyperpar_list_social_L2_prop_nl) <- predterms_short + + +#marginals of fixed effects +marginals_fixed_list_Intercept <- vector("list", models_number) +names(marginals_fixed_list_Intercept) <- predterms_short + +marginals_fixed_list_L1 <- vector("list", models_number) +names(marginals_fixed_list_L1) <- predterms_short + +marginals_fixed_list_L2_prop <- vector("list", models_number) +names(marginals_fixed_list_L2_prop) <- predterms_short + +marginals_fixed_list_O <- vector("list", models_number) +names(marginals_fixed_list_O) <- predterms_short + +marginals_fixed_list_N <- vector("list", models_number) +names(marginals_fixed_list_N) <- predterms_short + +marginals_fixed_list_E <- vector("list", models_number) +names(marginals_fixed_list_E) <- predterms_short + +marginals_fixed_list_L1_L2_prop <- vector("list", models_number) +names(marginals_fixed_list_L1_L2_prop) <- predterms_short + + + + +#summary statistics of random effects +summary_random_list_phy <- vector("list", models_number) +names(summary_random_list_phy) <- predterms_short + +summary_random_list_spa <- vector("list", models_number) +names(summary_random_list_spa) <- predterms_short + +summary_random_list_social_L1_nl <- vector("list", models_number) +names(summary_random_list_social_L1_nl) <- predterms_short + +summary_random_list_social_L2_prop_nl <- vector("list", models_number) +names(summary_random_list_social_L2_prop_nl) <- predterms_short + + +coefm <- matrix(NA,models_number,1) +result <- vector("list",models_number) + +for(i in 1:models_number){ + formula <- as.formula(paste("boundness_st ~ ",predterms[[i]])) + result[[i]] <- inla(formula, family="gaussian", + control.family = list(hyper = pcprior_hyper_0.99), + #control.inla = list(tolerance = 1e-8, h = 0.0001), + #tolerance: the tolerance for the optimisation of the hyperparameters + #h: the step-length for the gradient calculations for the hyperparameters. + data=metrics_joined, control.compute=list(waic=TRUE)) + + coefm[i,1] <- round(result[[i]]$waic$waic, 2) + + intercept_matrix[i, 1:3] <- c(result[[i]]$summary.fixed[1,]$`0.025quant`, result[[i]]$summary.fixed[1,]$`0.5quant`, result[[i]]$summary.fixed[1,]$`0.975quant`) + intercept_matrix[i, 4] <- predterms_short[[i]] + intercept_matrix[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_Intercept[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["(Intercept)"]])) + colnames(marginals_fixed_list_Intercept[[i]]) <- c("x for Intercept", "y for Intercept") + + if(i %in% phylogenetic_element) { + phy_effects_matrix[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for phy_id`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + phy_effects_matrix[i, 4] <- predterms_short[[i]] + phy_effects_matrix[i, 5] <- result[[i]]$waic$waic + } + + if(i %in% spatial_element) { + spa_effects_matrix[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for sp_id`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + spa_effects_matrix[i, 4] <- predterms_short[[i]] + spa_effects_matrix[i, 5] <- result[[i]]$waic$waic + } + + + if(i %in% L1_nl_element){ + social_effects_matrix_L1_nl[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for inla.group(L1_copy)`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + social_effects_matrix_L1_nl[i, 4] <- predterms_short[[i]] + social_effects_matrix_L1_nl[i, 5] <- result[[i]]$waic$waic + } + + if(i %in% L2_prop_nl_element){ + social_effects_matrix_L2_prop_nl[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for inla.group(L2_copy)`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + social_effects_matrix_L2_prop_nl[i, 4] <- predterms_short[[i]] + social_effects_matrix_L2_prop_nl[i, 5] <- result[[i]]$waic$waic + } + + if(i %in% L1_element) { + social_effects_matrix_L1[i, 1:3] <- c(result[[i]]$summary.fixed["L1_log_st",]$`0.025quant`, result[[i]]$summary.fixed["L1_log_st",]$`0.5quant`, result[[i]]$summary.fixed["L1_log_st",]$`0.975quant`) + social_effects_matrix_L1[i, 4] <- predterms_short[[i]] + social_effects_matrix_L1[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_L1[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["L1_log_st"]])) + colnames(marginals_fixed_list_L1[[i]]) <- c("x for L1", "y for L1") + } + + if(i %in% L2_prop_element) { + social_effects_matrix_L2_prop[i, 1:3] <- c(result[[i]]$summary.fixed["L2_prop",]$`0.025quant`, result[[i]]$summary.fixed["L2_prop",]$`0.5quant`, result[[i]]$summary.fixed["L2_prop",]$`0.975quant`) + social_effects_matrix_L2_prop[i, 4] <- predterms_short[[i]] + social_effects_matrix_L2_prop[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_L2_prop[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["L2_prop"]])) + colnames(marginals_fixed_list_L2_prop[[i]]) <- c("x for L2 proportion", "y for L2 proportion") + } + + if(i %in% neighbour_element) { + social_effects_matrix_N[i, 1:3] <- c(result[[i]]$summary.fixed[2,]$`0.025quant`, result[[i]]$summary.fixed[2,]$`0.5quant`, result[[i]]$summary.fixed[2,]$`0.975quant`) + social_effects_matrix_N[i, 4] <- predterms_short[[i]] + social_effects_matrix_N[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_N[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][[2]])) + colnames(marginals_fixed_list_N[[i]]) <- c("x for Neighbours", "y for Neighbours") + } + + if(i %in% official_element) { + social_effects_matrix_O[i, 1:3] <- c(result[[i]]$summary.fixed[2,]$`0.025quant`, result[[i]]$summary.fixed[2,]$`0.5quant`, result[[i]]$summary.fixed[2,]$`0.975quant`) + social_effects_matrix_O[i, 4] <- predterms_short[[i]] + social_effects_matrix_O[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_O[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][[2]])) + colnames(marginals_fixed_list_O[[i]]) <- c("x for Official", "y for Official") + } + + if(i %in% education_element) { + social_effects_matrix_E[i, 1:3] <- c(result[[i]]$summary.fixed[2,]$`0.025quant`, result[[i]]$summary.fixed[2,]$`0.5quant`, result[[i]]$summary.fixed[2,]$`0.975quant`) + social_effects_matrix_E[i, 4] <- predterms_short[[i]] + social_effects_matrix_E[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_E[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][[2]])) + colnames(marginals_fixed_list_E[[i]]) <- c("x for Education", "y for Education") + } + + fitted_list[[i]] <- result[[i]]$summary.fitted.values + fitted_list[[i]] <- fitted_list[[i]] %>% + mutate(across(where(is.numeric), round, 2)) + + marginals_hyperpar_list_gaussian[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for the Gaussian observations"]])) + colnames(marginals_hyperpar_list_gaussian[[i]]) <- c("x for the Gaussian observations", "y for the Gaussian observations") + + if(i %in% phylogenetic_element){ + marginals_hyperpar_list_phy[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for phy_id"]])) + colnames(marginals_hyperpar_list_phy[[i]]) <- c("x for phy_id", "y for phy_id") + } + + if(i %in% spatial_element){ + marginals_hyperpar_list_spa[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for sp_id"]])) + colnames(marginals_hyperpar_list_spa[[i]]) <- c("x for sp_id", "y for sp_id") + } + + if(i %in% L1_nl_element){ + marginals_hyperpar_list_social_L1_nl[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for inla.group(L1_copy)"]])) + colnames(marginals_hyperpar_list_social_L1_nl[[i]]) <- c("x for inla.group(L1_copy)", "y for inla.group(L1_copy)") + } + + if(i %in% L2_prop_nl_element){ + marginals_hyperpar_list_social_L2_prop_nl[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for inla.group(L2_copy)"]])) + colnames(marginals_hyperpar_list_social_L2_prop_nl[[i]]) <- c("x for inla.group(L2_copy)", "y for inla.group(L2_copy)") + } + + if(i %in% phylogenetic_element){ + summary_random_list_phy[[i]] <- cbind(result[[i]]$summary.random$phy_id) %>% + rename(phy_id = ID) %>% + as.data.frame() %>% + mutate(across(where(is.numeric), round, 2)) + } + + if(i %in% spatial_element){ + summary_random_list_spa[[i]] <- cbind(result[[i]]$summary.random$sp_id) %>% + rename(sp_id = ID) %>% + as.data.frame() %>% + mutate(across(where(is.numeric), round, 2)) + } +} + +#beepr::beep(5) + +save(result, file = "output_models_reduced/models_Boundness_social_0.99.RData") + + +coefm <- as.data.frame(cbind(predterms_short, coefm)) +colnames(coefm) <- c("model", "WAIC") +coefm <- coefm %>% + mutate(across(.cols=2, as.numeric)) %>% + mutate(across(where(is.numeric), round, 2)) %>% + arrange(WAIC) + +coefm$WAIC <- as.numeric(coefm$WAIC) +coefm <- coefm[order(coefm$WAIC),] + +coefm_path <- paste("output_tables_reduced/", "waics", "Boundness_social_models", "prior_0.99", ".csv", collapse = "") +write.csv(coefm, coefm_path, row.names=FALSE) + + +phy_effects<-as.data.frame(phy_effects_matrix) +spa_effects<-as.data.frame(spa_effects_matrix) +intercept_effects <- as.data.frame(intercept_matrix) +L1_effects <- as.data.frame(social_effects_matrix_L1) +L1_nl_effects <- as.data.frame(social_effects_matrix_L1_nl) +L2_prop_effects <- as.data.frame(social_effects_matrix_L2_prop) +L2_prop_nl_effects <- as.data.frame(social_effects_matrix_L2_prop_nl) +N_effects<-as.data.frame(social_effects_matrix_N) +E_effects<-as.data.frame(social_effects_matrix_E) +O_effects<-as.data.frame(social_effects_matrix_O) + +phy_effects$effect <- "phylogenetic SD" +spa_effects$effect <- "spatial SD" +intercept_effects$effect <- "Intercept" +L1_effects$effect <- "L1" +L1_nl_effects$effect <- "social SD:\nL1" +L2_prop_effects$effect <- "L2 proportion" +L2_prop_nl_effects$effect <- "social SD:\nL2 proportion" +N_effects$effect <- "Neighbours" +E_effects$effect <- "Education" +O_effects$effect <- "Official status" + +effs <- as.data.frame(rbind(phy_effects, spa_effects, intercept_effects, L1_effects, L1_nl_effects, L2_prop_effects, L2_prop_nl_effects, N_effects, O_effects, E_effects)) +effs <- effs %>% + mutate(across(.cols=c(1:3, 5), as.numeric)) %>% + mutate(across(where(is.numeric), round, 2)) %>% + na.omit() %>% + arrange(WAIC) %>% + relocate(model) + +effs_path <- paste("output_tables_reduced/", "effects", "Boundness_social_models", "prior_0.99", ".csv", collapse = "") +write.csv(effs, effs_path, row.names=FALSE) diff --git a/101/replication_package/sensitivity_testing_reduced_I_001.R b/101/replication_package/sensitivity_testing_reduced_I_001.R new file mode 100644 index 0000000000000000000000000000000000000000..fbb3853ed97d7b711e418d5ae70c6315c0ccd590 --- /dev/null +++ b/101/replication_package/sensitivity_testing_reduced_I_001.R @@ -0,0 +1,422 @@ +#model fitting: Informativity predicted by social effects on top of random phylogenetic and spatial factors + +source("requirements.R") + +source("install_and_load_INLA.R") + +source("set_up_inla.R") + +metrics_joined <- metrics_joined %>% + filter(!is.na(L1_log10_st)) %>% + rename(L1_log_st = L1_log10_st) %>% + mutate(L1_copy = L1_log_st) %>% + filter(!is.na(L2_prop)) %>% + mutate(L2_copy = L2_prop) %>% + filter(!is.na(neighboring_languages_st)) %>% + filter(!is.na(Official)) %>% + filter(!is.na(Education)) %>% + filter(!is.na(boundness_st)) %>% + filter(!is.na(informativity_st)) + +#dropping tips not in Grambank +metrics_joined <- metrics_joined[metrics_joined$Language_ID %in% tree$tip.label, ] +tree <- keep.tip(tree, metrics_joined$Language_ID) + +x <- assert_that(all(tree$tip.label %in% metrics_joined$Language_ID), msg = "The data and phylogeny taxa do not match") + +## Building standardized phylogenetic precision matrix +tree_scaled <- tree + +tree_vcv = vcv.phylo(tree_scaled) +typical_phylogenetic_variance = exp(mean(log(diag(tree_vcv)))) + +tree_scaled$edge.length <- tree_scaled$edge.length/typical_phylogenetic_variance +phylo_prec_mat <- MCMCglmm::inverseA(tree_scaled, + nodes = "ALL", + scale = FALSE)$Ainv + +metrics_joined = metrics_joined[order(match(metrics_joined$Language_ID, rownames(phylo_prec_mat))),] + +#"local" set of parameters +## Create spatial covariance matrix using the matern covariance function +spatial_covar_mat_1 = varcov.spatial(metrics_joined[,c("Longitude", "Latitude")], + cov.pars = phi_1, kappa = kappa)$varcov +# Calculate and standardize by the typical variance +typical_variance_spatial_1 = exp(mean(log(diag(spatial_covar_mat_1)))) +spatial_cov_std_1 = spatial_covar_mat_1 / typical_variance_spatial_1 +spatial_prec_mat_1 = solve(spatial_cov_std_1) +dimnames(spatial_prec_mat_1) = list(metrics_joined$Language_ID, metrics_joined$Language_ID) + +## Since we are using a sparse phylogenetic matrix, we are matching taxa to rows in the matrix +phy_id = match(tree$tip.label, rownames(phylo_prec_mat)) +metrics_joined$phy_id = phy_id + +## Other effects are in the same order they appear in the dataset +metrics_joined$sp_id = 1:nrow(spatial_prec_mat_1) + +pcprior_hyper_0.01 = list(prec =list(prior="pc.prec", param = c(1, 0.01))) + +#Preparing the formulas for 10 competing models to be used in inla() call +listcombo <- list( + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.01)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.01)", "L1_log_st"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.01)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.01)", "f(inla.group(L1_copy), model='rw2', scale.model = TRUE)"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.01)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.01)", "L2_prop"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.01)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.01)", "f(inla.group(L2_copy), model='rw2', scale.model = TRUE)"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.01)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.01)", "f(inla.group(L1_copy), model='rw2', scale.model = TRUE)", "f(inla.group(L2_copy), model='rw2', scale.model = TRUE)"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.01)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.01)", "L1_log_st", "L2_prop"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.01)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.01)", "neighboring_languages_st"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.01)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.01)", "Official"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.01)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.01)", "Education")) + + +predterms <- lapply(listcombo, function(x) paste(x, collapse="+")) + +predterms <- t(as.data.frame(predterms)) + +predterms_short <- predterms +predterms_short <- gsub("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.01)", "Phylogenetic", predterms_short, fixed=TRUE) +predterms_short <- gsub("f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.01)", "Spatial: local", predterms_short, fixed=TRUE) + +predterms_short <- gsub("f(inla.group(L1_copy), model='rw2', scale.model = TRUE)", "L1 speakers (nonlinear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("L1_log_st", "L1 speakers (linear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("f(inla.group(L2_copy), model='rw2', scale.model = TRUE)", "L2 proportion (nonlinear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("L2_prop", "L2 proportion (linear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("neighboring_languages_st", "Neighbours", predterms_short, fixed=TRUE) + + +phylogenetic_element <- data.frame("judgement" = grepl("Phylogenetic", predterms_short), + number = 1:length(predterms_short)) +phylogenetic_element <- phylogenetic_element[phylogenetic_element$judgement == TRUE,]$number + +spatial_element_local <- data.frame("judgement" = grepl("local", predterms_short), + number = 1:length(predterms_short)) +spatial_element_local <- spatial_element_local[spatial_element_local$judgement == TRUE,]$number + +spatial_element_regional <- data.frame("judgement" = grepl("regional", predterms_short), + number = 1:length(predterms_short)) +spatial_element_regional <- spatial_element_regional[spatial_element_regional$judgement == TRUE,]$number + +spatial_element <- c(spatial_element_local, spatial_element_regional) + +L1_element <- data.frame("judgement" = grepl("L1 speakers (linear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L1_element <- L1_element[L1_element$judgement == TRUE,]$number + + +L1_nl_element <- data.frame("judgement" = grepl("L1 speakers (nonlinear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L1_nl_element <- L1_nl_element[L1_nl_element$judgement == TRUE,]$number + +L2_prop_element <- data.frame("judgement" = grepl("L2 proportion (linear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L2_prop_element <- L2_prop_element[L2_prop_element$judgement == TRUE,]$number + +L2_prop_nl_element <- data.frame("judgement" = grepl("L2 proportion (nonlinear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L2_prop_nl_element <- L2_prop_nl_element[L2_prop_nl_element$judgement == TRUE,]$number + +neighbour_element <- data.frame("judgement" = grepl("Neighbours", predterms_short), + number = 1:length(predterms_short)) +neighbour_element <- neighbour_element[neighbour_element$judgement == TRUE,]$number + +official_element <- data.frame("judgement" = grepl("Official", predterms_short), + number = 1:length(predterms_short)) +official_element <- official_element[official_element$judgement == TRUE,]$number + +education_element <- data.frame("judgement" = grepl("Education", predterms_short), + number = 1:length(predterms_short)) +education_element <- education_element[education_element$judgement == TRUE,]$number + +models_number <- length(predterms_short) + +#preparing empty matrices to be filled with effect estimates (quantiles), model name, and WAIC value +phy_effects_matrix <- matrix(NA, models_number, 5) +colnames(phy_effects_matrix) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +spa_effects_matrix <- matrix(NA, models_number, 5) +colnames(spa_effects_matrix) <- c("2.5%", "50%", "97.5%", "model", "WAIC") + +intercept_matrix <- matrix(NA, models_number, 5) +colnames(intercept_matrix) <- c("2.5%", "50%", "97.5%", "model", "WAIC") + +social_effects_matrix_L1 <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_L1) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L1_nl <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_L1_nl) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L2_prop <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_L2_prop) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L2_prop_nl <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_L2_prop_nl) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_N <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_N) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_O <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_O) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_E <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_E) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L1_L2_prop <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_L1_L2_prop) <- c("2.5%", "50%", "97.5%", "model", "WAIC") + +#fitted values +fitted_list <- vector("list", models_number) +names(fitted_list) <- predterms_short + +#marginals of hyperparameters +marginals_hyperpar_list_gaussian <- vector("list", models_number) +names(marginals_hyperpar_list_gaussian) <- predterms_short + +marginals_hyperpar_list_phy <- vector("list", models_number) +names(marginals_hyperpar_list_phy) <- predterms_short + +marginals_hyperpar_list_spa <- vector("list", models_number) +names(marginals_hyperpar_list_spa) <- predterms_short + +marginals_hyperpar_list_social_L1_nl <- vector("list", models_number) +names(marginals_hyperpar_list_social_L1_nl) <- predterms_short + +marginals_hyperpar_list_social_L2_prop_nl <- vector("list", models_number) +names(marginals_hyperpar_list_social_L2_prop_nl) <- predterms_short + + +#marginals of fixed effects +marginals_fixed_list_Intercept <- vector("list", models_number) +names(marginals_fixed_list_Intercept) <- predterms_short + +marginals_fixed_list_L1 <- vector("list", models_number) +names(marginals_fixed_list_L1) <- predterms_short + +marginals_fixed_list_L2_prop <- vector("list", models_number) +names(marginals_fixed_list_L2_prop) <- predterms_short + +marginals_fixed_list_O <- vector("list", models_number) +names(marginals_fixed_list_O) <- predterms_short + +marginals_fixed_list_N <- vector("list", models_number) +names(marginals_fixed_list_N) <- predterms_short + +marginals_fixed_list_E <- vector("list", models_number) +names(marginals_fixed_list_E) <- predterms_short + +marginals_fixed_list_L1_L2_prop <- vector("list", models_number) +names(marginals_fixed_list_L1_L2_prop) <- predterms_short + + + + +#summary statistics of random effects +summary_random_list_phy <- vector("list", models_number) +names(summary_random_list_phy) <- predterms_short + +summary_random_list_spa <- vector("list", models_number) +names(summary_random_list_spa) <- predterms_short + +summary_random_list_social_L1_nl <- vector("list", models_number) +names(summary_random_list_social_L1_nl) <- predterms_short + +summary_random_list_social_L2_prop_nl <- vector("list", models_number) +names(summary_random_list_social_L2_prop_nl) <- predterms_short + + +coefm <- matrix(NA,models_number,1) +result <- vector("list",models_number) + +for(i in 1:models_number){ + formula <- as.formula(paste("informativity_st ~ ",predterms[[i]])) + result[[i]] <- inla(formula, family="gaussian", + control.family = list(hyper = pcprior_hyper_0.01), + #control.inla = list(tolerance = 1e-8, h = 0.0001), + #tolerance: the tolerance for the optimisation of the hyperparameters + #h: the step-length for the gradient calculations for the hyperparameters. + data=metrics_joined, control.compute=list(waic=TRUE)) + + coefm[i,1] <- round(result[[i]]$waic$waic, 2) + + intercept_matrix[i, 1:3] <- c(result[[i]]$summary.fixed[1,]$`0.025quant`, result[[i]]$summary.fixed[1,]$`0.5quant`, result[[i]]$summary.fixed[1,]$`0.975quant`) + intercept_matrix[i, 4] <- predterms_short[[i]] + intercept_matrix[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_Intercept[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["(Intercept)"]])) + colnames(marginals_fixed_list_Intercept[[i]]) <- c("x for Intercept", "y for Intercept") + + if(i %in% phylogenetic_element) { + phy_effects_matrix[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for phy_id`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + phy_effects_matrix[i, 4] <- predterms_short[[i]] + phy_effects_matrix[i, 5] <- result[[i]]$waic$waic + } + + if(i %in% spatial_element) { + spa_effects_matrix[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for sp_id`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + spa_effects_matrix[i, 4] <- predterms_short[[i]] + spa_effects_matrix[i, 5] <- result[[i]]$waic$waic + } + + + if(i %in% L1_nl_element){ + social_effects_matrix_L1_nl[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for inla.group(L1_copy)`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + social_effects_matrix_L1_nl[i, 4] <- predterms_short[[i]] + social_effects_matrix_L1_nl[i, 5] <- result[[i]]$waic$waic + } + + if(i %in% L2_prop_nl_element){ + social_effects_matrix_L2_prop_nl[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for inla.group(L2_copy)`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + social_effects_matrix_L2_prop_nl[i, 4] <- predterms_short[[i]] + social_effects_matrix_L2_prop_nl[i, 5] <- result[[i]]$waic$waic + } + + if(i %in% L1_element) { + social_effects_matrix_L1[i, 1:3] <- c(result[[i]]$summary.fixed["L1_log_st",]$`0.025quant`, result[[i]]$summary.fixed["L1_log_st",]$`0.5quant`, result[[i]]$summary.fixed["L1_log_st",]$`0.975quant`) + social_effects_matrix_L1[i, 4] <- predterms_short[[i]] + social_effects_matrix_L1[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_L1[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["L1_log_st"]])) + colnames(marginals_fixed_list_L1[[i]]) <- c("x for L1", "y for L1") + } + + if(i %in% L2_prop_element) { + social_effects_matrix_L2_prop[i, 1:3] <- c(result[[i]]$summary.fixed["L2_prop",]$`0.025quant`, result[[i]]$summary.fixed["L2_prop",]$`0.5quant`, result[[i]]$summary.fixed["L2_prop",]$`0.975quant`) + social_effects_matrix_L2_prop[i, 4] <- predterms_short[[i]] + social_effects_matrix_L2_prop[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_L2_prop[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["L2_prop"]])) + colnames(marginals_fixed_list_L2_prop[[i]]) <- c("x for L2 proportion", "y for L2 proportion") + } + + if(i %in% neighbour_element) { + social_effects_matrix_N[i, 1:3] <- c(result[[i]]$summary.fixed[2,]$`0.025quant`, result[[i]]$summary.fixed[2,]$`0.5quant`, result[[i]]$summary.fixed[2,]$`0.975quant`) + social_effects_matrix_N[i, 4] <- predterms_short[[i]] + social_effects_matrix_N[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_N[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][[2]])) + colnames(marginals_fixed_list_N[[i]]) <- c("x for Neighbours", "y for Neighbours") + } + + if(i %in% official_element) { + social_effects_matrix_O[i, 1:3] <- c(result[[i]]$summary.fixed[2,]$`0.025quant`, result[[i]]$summary.fixed[2,]$`0.5quant`, result[[i]]$summary.fixed[2,]$`0.975quant`) + social_effects_matrix_O[i, 4] <- predterms_short[[i]] + social_effects_matrix_O[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_O[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][[2]])) + colnames(marginals_fixed_list_O[[i]]) <- c("x for Official", "y for Official") + } + + if(i %in% education_element) { + social_effects_matrix_E[i, 1:3] <- c(result[[i]]$summary.fixed[2,]$`0.025quant`, result[[i]]$summary.fixed[2,]$`0.5quant`, result[[i]]$summary.fixed[2,]$`0.975quant`) + social_effects_matrix_E[i, 4] <- predterms_short[[i]] + social_effects_matrix_E[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_E[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][[2]])) + colnames(marginals_fixed_list_E[[i]]) <- c("x for Education", "y for Education") + } + + fitted_list[[i]] <- result[[i]]$summary.fitted.values + fitted_list[[i]] <- fitted_list[[i]] %>% + mutate(across(where(is.numeric), round, 2)) + + marginals_hyperpar_list_gaussian[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for the Gaussian observations"]])) + colnames(marginals_hyperpar_list_gaussian[[i]]) <- c("x for the Gaussian observations", "y for the Gaussian observations") + + if(i %in% phylogenetic_element){ + marginals_hyperpar_list_phy[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for phy_id"]])) + colnames(marginals_hyperpar_list_phy[[i]]) <- c("x for phy_id", "y for phy_id") + } + + if(i %in% spatial_element){ + marginals_hyperpar_list_spa[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for sp_id"]])) + colnames(marginals_hyperpar_list_spa[[i]]) <- c("x for sp_id", "y for sp_id") + } + + if(i %in% L1_nl_element){ + marginals_hyperpar_list_social_L1_nl[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for inla.group(L1_copy)"]])) + colnames(marginals_hyperpar_list_social_L1_nl[[i]]) <- c("x for inla.group(L1_copy)", "y for inla.group(L1_copy)") + } + + if(i %in% L2_prop_nl_element){ + marginals_hyperpar_list_social_L2_prop_nl[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for inla.group(L2_copy)"]])) + colnames(marginals_hyperpar_list_social_L2_prop_nl[[i]]) <- c("x for inla.group(L2_copy)", "y for inla.group(L2_copy)") + } + + if(i %in% phylogenetic_element){ + summary_random_list_phy[[i]] <- cbind(result[[i]]$summary.random$phy_id) %>% + rename(phy_id = ID) %>% + as.data.frame() %>% + mutate(across(where(is.numeric), round, 2)) + } + + if(i %in% spatial_element){ + summary_random_list_spa[[i]] <- cbind(result[[i]]$summary.random$sp_id) %>% + rename(sp_id = ID) %>% + as.data.frame() %>% + mutate(across(where(is.numeric), round, 2)) + } +} + +#beepr::beep(5) + +save(result, file = "output_models_reduced/models_Informativity_social_0.01.RData") + + +coefm <- as.data.frame(cbind(predterms_short, coefm)) +colnames(coefm) <- c("model", "WAIC") +coefm <- coefm %>% + mutate(across(.cols=2, as.numeric)) %>% + mutate(across(where(is.numeric), round, 2)) %>% + arrange(WAIC) + +coefm$WAIC <- as.numeric(coefm$WAIC) +coefm <- coefm[order(coefm$WAIC),] + +coefm_path <- paste("output_tables_reduced/", "waics", "Informativity_social_models", "prior_0.01", ".csv", collapse = "") +write.csv(coefm, coefm_path, row.names=FALSE) + + +phy_effects<-as.data.frame(phy_effects_matrix) +spa_effects<-as.data.frame(spa_effects_matrix) +intercept_effects <- as.data.frame(intercept_matrix) +L1_effects <- as.data.frame(social_effects_matrix_L1) +L1_nl_effects <- as.data.frame(social_effects_matrix_L1_nl) +L2_prop_effects <- as.data.frame(social_effects_matrix_L2_prop) +L2_prop_nl_effects <- as.data.frame(social_effects_matrix_L2_prop_nl) +N_effects<-as.data.frame(social_effects_matrix_N) +E_effects<-as.data.frame(social_effects_matrix_E) +O_effects<-as.data.frame(social_effects_matrix_O) + +phy_effects$effect <- "phylogenetic SD" +spa_effects$effect <- "spatial SD" +intercept_effects$effect <- "Intercept" +L1_effects$effect <- "L1" +L1_nl_effects$effect <- "social SD:\nL1" +L2_prop_effects$effect <- "L2 proportion" +L2_prop_nl_effects$effect <- "social SD:\nL2 proportion" +N_effects$effect <- "Neighbours" +E_effects$effect <- "Education" +O_effects$effect <- "Official status" + +effs <- as.data.frame(rbind(phy_effects, spa_effects, intercept_effects, L1_effects, L1_nl_effects, L2_prop_effects, L2_prop_nl_effects, N_effects, O_effects, E_effects)) +effs <- effs %>% + mutate(across(.cols=c(1:3, 5), as.numeric)) %>% + mutate(across(where(is.numeric), round, 2)) %>% + na.omit() %>% + arrange(WAIC) %>% + relocate(model) + +effs_path <- paste("output_tables_reduced/", "effects", "Informativity_social_models", "prior_0.01", ".csv", collapse = "") +write.csv(effs, effs_path, row.names=FALSE) + diff --git a/101/replication_package/sensitivity_testing_reduced_I_05.R b/101/replication_package/sensitivity_testing_reduced_I_05.R new file mode 100644 index 0000000000000000000000000000000000000000..0f06fedd710d36a3efebbcc53f6222b9269d2083 --- /dev/null +++ b/101/replication_package/sensitivity_testing_reduced_I_05.R @@ -0,0 +1,422 @@ +#model fitting: Informativity predicted by social effects on top of random phylogenetic and spatial factors + +source("requirements.R") + +source("install_and_load_INLA.R") + +source("set_up_inla.R") + +metrics_joined <- metrics_joined %>% + filter(!is.na(L1_log10_st)) %>% + rename(L1_log_st = L1_log10_st) %>% + mutate(L1_copy = L1_log_st) %>% + filter(!is.na(L2_prop)) %>% + mutate(L2_copy = L2_prop) %>% + filter(!is.na(neighboring_languages_st)) %>% + filter(!is.na(Official)) %>% + filter(!is.na(Education)) %>% + filter(!is.na(boundness_st)) %>% + filter(!is.na(informativity_st)) + +#dropping tips not in Grambank +metrics_joined <- metrics_joined[metrics_joined$Language_ID %in% tree$tip.label, ] +tree <- keep.tip(tree, metrics_joined$Language_ID) + +x <- assert_that(all(tree$tip.label %in% metrics_joined$Language_ID), msg = "The data and phylogeny taxa do not match") + +## Building standardized phylogenetic precision matrix +tree_scaled <- tree + +tree_vcv = vcv.phylo(tree_scaled) +typical_phylogenetic_variance = exp(mean(log(diag(tree_vcv)))) + +tree_scaled$edge.length <- tree_scaled$edge.length/typical_phylogenetic_variance +phylo_prec_mat <- MCMCglmm::inverseA(tree_scaled, + nodes = "ALL", + scale = FALSE)$Ainv + +metrics_joined = metrics_joined[order(match(metrics_joined$Language_ID, rownames(phylo_prec_mat))),] + +#"local" set of parameters +## Create spatial covariance matrix using the matern covariance function +spatial_covar_mat_1 = varcov.spatial(metrics_joined[,c("Longitude", "Latitude")], + cov.pars = phi_1, kappa = kappa)$varcov +# Calculate and standardize by the typical variance +typical_variance_spatial_1 = exp(mean(log(diag(spatial_covar_mat_1)))) +spatial_cov_std_1 = spatial_covar_mat_1 / typical_variance_spatial_1 +spatial_prec_mat_1 = solve(spatial_cov_std_1) +dimnames(spatial_prec_mat_1) = list(metrics_joined$Language_ID, metrics_joined$Language_ID) + +## Since we are using a sparse phylogenetic matrix, we are matching taxa to rows in the matrix +phy_id = match(tree$tip.label, rownames(phylo_prec_mat)) +metrics_joined$phy_id = phy_id + +## Other effects are in the same order they appear in the dataset +metrics_joined$sp_id = 1:nrow(spatial_prec_mat_1) + +pcprior_hyper_0.5 = list(prec =list(prior="pc.prec", param = c(1, 0.5))) + +#Preparing the formulas for 10 competing models to be used in inla() call +listcombo <- list( + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.5)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.5)", "L1_log_st"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.5)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.5)", "f(inla.group(L1_copy), model='rw2', scale.model = TRUE)"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.5)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.5)", "L2_prop"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.5)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.5)", "f(inla.group(L2_copy), model='rw2', scale.model = TRUE)"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.5)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.5)", "f(inla.group(L1_copy), model='rw2', scale.model = TRUE)", "f(inla.group(L2_copy), model='rw2', scale.model = TRUE)"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.5)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.5)", "L1_log_st", "L2_prop"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.5)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.5)", "neighboring_languages_st"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.5)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.5)", "Official"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.5)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.5)", "Education")) + + +predterms <- lapply(listcombo, function(x) paste(x, collapse="+")) + +predterms <- t(as.data.frame(predterms)) + +predterms_short <- predterms +predterms_short <- gsub("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.5)", "Phylogenetic", predterms_short, fixed=TRUE) +predterms_short <- gsub("f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.5)", "Spatial: local", predterms_short, fixed=TRUE) + +predterms_short <- gsub("f(inla.group(L1_copy), model='rw2', scale.model = TRUE)", "L1 speakers (nonlinear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("L1_log_st", "L1 speakers (linear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("f(inla.group(L2_copy), model='rw2', scale.model = TRUE)", "L2 proportion (nonlinear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("L2_prop", "L2 proportion (linear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("neighboring_languages_st", "Neighbours", predterms_short, fixed=TRUE) + + +phylogenetic_element <- data.frame("judgement" = grepl("Phylogenetic", predterms_short), + number = 1:length(predterms_short)) +phylogenetic_element <- phylogenetic_element[phylogenetic_element$judgement == TRUE,]$number + +spatial_element_local <- data.frame("judgement" = grepl("local", predterms_short), + number = 1:length(predterms_short)) +spatial_element_local <- spatial_element_local[spatial_element_local$judgement == TRUE,]$number + +spatial_element_regional <- data.frame("judgement" = grepl("regional", predterms_short), + number = 1:length(predterms_short)) +spatial_element_regional <- spatial_element_regional[spatial_element_regional$judgement == TRUE,]$number + +spatial_element <- c(spatial_element_local, spatial_element_regional) + +L1_element <- data.frame("judgement" = grepl("L1 speakers (linear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L1_element <- L1_element[L1_element$judgement == TRUE,]$number + + +L1_nl_element <- data.frame("judgement" = grepl("L1 speakers (nonlinear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L1_nl_element <- L1_nl_element[L1_nl_element$judgement == TRUE,]$number + +L2_prop_element <- data.frame("judgement" = grepl("L2 proportion (linear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L2_prop_element <- L2_prop_element[L2_prop_element$judgement == TRUE,]$number + +L2_prop_nl_element <- data.frame("judgement" = grepl("L2 proportion (nonlinear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L2_prop_nl_element <- L2_prop_nl_element[L2_prop_nl_element$judgement == TRUE,]$number + +neighbour_element <- data.frame("judgement" = grepl("Neighbours", predterms_short), + number = 1:length(predterms_short)) +neighbour_element <- neighbour_element[neighbour_element$judgement == TRUE,]$number + +official_element <- data.frame("judgement" = grepl("Official", predterms_short), + number = 1:length(predterms_short)) +official_element <- official_element[official_element$judgement == TRUE,]$number + +education_element <- data.frame("judgement" = grepl("Education", predterms_short), + number = 1:length(predterms_short)) +education_element <- education_element[education_element$judgement == TRUE,]$number + +models_number <- length(predterms_short) + +#preparing empty matrices to be filled with effect estimates (quantiles), model name, and WAIC value +phy_effects_matrix <- matrix(NA, models_number, 5) +colnames(phy_effects_matrix) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +spa_effects_matrix <- matrix(NA, models_number, 5) +colnames(spa_effects_matrix) <- c("2.5%", "50%", "97.5%", "model", "WAIC") + +intercept_matrix <- matrix(NA, models_number, 5) +colnames(intercept_matrix) <- c("2.5%", "50%", "97.5%", "model", "WAIC") + +social_effects_matrix_L1 <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_L1) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L1_nl <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_L1_nl) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L2_prop <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_L2_prop) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L2_prop_nl <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_L2_prop_nl) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_N <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_N) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_O <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_O) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_E <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_E) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L1_L2_prop <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_L1_L2_prop) <- c("2.5%", "50%", "97.5%", "model", "WAIC") + +#fitted values +fitted_list <- vector("list", models_number) +names(fitted_list) <- predterms_short + +#marginals of hyperparameters +marginals_hyperpar_list_gaussian <- vector("list", models_number) +names(marginals_hyperpar_list_gaussian) <- predterms_short + +marginals_hyperpar_list_phy <- vector("list", models_number) +names(marginals_hyperpar_list_phy) <- predterms_short + +marginals_hyperpar_list_spa <- vector("list", models_number) +names(marginals_hyperpar_list_spa) <- predterms_short + +marginals_hyperpar_list_social_L1_nl <- vector("list", models_number) +names(marginals_hyperpar_list_social_L1_nl) <- predterms_short + +marginals_hyperpar_list_social_L2_prop_nl <- vector("list", models_number) +names(marginals_hyperpar_list_social_L2_prop_nl) <- predterms_short + + +#marginals of fixed effects +marginals_fixed_list_Intercept <- vector("list", models_number) +names(marginals_fixed_list_Intercept) <- predterms_short + +marginals_fixed_list_L1 <- vector("list", models_number) +names(marginals_fixed_list_L1) <- predterms_short + +marginals_fixed_list_L2_prop <- vector("list", models_number) +names(marginals_fixed_list_L2_prop) <- predterms_short + +marginals_fixed_list_O <- vector("list", models_number) +names(marginals_fixed_list_O) <- predterms_short + +marginals_fixed_list_N <- vector("list", models_number) +names(marginals_fixed_list_N) <- predterms_short + +marginals_fixed_list_E <- vector("list", models_number) +names(marginals_fixed_list_E) <- predterms_short + +marginals_fixed_list_L1_L2_prop <- vector("list", models_number) +names(marginals_fixed_list_L1_L2_prop) <- predterms_short + + + + +#summary statistics of random effects +summary_random_list_phy <- vector("list", models_number) +names(summary_random_list_phy) <- predterms_short + +summary_random_list_spa <- vector("list", models_number) +names(summary_random_list_spa) <- predterms_short + +summary_random_list_social_L1_nl <- vector("list", models_number) +names(summary_random_list_social_L1_nl) <- predterms_short + +summary_random_list_social_L2_prop_nl <- vector("list", models_number) +names(summary_random_list_social_L2_prop_nl) <- predterms_short + + +coefm <- matrix(NA,models_number,1) +result <- vector("list",models_number) + +for(i in 1:models_number){ + formula <- as.formula(paste("informativity_st ~ ",predterms[[i]])) + result[[i]] <- inla(formula, family="gaussian", + control.family = list(hyper = pcprior_hyper_0.5), + #control.inla = list(tolerance = 1e-8, h = 0.0001), + #tolerance: the tolerance for the optimisation of the hyperparameters + #h: the step-length for the gradient calculations for the hyperparameters. + data=metrics_joined, control.compute=list(waic=TRUE)) + + coefm[i,1] <- round(result[[i]]$waic$waic, 2) + + intercept_matrix[i, 1:3] <- c(result[[i]]$summary.fixed[1,]$`0.025quant`, result[[i]]$summary.fixed[1,]$`0.5quant`, result[[i]]$summary.fixed[1,]$`0.975quant`) + intercept_matrix[i, 4] <- predterms_short[[i]] + intercept_matrix[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_Intercept[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["(Intercept)"]])) + colnames(marginals_fixed_list_Intercept[[i]]) <- c("x for Intercept", "y for Intercept") + + if(i %in% phylogenetic_element) { + phy_effects_matrix[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for phy_id`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + phy_effects_matrix[i, 4] <- predterms_short[[i]] + phy_effects_matrix[i, 5] <- result[[i]]$waic$waic + } + + if(i %in% spatial_element) { + spa_effects_matrix[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for sp_id`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + spa_effects_matrix[i, 4] <- predterms_short[[i]] + spa_effects_matrix[i, 5] <- result[[i]]$waic$waic + } + + + if(i %in% L1_nl_element){ + social_effects_matrix_L1_nl[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for inla.group(L1_copy)`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + social_effects_matrix_L1_nl[i, 4] <- predterms_short[[i]] + social_effects_matrix_L1_nl[i, 5] <- result[[i]]$waic$waic + } + + if(i %in% L2_prop_nl_element){ + social_effects_matrix_L2_prop_nl[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for inla.group(L2_copy)`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + social_effects_matrix_L2_prop_nl[i, 4] <- predterms_short[[i]] + social_effects_matrix_L2_prop_nl[i, 5] <- result[[i]]$waic$waic + } + + if(i %in% L1_element) { + social_effects_matrix_L1[i, 1:3] <- c(result[[i]]$summary.fixed["L1_log_st",]$`0.025quant`, result[[i]]$summary.fixed["L1_log_st",]$`0.5quant`, result[[i]]$summary.fixed["L1_log_st",]$`0.975quant`) + social_effects_matrix_L1[i, 4] <- predterms_short[[i]] + social_effects_matrix_L1[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_L1[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["L1_log_st"]])) + colnames(marginals_fixed_list_L1[[i]]) <- c("x for L1", "y for L1") + } + + if(i %in% L2_prop_element) { + social_effects_matrix_L2_prop[i, 1:3] <- c(result[[i]]$summary.fixed["L2_prop",]$`0.025quant`, result[[i]]$summary.fixed["L2_prop",]$`0.5quant`, result[[i]]$summary.fixed["L2_prop",]$`0.975quant`) + social_effects_matrix_L2_prop[i, 4] <- predterms_short[[i]] + social_effects_matrix_L2_prop[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_L2_prop[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["L2_prop"]])) + colnames(marginals_fixed_list_L2_prop[[i]]) <- c("x for L2 proportion", "y for L2 proportion") + } + + if(i %in% neighbour_element) { + social_effects_matrix_N[i, 1:3] <- c(result[[i]]$summary.fixed[2,]$`0.025quant`, result[[i]]$summary.fixed[2,]$`0.5quant`, result[[i]]$summary.fixed[2,]$`0.975quant`) + social_effects_matrix_N[i, 4] <- predterms_short[[i]] + social_effects_matrix_N[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_N[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][[2]])) + colnames(marginals_fixed_list_N[[i]]) <- c("x for Neighbours", "y for Neighbours") + } + + if(i %in% official_element) { + social_effects_matrix_O[i, 1:3] <- c(result[[i]]$summary.fixed[2,]$`0.025quant`, result[[i]]$summary.fixed[2,]$`0.5quant`, result[[i]]$summary.fixed[2,]$`0.975quant`) + social_effects_matrix_O[i, 4] <- predterms_short[[i]] + social_effects_matrix_O[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_O[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][[2]])) + colnames(marginals_fixed_list_O[[i]]) <- c("x for Official", "y for Official") + } + + if(i %in% education_element) { + social_effects_matrix_E[i, 1:3] <- c(result[[i]]$summary.fixed[2,]$`0.025quant`, result[[i]]$summary.fixed[2,]$`0.5quant`, result[[i]]$summary.fixed[2,]$`0.975quant`) + social_effects_matrix_E[i, 4] <- predterms_short[[i]] + social_effects_matrix_E[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_E[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][[2]])) + colnames(marginals_fixed_list_E[[i]]) <- c("x for Education", "y for Education") + } + + fitted_list[[i]] <- result[[i]]$summary.fitted.values + fitted_list[[i]] <- fitted_list[[i]] %>% + mutate(across(where(is.numeric), round, 2)) + + marginals_hyperpar_list_gaussian[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for the Gaussian observations"]])) + colnames(marginals_hyperpar_list_gaussian[[i]]) <- c("x for the Gaussian observations", "y for the Gaussian observations") + + if(i %in% phylogenetic_element){ + marginals_hyperpar_list_phy[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for phy_id"]])) + colnames(marginals_hyperpar_list_phy[[i]]) <- c("x for phy_id", "y for phy_id") + } + + if(i %in% spatial_element){ + marginals_hyperpar_list_spa[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for sp_id"]])) + colnames(marginals_hyperpar_list_spa[[i]]) <- c("x for sp_id", "y for sp_id") + } + + if(i %in% L1_nl_element){ + marginals_hyperpar_list_social_L1_nl[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for inla.group(L1_copy)"]])) + colnames(marginals_hyperpar_list_social_L1_nl[[i]]) <- c("x for inla.group(L1_copy)", "y for inla.group(L1_copy)") + } + + if(i %in% L2_prop_nl_element){ + marginals_hyperpar_list_social_L2_prop_nl[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for inla.group(L2_copy)"]])) + colnames(marginals_hyperpar_list_social_L2_prop_nl[[i]]) <- c("x for inla.group(L2_copy)", "y for inla.group(L2_copy)") + } + + if(i %in% phylogenetic_element){ + summary_random_list_phy[[i]] <- cbind(result[[i]]$summary.random$phy_id) %>% + rename(phy_id = ID) %>% + as.data.frame() %>% + mutate(across(where(is.numeric), round, 2)) + } + + if(i %in% spatial_element){ + summary_random_list_spa[[i]] <- cbind(result[[i]]$summary.random$sp_id) %>% + rename(sp_id = ID) %>% + as.data.frame() %>% + mutate(across(where(is.numeric), round, 2)) + } +} + +#beepr::beep(5) + +save(result, file = "output_models_reduced/models_Informativity_social_0.5.RData") + + +coefm <- as.data.frame(cbind(predterms_short, coefm)) +colnames(coefm) <- c("model", "WAIC") +coefm <- coefm %>% + mutate(across(.cols=2, as.numeric)) %>% + mutate(across(where(is.numeric), round, 2)) %>% + arrange(WAIC) + +coefm$WAIC <- as.numeric(coefm$WAIC) +coefm <- coefm[order(coefm$WAIC),] + +coefm_path <- paste("output_tables_reduced/", "waics", "Informativity_social_models", "prior_0.5", ".csv", collapse = "") +write.csv(coefm, coefm_path, row.names=FALSE) + + +phy_effects<-as.data.frame(phy_effects_matrix) +spa_effects<-as.data.frame(spa_effects_matrix) +intercept_effects <- as.data.frame(intercept_matrix) +L1_effects <- as.data.frame(social_effects_matrix_L1) +L1_nl_effects <- as.data.frame(social_effects_matrix_L1_nl) +L2_prop_effects <- as.data.frame(social_effects_matrix_L2_prop) +L2_prop_nl_effects <- as.data.frame(social_effects_matrix_L2_prop_nl) +N_effects<-as.data.frame(social_effects_matrix_N) +E_effects<-as.data.frame(social_effects_matrix_E) +O_effects<-as.data.frame(social_effects_matrix_O) + +phy_effects$effect <- "phylogenetic SD" +spa_effects$effect <- "spatial SD" +intercept_effects$effect <- "Intercept" +L1_effects$effect <- "L1" +L1_nl_effects$effect <- "social SD:\nL1" +L2_prop_effects$effect <- "L2 proportion" +L2_prop_nl_effects$effect <- "social SD:\nL2 proportion" +N_effects$effect <- "Neighbours" +E_effects$effect <- "Education" +O_effects$effect <- "Official status" + +effs <- as.data.frame(rbind(phy_effects, spa_effects, intercept_effects, L1_effects, L1_nl_effects, L2_prop_effects, L2_prop_nl_effects, N_effects, O_effects, E_effects)) +effs <- effs %>% + mutate(across(.cols=c(1:3, 5), as.numeric)) %>% + mutate(across(where(is.numeric), round, 2)) %>% + na.omit() %>% + arrange(WAIC) %>% + relocate(model) + +effs_path <- paste("output_tables_reduced/", "effects", "Informativity_social_models", "prior_0.5", ".csv", collapse = "") +write.csv(effs, effs_path, row.names=FALSE) + diff --git a/101/replication_package/sensitivity_testing_reduced_I_099.R b/101/replication_package/sensitivity_testing_reduced_I_099.R new file mode 100644 index 0000000000000000000000000000000000000000..7b7b526eaca46356c96a94d44d7ffa56f4a85c56 --- /dev/null +++ b/101/replication_package/sensitivity_testing_reduced_I_099.R @@ -0,0 +1,422 @@ +#model fitting: Informativity predicted by social effects on top of random phylogenetic and spatial factors + +source("requirements.R") + +source("install_and_load_INLA.R") + +source("set_up_inla.R") + +metrics_joined <- metrics_joined %>% + filter(!is.na(L1_log10_st)) %>% + rename(L1_log_st = L1_log10_st) %>% + mutate(L1_copy = L1_log_st) %>% + filter(!is.na(L2_prop)) %>% + mutate(L2_copy = L2_prop) %>% + filter(!is.na(neighboring_languages_st)) %>% + filter(!is.na(Official)) %>% + filter(!is.na(Education)) %>% + filter(!is.na(boundness_st)) %>% + filter(!is.na(informativity_st)) + +#dropping tips not in Grambank +metrics_joined <- metrics_joined[metrics_joined$Language_ID %in% tree$tip.label, ] +tree <- keep.tip(tree, metrics_joined$Language_ID) + +x <- assert_that(all(tree$tip.label %in% metrics_joined$Language_ID), msg = "The data and phylogeny taxa do not match") + +## Building standardized phylogenetic precision matrix +tree_scaled <- tree + +tree_vcv = vcv.phylo(tree_scaled) +typical_phylogenetic_variance = exp(mean(log(diag(tree_vcv)))) + +tree_scaled$edge.length <- tree_scaled$edge.length/typical_phylogenetic_variance +phylo_prec_mat <- MCMCglmm::inverseA(tree_scaled, + nodes = "ALL", + scale = FALSE)$Ainv + +metrics_joined = metrics_joined[order(match(metrics_joined$Language_ID, rownames(phylo_prec_mat))),] + +#"local" set of parameters +## Create spatial covariance matrix using the matern covariance function +spatial_covar_mat_1 = varcov.spatial(metrics_joined[,c("Longitude", "Latitude")], + cov.pars = phi_1, kappa = kappa)$varcov +# Calculate and standardize by the typical variance +typical_variance_spatial_1 = exp(mean(log(diag(spatial_covar_mat_1)))) +spatial_cov_std_1 = spatial_covar_mat_1 / typical_variance_spatial_1 +spatial_prec_mat_1 = solve(spatial_cov_std_1) +dimnames(spatial_prec_mat_1) = list(metrics_joined$Language_ID, metrics_joined$Language_ID) + +## Since we are using a sparse phylogenetic matrix, we are matching taxa to rows in the matrix +phy_id = match(tree$tip.label, rownames(phylo_prec_mat)) +metrics_joined$phy_id = phy_id + +## Other effects are in the same order they appear in the dataset +metrics_joined$sp_id = 1:nrow(spatial_prec_mat_1) + +pcprior_hyper_0.99 = list(prec =list(prior="pc.prec", param = c(1, 0.99))) + +#Preparing the formulas for 10 competing models to be used in inla() call +listcombo <- list( + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.99)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.99)", "L1_log_st"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.99)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.99)", "f(inla.group(L1_copy), model='rw2', scale.model = TRUE)"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.99)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.99)", "L2_prop"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.99)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.99)", "f(inla.group(L2_copy), model='rw2', scale.model = TRUE)"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.99)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.99)", "f(inla.group(L1_copy), model='rw2', scale.model = TRUE)", "f(inla.group(L2_copy), model='rw2', scale.model = TRUE)"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.99)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.99)", "L1_log_st", "L2_prop"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.99)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.99)", "neighboring_languages_st"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.99)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.99)", "Official"), + + c("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.99)", "f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.99)", "Education")) + + +predterms <- lapply(listcombo, function(x) paste(x, collapse="+")) + +predterms <- t(as.data.frame(predterms)) + +predterms_short <- predterms +predterms_short <- gsub("f(phy_id, model = 'generic0', Cmatrix = phylo_prec_mat, constr = TRUE, hyper = pcprior_hyper_0.99)", "Phylogenetic", predterms_short, fixed=TRUE) +predterms_short <- gsub("f(sp_id, model = 'generic0', Cmatrix = spatial_prec_mat_1, constr = TRUE, hyper = pcprior_hyper_0.99)", "Spatial: local", predterms_short, fixed=TRUE) + +predterms_short <- gsub("f(inla.group(L1_copy), model='rw2', scale.model = TRUE)", "L1 speakers (nonlinear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("L1_log_st", "L1 speakers (linear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("f(inla.group(L2_copy), model='rw2', scale.model = TRUE)", "L2 proportion (nonlinear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("L2_prop", "L2 proportion (linear)", predterms_short, fixed=TRUE) +predterms_short <- gsub("neighboring_languages_st", "Neighbours", predterms_short, fixed=TRUE) + + +phylogenetic_element <- data.frame("judgement" = grepl("Phylogenetic", predterms_short), + number = 1:length(predterms_short)) +phylogenetic_element <- phylogenetic_element[phylogenetic_element$judgement == TRUE,]$number + +spatial_element_local <- data.frame("judgement" = grepl("local", predterms_short), + number = 1:length(predterms_short)) +spatial_element_local <- spatial_element_local[spatial_element_local$judgement == TRUE,]$number + +spatial_element_regional <- data.frame("judgement" = grepl("regional", predterms_short), + number = 1:length(predterms_short)) +spatial_element_regional <- spatial_element_regional[spatial_element_regional$judgement == TRUE,]$number + +spatial_element <- c(spatial_element_local, spatial_element_regional) + +L1_element <- data.frame("judgement" = grepl("L1 speakers (linear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L1_element <- L1_element[L1_element$judgement == TRUE,]$number + + +L1_nl_element <- data.frame("judgement" = grepl("L1 speakers (nonlinear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L1_nl_element <- L1_nl_element[L1_nl_element$judgement == TRUE,]$number + +L2_prop_element <- data.frame("judgement" = grepl("L2 proportion (linear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L2_prop_element <- L2_prop_element[L2_prop_element$judgement == TRUE,]$number + +L2_prop_nl_element <- data.frame("judgement" = grepl("L2 proportion (nonlinear)", predterms_short, fixed=TRUE), + number = 1:length(predterms_short)) +L2_prop_nl_element <- L2_prop_nl_element[L2_prop_nl_element$judgement == TRUE,]$number + +neighbour_element <- data.frame("judgement" = grepl("Neighbours", predterms_short), + number = 1:length(predterms_short)) +neighbour_element <- neighbour_element[neighbour_element$judgement == TRUE,]$number + +official_element <- data.frame("judgement" = grepl("Official", predterms_short), + number = 1:length(predterms_short)) +official_element <- official_element[official_element$judgement == TRUE,]$number + +education_element <- data.frame("judgement" = grepl("Education", predterms_short), + number = 1:length(predterms_short)) +education_element <- education_element[education_element$judgement == TRUE,]$number + +models_number <- length(predterms_short) + +#preparing empty matrices to be filled with effect estimates (quantiles), model name, and WAIC value +phy_effects_matrix <- matrix(NA, models_number, 5) +colnames(phy_effects_matrix) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +spa_effects_matrix <- matrix(NA, models_number, 5) +colnames(spa_effects_matrix) <- c("2.5%", "50%", "97.5%", "model", "WAIC") + +intercept_matrix <- matrix(NA, models_number, 5) +colnames(intercept_matrix) <- c("2.5%", "50%", "97.5%", "model", "WAIC") + +social_effects_matrix_L1 <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_L1) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L1_nl <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_L1_nl) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L2_prop <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_L2_prop) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L2_prop_nl <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_L2_prop_nl) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_N <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_N) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_O <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_O) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_E <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_E) <- c("2.5%", "50%", "97.5%", "model", "WAIC") +social_effects_matrix_L1_L2_prop <- matrix(NA, models_number, 5) +colnames(social_effects_matrix_L1_L2_prop) <- c("2.5%", "50%", "97.5%", "model", "WAIC") + +#fitted values +fitted_list <- vector("list", models_number) +names(fitted_list) <- predterms_short + +#marginals of hyperparameters +marginals_hyperpar_list_gaussian <- vector("list", models_number) +names(marginals_hyperpar_list_gaussian) <- predterms_short + +marginals_hyperpar_list_phy <- vector("list", models_number) +names(marginals_hyperpar_list_phy) <- predterms_short + +marginals_hyperpar_list_spa <- vector("list", models_number) +names(marginals_hyperpar_list_spa) <- predterms_short + +marginals_hyperpar_list_social_L1_nl <- vector("list", models_number) +names(marginals_hyperpar_list_social_L1_nl) <- predterms_short + +marginals_hyperpar_list_social_L2_prop_nl <- vector("list", models_number) +names(marginals_hyperpar_list_social_L2_prop_nl) <- predterms_short + + +#marginals of fixed effects +marginals_fixed_list_Intercept <- vector("list", models_number) +names(marginals_fixed_list_Intercept) <- predterms_short + +marginals_fixed_list_L1 <- vector("list", models_number) +names(marginals_fixed_list_L1) <- predterms_short + +marginals_fixed_list_L2_prop <- vector("list", models_number) +names(marginals_fixed_list_L2_prop) <- predterms_short + +marginals_fixed_list_O <- vector("list", models_number) +names(marginals_fixed_list_O) <- predterms_short + +marginals_fixed_list_N <- vector("list", models_number) +names(marginals_fixed_list_N) <- predterms_short + +marginals_fixed_list_E <- vector("list", models_number) +names(marginals_fixed_list_E) <- predterms_short + +marginals_fixed_list_L1_L2_prop <- vector("list", models_number) +names(marginals_fixed_list_L1_L2_prop) <- predterms_short + + + + +#summary statistics of random effects +summary_random_list_phy <- vector("list", models_number) +names(summary_random_list_phy) <- predterms_short + +summary_random_list_spa <- vector("list", models_number) +names(summary_random_list_spa) <- predterms_short + +summary_random_list_social_L1_nl <- vector("list", models_number) +names(summary_random_list_social_L1_nl) <- predterms_short + +summary_random_list_social_L2_prop_nl <- vector("list", models_number) +names(summary_random_list_social_L2_prop_nl) <- predterms_short + + +coefm <- matrix(NA,models_number,1) +result <- vector("list",models_number) + +for(i in 1:models_number){ + formula <- as.formula(paste("informativity_st ~ ",predterms[[i]])) + result[[i]] <- inla(formula, family="gaussian", + control.family = list(hyper = pcprior_hyper_0.99), + #control.inla = list(tolerance = 1e-8, h = 0.0001), + #tolerance: the tolerance for the optimisation of the hyperparameters + #h: the step-length for the gradient calculations for the hyperparameters. + data=metrics_joined, control.compute=list(waic=TRUE)) + + coefm[i,1] <- round(result[[i]]$waic$waic, 2) + + intercept_matrix[i, 1:3] <- c(result[[i]]$summary.fixed[1,]$`0.025quant`, result[[i]]$summary.fixed[1,]$`0.5quant`, result[[i]]$summary.fixed[1,]$`0.975quant`) + intercept_matrix[i, 4] <- predterms_short[[i]] + intercept_matrix[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_Intercept[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["(Intercept)"]])) + colnames(marginals_fixed_list_Intercept[[i]]) <- c("x for Intercept", "y for Intercept") + + if(i %in% phylogenetic_element) { + phy_effects_matrix[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for phy_id`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + phy_effects_matrix[i, 4] <- predterms_short[[i]] + phy_effects_matrix[i, 5] <- result[[i]]$waic$waic + } + + if(i %in% spatial_element) { + spa_effects_matrix[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for sp_id`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + spa_effects_matrix[i, 4] <- predterms_short[[i]] + spa_effects_matrix[i, 5] <- result[[i]]$waic$waic + } + + + if(i %in% L1_nl_element){ + social_effects_matrix_L1_nl[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for inla.group(L1_copy)`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + social_effects_matrix_L1_nl[i, 4] <- predterms_short[[i]] + social_effects_matrix_L1_nl[i, 5] <- result[[i]]$waic$waic + } + + if(i %in% L2_prop_nl_element){ + social_effects_matrix_L2_prop_nl[i, 1:3] <- inla.tmarginal(function(x) 1/sqrt(x), + result[[i]]$marginals.hyperpar$`Precision for inla.group(L2_copy)`, + method = "linear") %>% + inla.qmarginal(c(0.025, 0.5, 0.975), .) + social_effects_matrix_L2_prop_nl[i, 4] <- predterms_short[[i]] + social_effects_matrix_L2_prop_nl[i, 5] <- result[[i]]$waic$waic + } + + if(i %in% L1_element) { + social_effects_matrix_L1[i, 1:3] <- c(result[[i]]$summary.fixed["L1_log_st",]$`0.025quant`, result[[i]]$summary.fixed["L1_log_st",]$`0.5quant`, result[[i]]$summary.fixed["L1_log_st",]$`0.975quant`) + social_effects_matrix_L1[i, 4] <- predterms_short[[i]] + social_effects_matrix_L1[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_L1[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["L1_log_st"]])) + colnames(marginals_fixed_list_L1[[i]]) <- c("x for L1", "y for L1") + } + + if(i %in% L2_prop_element) { + social_effects_matrix_L2_prop[i, 1:3] <- c(result[[i]]$summary.fixed["L2_prop",]$`0.025quant`, result[[i]]$summary.fixed["L2_prop",]$`0.5quant`, result[[i]]$summary.fixed["L2_prop",]$`0.975quant`) + social_effects_matrix_L2_prop[i, 4] <- predterms_short[[i]] + social_effects_matrix_L2_prop[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_L2_prop[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][["L2_prop"]])) + colnames(marginals_fixed_list_L2_prop[[i]]) <- c("x for L2 proportion", "y for L2 proportion") + } + + if(i %in% neighbour_element) { + social_effects_matrix_N[i, 1:3] <- c(result[[i]]$summary.fixed[2,]$`0.025quant`, result[[i]]$summary.fixed[2,]$`0.5quant`, result[[i]]$summary.fixed[2,]$`0.975quant`) + social_effects_matrix_N[i, 4] <- predterms_short[[i]] + social_effects_matrix_N[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_N[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][[2]])) + colnames(marginals_fixed_list_N[[i]]) <- c("x for Neighbours", "y for Neighbours") + } + + if(i %in% official_element) { + social_effects_matrix_O[i, 1:3] <- c(result[[i]]$summary.fixed[2,]$`0.025quant`, result[[i]]$summary.fixed[2,]$`0.5quant`, result[[i]]$summary.fixed[2,]$`0.975quant`) + social_effects_matrix_O[i, 4] <- predterms_short[[i]] + social_effects_matrix_O[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_O[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][[2]])) + colnames(marginals_fixed_list_O[[i]]) <- c("x for Official", "y for Official") + } + + if(i %in% education_element) { + social_effects_matrix_E[i, 1:3] <- c(result[[i]]$summary.fixed[2,]$`0.025quant`, result[[i]]$summary.fixed[2,]$`0.5quant`, result[[i]]$summary.fixed[2,]$`0.975quant`) + social_effects_matrix_E[i, 4] <- predterms_short[[i]] + social_effects_matrix_E[i, 5] <- result[[i]]$waic$waic + + marginals_fixed_list_E[[i]] <- as.data.frame(cbind(result[[i]][["marginals.fixed"]][[2]])) + colnames(marginals_fixed_list_E[[i]]) <- c("x for Education", "y for Education") + } + + fitted_list[[i]] <- result[[i]]$summary.fitted.values + fitted_list[[i]] <- fitted_list[[i]] %>% + mutate(across(where(is.numeric), round, 2)) + + marginals_hyperpar_list_gaussian[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for the Gaussian observations"]])) + colnames(marginals_hyperpar_list_gaussian[[i]]) <- c("x for the Gaussian observations", "y for the Gaussian observations") + + if(i %in% phylogenetic_element){ + marginals_hyperpar_list_phy[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for phy_id"]])) + colnames(marginals_hyperpar_list_phy[[i]]) <- c("x for phy_id", "y for phy_id") + } + + if(i %in% spatial_element){ + marginals_hyperpar_list_spa[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for sp_id"]])) + colnames(marginals_hyperpar_list_spa[[i]]) <- c("x for sp_id", "y for sp_id") + } + + if(i %in% L1_nl_element){ + marginals_hyperpar_list_social_L1_nl[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for inla.group(L1_copy)"]])) + colnames(marginals_hyperpar_list_social_L1_nl[[i]]) <- c("x for inla.group(L1_copy)", "y for inla.group(L1_copy)") + } + + if(i %in% L2_prop_nl_element){ + marginals_hyperpar_list_social_L2_prop_nl[[i]] <- as.data.frame(cbind(result[[i]]$marginals.hyperpar[["Precision for inla.group(L2_copy)"]])) + colnames(marginals_hyperpar_list_social_L2_prop_nl[[i]]) <- c("x for inla.group(L2_copy)", "y for inla.group(L2_copy)") + } + + if(i %in% phylogenetic_element){ + summary_random_list_phy[[i]] <- cbind(result[[i]]$summary.random$phy_id) %>% + rename(phy_id = ID) %>% + as.data.frame() %>% + mutate(across(where(is.numeric), round, 2)) + } + + if(i %in% spatial_element){ + summary_random_list_spa[[i]] <- cbind(result[[i]]$summary.random$sp_id) %>% + rename(sp_id = ID) %>% + as.data.frame() %>% + mutate(across(where(is.numeric), round, 2)) + } +} + +#beepr::beep(5) + +save(result, file = "output_models_reduced/models_Informativity_social_0.99.RData") + + +coefm <- as.data.frame(cbind(predterms_short, coefm)) +colnames(coefm) <- c("model", "WAIC") +coefm <- coefm %>% + mutate(across(.cols=2, as.numeric)) %>% + mutate(across(where(is.numeric), round, 2)) %>% + arrange(WAIC) + +coefm$WAIC <- as.numeric(coefm$WAIC) +coefm <- coefm[order(coefm$WAIC),] + +coefm_path <- paste("output_tables_reduced/", "waics", "Informativity_social_models", "prior_0.99", ".csv", collapse = "") +write.csv(coefm, coefm_path, row.names=FALSE) + + +phy_effects<-as.data.frame(phy_effects_matrix) +spa_effects<-as.data.frame(spa_effects_matrix) +intercept_effects <- as.data.frame(intercept_matrix) +L1_effects <- as.data.frame(social_effects_matrix_L1) +L1_nl_effects <- as.data.frame(social_effects_matrix_L1_nl) +L2_prop_effects <- as.data.frame(social_effects_matrix_L2_prop) +L2_prop_nl_effects <- as.data.frame(social_effects_matrix_L2_prop_nl) +N_effects<-as.data.frame(social_effects_matrix_N) +E_effects<-as.data.frame(social_effects_matrix_E) +O_effects<-as.data.frame(social_effects_matrix_O) + +phy_effects$effect <- "phylogenetic SD" +spa_effects$effect <- "spatial SD" +intercept_effects$effect <- "Intercept" +L1_effects$effect <- "L1" +L1_nl_effects$effect <- "social SD:\nL1" +L2_prop_effects$effect <- "L2 proportion" +L2_prop_nl_effects$effect <- "social SD:\nL2 proportion" +N_effects$effect <- "Neighbours" +E_effects$effect <- "Education" +O_effects$effect <- "Official status" + +effs <- as.data.frame(rbind(phy_effects, spa_effects, intercept_effects, L1_effects, L1_nl_effects, L2_prop_effects, L2_prop_nl_effects, N_effects, O_effects, E_effects)) +effs <- effs %>% + mutate(across(.cols=c(1:3, 5), as.numeric)) %>% + mutate(across(where(is.numeric), round, 2)) %>% + na.omit() %>% + arrange(WAIC) %>% + relocate(model) + +effs_path <- paste("output_tables_reduced/", "effects", "Informativity_social_models", "prior_0.99", ".csv", collapse = "") +write.csv(effs, effs_path, row.names=FALSE) + diff --git a/101/replication_package/set_up_general.R b/101/replication_package/set_up_general.R new file mode 100644 index 0000000000000000000000000000000000000000..be92ae079d60d532d6b473e4aac30ad5e05ca3d1 --- /dev/null +++ b/101/replication_package/set_up_general.R @@ -0,0 +1,33 @@ +source("requirements.R") + +#creating basic dfs for general use + +#optional script that generates grambank dataset, parameters file, and glottolog from git submodules -- the files that have already been made available by authors. +#this script is only runnable if the external data are correctly downloaded +#source("get_external_data.R") +#source("generating_GB_input_file.R") + +if(!(file.exists("output/Bound_morph/bound_morph_score.tsv"))){ + cat("Calculating boundness score.\n") + source("creating_boundness_metric.R") +} + +if(!(file.exists("output/Informativity/informativity_score.tsv"))){ + cat("Calculating informativity score.\n") + source("creating_informativity_score.R") +} + +if(!(file.exists("data_wrangling/wrangled.tree"))){ + cat("Pruning EDGE-tree.\n") + source("wrangling_tree.R") +} + +AUTOTYP_areas_fn <- "data_wrangling/glottolog_AUTOTYPE_areas.tsv" +if(!(file.exists(AUTOTYP_areas_fn))){ + cat("Generating table of AUTOTYP-areas.\n") + source("assigning_AUTOTYP_areas.R") +} + +#GB langs for subsettting +GB_langs <- read_tsv("data/GB_wide/GB_wide_strict.tsv", col_types = WIDE_COLSPEC) %>% + dplyr::select(Language_ID) diff --git a/101/replication_package/set_up_inla.R b/101/replication_package/set_up_inla.R new file mode 100644 index 0000000000000000000000000000000000000000..7e99f252678a3ae7efb86c441f875740705fb72e --- /dev/null +++ b/101/replication_package/set_up_inla.R @@ -0,0 +1,78 @@ +source("requirements.R") + +#parameters +kappa = 1 +phi_1 = c(1, 1.25) # "Local" version: (sigma, phi) First value is not used +phi_2 = c(1, 17) # "Regional" version: (sigma, phi) First value is not used + +#GB langs for subsetting +GB_langs <- read_tsv("data/GB_wide/GB_wide_strict.tsv", col_types = WIDE_COLSPEC) %>% + dplyr::select(Language_ID) + +areas <- read_tsv("data_wrangling/glottolog_AUTOTYPE_areas.tsv", show_col_types = F) %>% + dplyr::select(Language_ID, AUTOTYP_area) + +glottolog_df <- read_tsv("data_wrangling/glottolog_cldf_wide_df.tsv", show_col_types = F) %>% + inner_join(GB_langs, by = "Language_ID") %>% + mutate(Family_ID = ifelse(is.na(Family_ID), Language_level_ID, Family_ID)) %>% + mutate(Longitude = round(Longitude, 3)) %>% # let's cut down the precision of the lat/long to make the process go quicker. See stack exchange thread where they say "The third decimal place is worth up to 110 m: it can identify a large agricultural field or institutional campus." https://gis.stackexchange.com/questions/8650/measuring-accuracy-of-latitude-and-longitude + mutate(Latitude = round(Latitude, 3)) + + +#taking care of duplicate coordinates by finding them and jittering them +glottolog_df <- glottolog_df %>% + mutate(longlat = paste0(Longitude, " - ", Latitude)) %>% + mutate(longlat = ifelse(longlat == "NA - NA", NA, longlat)) %>% + mutate(dup_longlat = (duplicated(longlat) + duplicated(longlat, fromLast = TRUE))) %>% + mutate(dup_longlat = ifelse(is.na(Longitude), NA, dup_longlat )) %>% + mutate(Longitude = ifelse(dup_longlat >= 1, jitter(Longitude, factor = 1), Longitude)) %>% + mutate(Latitude = ifelse(dup_longlat >= 1, jitter(Latitude, factor = 1), Latitude)) + +# #checking closest languoids +# glottolog_matrix <- glottolog_df %>% +# column_to_rownames("Language_ID") %>% +# dplyr::select(Longitude, Latitude) %>% +# as.matrix() +# +# dists <- rdist.earth(glottolog_matrix, miles = F) +# +# diag(dists) <- NA +# +# dists %>% +# reshape2::melt() %>% +# arrange(value) %>% +# .[1:10,] + +if(sample == "reduced"){ + pop_file_fn <- "data_wrangling/pop_reduced.tsv" +} else { + pop_file_fn <- "data_wrangling/pop_full.tsv" +} + +metrics_joined <- read_tsv(pop_file_fn, show_col_types = F ) %>% + full_join(read_tsv("output/Informativity/informativity_score.tsv", show_col_types = F), by = "Language_ID" ) %>% + full_join(read_tsv("output/Bound_morph/bound_morph_score.tsv", show_col_types = F), by = "Language_ID" ) %>% + full_join(glottolog_df, by = "Language_ID") %>% + #full_join(mean_size, by = "Language_ID") %>% + #full_join(hierarchy, by = "Language_ID") %>% + full_join(areas, by = "Language_ID") + +if(sample == "reduced"){ + metrics_joined <- metrics_joined %>% + dplyr::select(Language_ID, Name, Family_ID, Macroarea, Latitude, Longitude, boundness_st, informativity_st, boundness, Informativity, L1_log10_st, L2_prop, Education, Official, neighboring_languages_st, AUTOTYP_area) +} else { + metrics_joined <- metrics_joined %>% + dplyr::select(Language_ID, Name, Family_ID, Macroarea, Latitude, Longitude, boundness_st, informativity_st, boundness, Informativity, L1_log10_st, L1_log10, L2_prop, Education, Official, neighboring_languages_st, AUTOTYP_area) +} + +metrics_joined <- metrics_joined %>% + #discarding languages with no or low numbers of L1 speakers and L2 speakers resulting primarily from language revival efforts + filter(!Language_ID == "gami1243") %>% + filter(!Language_ID == "tuni1252") %>% + filter(!Language_ID == "yuch1247") %>% + filter(!Language_ID == "mari1424") %>% + filter(!Language_ID == "natc1249") %>% + filter(!Language_ID == "poli1260") #removing Polish due to problems with coding + +tree <- read.tree(file.path("data_wrangling/wrangled.tree")) + \ No newline at end of file diff --git a/101/replication_package/table_INLA_summary_all_models_SI.R b/101/replication_package/table_INLA_summary_all_models_SI.R new file mode 100644 index 0000000000000000000000000000000000000000..63afb9bf94bd58b45a43e842e8538ecaed2eeb47 --- /dev/null +++ b/101/replication_package/table_INLA_summary_all_models_SI.R @@ -0,0 +1,61 @@ +#generate summary tables of WAIC values and effects for all boundness and informativity models (including social-only models and models including non-linear effects) + +effs_B_SP <- + read.csv("output_tables/ effects Boundness_phylogenetic_spatial_models .csv") %>% + rename(lower = 2, + upper = 4, + mean = 3) +effs_B_social <- + read.csv("output_tables/ effects Boundness_social_models .csv") %>% + rename(lower = 2, + upper = 4, + mean = 3) +effs_B_social_only <- + read.csv("output_tables/ effects Boundness_social_only_models .csv") %>% + rename(lower = 2, + upper = 4, + mean = 3) + + + +effs_B <- + as.data.frame(rbind(effs_B_SP, effs_B_social, effs_B_social_only)) %>% + mutate(response = "fusion") + +effs_I_SP <- + read.csv("output_tables/ effects Informativity_phylogenetic_spatial_models .csv") %>% + rename(lower = 2, + upper = 4, + mean = 3) +effs_I_social <- + read.csv("output_tables/ effects Informativity_social_models .csv") %>% + rename(lower = 2, + upper = 4, + mean = 3) +effs_I_social_only <- + read.csv("output_tables/ effects Informativity_social_only_models .csv") %>% + rename(lower = 2, + upper = 4, + mean = 3) + +effs_I <- + as.data.frame(rbind(effs_I_SP, effs_I_social, effs_I_social_only)) %>% + mutate(response = "informativity") + +all_effs <- as.data.frame(rbind(effs_B, effs_I)) %>% + rename("2.5%" = 2, + "50%" = 3, + "97.5%" = 4) %>% + relocate(effect, .after = model) %>% + relocate(response, .after = model) + +write.csv(all_effs, "output_tables/Table_INLA_all_models.csv") + +all_effs <- all_effs %>% + flextable() %>% + autofit() %>% + merge_v(j = c("response", "model")) %>% + fix_border_issues() + +save_as_docx("Summary of all fitted INLA models" = all_effs, + path = "output_tables/Table_INLA_all_models.docx") diff --git a/101/replication_package/table_INLA_summary_all_models_SI_reduced.R b/101/replication_package/table_INLA_summary_all_models_SI_reduced.R new file mode 100644 index 0000000000000000000000000000000000000000..49a5c5b6c893a097c301f1cd38b34bbc7fbd8347 --- /dev/null +++ b/101/replication_package/table_INLA_summary_all_models_SI_reduced.R @@ -0,0 +1,35 @@ +#generate summary tables of WAIC values and effects for all boundness and informativity models (including social-only models and models including non-linear effects) + +#for random effects only, the access folder is output_tables rather than output_tables_reduced +effs_B_SP <- read.csv("output_tables/ effects Boundness_phylogenetic_spatial_models .csv") +effs_B_social <- read.csv("output_tables_reduced/ effects Boundness_social_models .csv") +effs_B_social_only <- read.csv("output_tables_reduced/ effects Boundness_social_only_models .csv") + +effs_B <- as.data.frame(rbind(effs_B_SP, effs_B_social, effs_B_social_only)) %>% + mutate(response="boundness") + +effs_I_SP <- read.csv("output_tables/ effects Informativity_phylogenetic_spatial_models .csv") +effs_I_social <- read.csv("output_tables_reduced/ effects Informativity_social_models .csv") +effs_I_social_only <- read.csv("output_tables_reduced/ effects Informativity_social_only_models .csv") + +effs_I <- as.data.frame(rbind(effs_I_SP, effs_I_social, effs_I_social_only)) %>% + mutate(response="informativity") + +all_effs <- as.data.frame(rbind(effs_B, effs_I)) %>% + rename("2.5%"=2, + "50%" = 3, + "97.5%" = 4) %>% + relocate(effect, .after = model) %>% + relocate(response, .after = model) + +write.csv(all_effs, "output_tables_reduced/Table_INLA_all_models.csv") + +all_effs <- all_effs %>% + flextable() %>% + autofit() %>% + merge_v(j=c("response", "model")) %>% + fix_border_issues() + +save_as_docx( + "Summary of all fitted INLA models" = all_effs, + path = "output_tables_reduced/Table_INLA_all_models.docx") diff --git a/101/replication_package/varcov.spatial_function.R b/101/replication_package/varcov.spatial_function.R new file mode 100644 index 0000000000000000000000000000000000000000..a065b249d15b4f2e2971edbd5aea3ab15f7f1487 --- /dev/null +++ b/101/replication_package/varcov.spatial_function.R @@ -0,0 +1,611 @@ +#This script contains the code from the package geoR for the particular funciton varcov.spatial. It was not possible to load the package itself due to problems with XQuartz from xquartz.macosforge.org no longer part of OS X, making it cumbersome for many mac-users to run the code. We are grateful to the creators of the package (Paulo J. Ribeiro Jr, Peter J. Diggle, Ole Christensen, Martin Schlather, Roger Bivand and Brian Ripley) for their labour acknowledge that this is their funciton. + +varcov.spatial = function (coords = NULL, dists.lowertri = NULL, cov.model = "matern", + kappa = 0.5, nugget = 0, cov.pars = stop("no cov.pars argument"), + inv = FALSE, det = FALSE, func.inv = c("cholesky", "eigen", + "svd", "solve"), scaled = FALSE, only.decomposition = FALSE, + sqrt.inv = FALSE, try.another.decomposition = TRUE, only.inv.lower.diag = FALSE, + ...) +{ + func.inv <- match.arg(func.inv) + cov.model <- sapply(cov.model, match.arg, choices = .geoR.cov.models) + if (only.inv.lower.diag) + inv <- TRUE + if (is.null(coords) & is.null(dists.lowertri)) + stop("one of the arguments, coords or dists.lowertri must be provided") + if (!is.null(coords) & !is.null(dists.lowertri)) + stop("only ONE argument, either coords or dists.lowertri must be provided") + if (!is.null(coords)) + n <- nrow(coords) + if (!is.null(dists.lowertri)) + n <- as.integer(round(0.5 * (1 + sqrt(1 + 8 * length(dists.lowertri))))) + tausq <- nugget + if (is.vector(cov.pars)) { + sigmasq <- cov.pars[1] + phi <- cov.pars[2] + } + else { + sigmasq <- cov.pars[, 1] + phi <- cov.pars[, 2] + } + if (!is.null(coords)) + dists.lowertri <- as.vector(dist(coords)) + if (round(1e+12 * min(dists.lowertri)) == 0) + warning("Two or more pairs of data at coincident (or very close) locations. \nThis may cause crashes in some matrices operations.\n") + varcov <- matrix(0, n, n) + if (scaled) { + if (all(phi < 1e-12)) + varcov <- diag(x = (1 + (tausq/sum(sigmasq))), n) + else { + if (is.vector(cov.pars)) + cov.pars.sc <- c(1, phi) + else cov.pars.sc <- cbind(1, phi) + covvec <- cov.spatial(obj = dists.lowertri, cov.model = cov.model, + kappa = kappa, cov.pars = cov.pars.sc) + varcov[lower.tri(varcov)] <- covvec + varcov <- t(varcov) + varcov[lower.tri(varcov)] <- covvec + remove("covvec") + if (sum(sigmasq) < 1e-16) + diag(varcov) <- 1 + else diag(varcov) <- 1 + (tausq/sum(sigmasq)) + } + } + else { + if (all(sigmasq < 1e-10) | all(phi < 1e-10)) { + varcov <- diag(x = (tausq + sum(sigmasq)), n) + } + else { + covvec <- cov.spatial(obj = dists.lowertri, cov.model = cov.model, + kappa = kappa, cov.pars = cov.pars) + varcov[lower.tri(varcov)] <- covvec + varcov <- t(varcov) + varcov[lower.tri(varcov)] <- covvec + remove("covvec") + diag(varcov) <- tausq + sum(sigmasq) + } + } + if (inv | det | only.decomposition | sqrt.inv | only.inv.lower.diag) { + if (func.inv == "cholesky") { + varcov.sqrt <- try(chol(varcov), silent = TRUE) + if (inherits(varcov.sqrt, "try-error")) { + if (try.another.decomposition) { + cat("trying another decomposition (svd)\n") + func.inv <- "svd" + } + else { + print(varcov.sqrt[1]) + stop() + } + } + else { + if (only.decomposition | inv) + remove("varcov") + if (!only.decomposition) { + if (det) + cov.logdeth <- sum(log(diag(varcov.sqrt))) + if (sqrt.inv) + inverse.sqrt <- solve(varcov.sqrt) + if (inv) { + invcov <- chol2inv(varcov.sqrt) + if (!sqrt.inv) + remove("varcov.sqrt") + } + } + } + } + if (func.inv == "svd") { + varcov.svd <- svd(varcov, nv = 0) + cov.logdeth <- try(sum(log(sqrt(varcov.svd$d))), + silent = TRUE) + if (inherits(cov.logdeth, "try-error")) { + if (try.another.decomposition) { + cat("trying another decomposition (eigen)\n") + func.inv <- "eigen" + } + else { + print(cov.logdeth[1]) + stop() + } + } + else { + if (only.decomposition | inv) + remove("varcov") + if (only.decomposition) + varcov.sqrt <- crossprod(t(varcov.svd$u) * + sqrt(sqrt(varcov.svd$d))) + if (inv) { + invcov <- crossprod(t(varcov.svd$u)/sqrt(varcov.svd$d)) + } + if (sqrt.inv) + inverse.sqrt <- crossprod(t(varcov.svd$u)/sqrt(sqrt(varcov.svd$d))) + } + } + if (func.inv == "solve") { + if (det) + stop("the option func.inv == \"solve\" does not allow computation of determinants. \nUse func.inv = \"chol\",\"svd\" or \"eigen\"\n") + invcov <- try(solve(varcov), silent = TRUE) + if (inherits(cov.logdeth, "try-error")) { + if (try.another.decomposition) + func.inv <- "eigen" + else { + print(invcov[1]) + stop() + } + } + remove("varcov") + } + if (func.inv == "eigen") { + varcov.eig <- try(eigen(varcov, symmetric = TRUE), + silent = TRUE) + cov.logdeth <- try(sum(log(sqrt(varcov.eig$val))), + silent = TRUE) + if (inherits(cov.logdeth, "try.error") | inherits(varcov.eig, + "try-error")) { + diag(varcov) <- 1.0001 * diag(varcov) + varcov.eig <- try(eigen(varcov, symmetric = TRUE), + silent = TRUE) + cov.logdeth <- try(sum(log(sqrt(varcov.eig$val))), + silent = TRUE) + if (inherits(cov.logdeth, "try.error") | inherits(varcov.eig, + "try-error")) { + return(list(crash.parms = c(tausq = tausq, + sigmasq = sigmasq, phi = phi, kappa = kappa))) + } + } + else { + if (only.decomposition | inv) + remove("varcov") + if (only.decomposition) + varcov.sqrt <- crossprod(t(varcov.eig$vec) * + sqrt(sqrt(varcov.eig$val))) + if (inv) + invcov <- crossprod(t(varcov.eig$vec)/sqrt(varcov.eig$val)) + if (sqrt.inv) + inverse.sqrt <- crossprod(t(varcov.eig$vec)/sqrt(sqrt(varcov.eig$val))) + } + } + } + if (!only.decomposition) { + if (det) { + if (inv) { + if (only.inv.lower.diag) + result <- list(lower.inverse = invcov[lower.tri(invcov)], + diag.inverse = diag(invcov), log.det.to.half = cov.logdeth) + else result <- list(inverse = invcov, log.det.to.half = cov.logdeth) + } + else { + result <- list(varcov = varcov, log.det.to.half = cov.logdeth) + } + if (sqrt.inv) + result$sqrt.inverse <- inverse.sqrt + } + else { + if (inv) { + if (only.inv.lower.diag) + result <- list(lower.inverse = invcov[lower.tri(invcov)], + diag.inverse = diag(invcov)) + else { + if (sqrt.inv) + result <- list(inverse = invcov, sqrt.inverse = inverse.sqrt) + else result <- list(inverse = invcov) + } + } + else result <- list(varcov = varcov) + } + } + else result <- list(sqrt.varcov = varcov.sqrt) + result$crash.parms <- NULL + return(result) +} + + + + + + + + +".geoR.cov.models" <- + c("matern", "exponential", "gaussian", "spherical", + "circular", "cubic", "wave", "linear", "power", + "powered.exponential", "stable", "cauchy", "gencauchy", + "gneiting", "gneiting.matern", "pure.nugget") + +"geoRCovModels" <- .geoR.cov.models + +"practicalRange" <- + function (cov.model, phi, kappa=0.5, correlation = 0.05, ...) + { + cov.model <- match.arg(cov.model, choices = .geoR.cov.models) + .check.cov.model(cov.model = cov.model, cov.pars=c(1,phi), kappa=kappa, output=FALSE) + if(cov.model %in% c("circular","cubic","spherical")) + return(phi) + if(any(cov.model %in% c("pure.nugget"))) + return(0) + if(any(cov.model %in% c("linear"))) + return(Inf) + if(any(cov.model %in% c("power"))) + return(Inf) + findRange <- function(range, cm, p, k, cor) + cov.spatial(range, cov.model = cm, kappa = k, cov.pars = c(1, p))-cor + pr <- uniroot(findRange, interval = c(0, 50 * phi + 1), + cm = cov.model, p = phi, k = kappa, cor = correlation, + ...)$root + return(pr) + } + +".check.cov.model" <- + function(cov.model, cov.pars, kappa, env=NULL, output=TRUE) + return(list(cov.model=cov.model, sigmasq=sigmasq, phi=phi, kappa=kappa, ns=ns)) + +"matern" <- + function (u, phi, kappa) + { + if(is.vector(u)) names(u) <- NULL + if(is.matrix(u)) dimnames(u) <- list(NULL, NULL) + uphi <- u/phi + uphi <- ifelse(u > 0, + (((2^(-(kappa-1)))/ifelse(0, Inf,gamma(kappa))) * + (uphi^kappa) * + besselK(x=uphi, nu=kappa)), 1) + uphi[u > 600*phi] <- 0 + return(uphi) + } + +".cor.number" <- + function(cov.model= c("exponential", "matern", "gaussian", + "spherical", "circular", "linear", "cubic", "wave", "power", + "powered.exponential", "stable", "cauchy", "gencauchy", "gneiting", + "gneiting.matern", "pure.nugget")) + { + ### WARNING: codes for covariance functions below + ### MUST be the same as in the C code "cor_diag" + cov.model <- match.arg(cov.model) + if(cov.model == "stable") cov.model <- "powered.exponential" + cornumber <- switch(cov.model, + pure.nugget = as.integer(1), + exponential = as.integer(2), + spherical = as.integer(3), + gaussian = as.integer(4), + wave = as.integer(5), + cubic = as.integer(6), + power = as.integer(7), + powered.exponential = as.integer(8), + cauchy = as.integer(9), + gneiting = as.integer(10), + circular = as.integer(11), + matern = as.integer(12), + gneiting.matern = as.integer(13), + gencauchy = as.integer(14), + stop("wrong or no specification of cov.model") + ) + return(cornumber) + } + +".check.cov.model" <- + function(cov.model, cov.pars, kappa, env=NULL, output=TRUE) + { + ## extracting covariance parameters + if(is.vector(cov.pars)) sigmasq <- cov.pars[1] + else sigmasq <- cov.pars[, 1] + if(is.vector(cov.pars)) phi <- cov.pars[2] + else phi <- cov.pars[, 2] + if(missing(kappa) || is.null(kappa)) kappa <- NA + ## checking for nested models + cov.pars <- drop(cov.pars) + if(is.vector(cov.pars)) ns <- 1 + else{ + ns <- nrow(cov.pars) + if(length(cov.model) == 1) cov.model <- rep(cov.model, ns) + if(length(kappa) == 1) kappa <- rep(kappa, ns) + } + if(length(cov.model) != ns) stop("wrong length for cov.model") + ## + cov.model <- sapply(cov.model, match.arg, .geoR.cov.models) + cov.model[cov.model == "stable"] <- "powered.exponential" + if(any(cov.model == c("gneiting.matern", "gencauchy"))){ + if(length(kappa) != 2*ns) + stop(paste("wrong length for kappa, ", cov.model, "model requires two values for the argument kappa")) + } + else{ + if(length(kappa) != ns) stop('wrong length for kappa') + } + ## settings for power model (do not reverse order of the next two lines!) + phi[cov.model == "linear"] <- 1 + cov.model[cov.model == "linear"] <- "power" + ## checking input for cov. models with extra parameter(s) + if(any(cov.model == 'gneiting.matern') && ns > 1) + stop('nested models including the gneiting.matern are not implemented') + for(i in 1:ns){ + if(any(cov.model[i] == c("matern","powered.exponential", "cauchy", + "gneiting.matern", "gencauchy"))){ + if(any(cov.model[i] == c("gneiting.matern", "gencauchy"))){ + if(any(is.na(kappa)) || length(kappa) != 2*ns) + stop(paste(cov.model[i],"correlation function model requires a vector with 2 parameters in the argument kappa")) + } + else{ + if(is.na(kappa[i]) | is.null(kappa[i])) + stop("for matern, powered.exponential and cauchy covariance functions the parameter kappa must be provided") + } + if((cov.model[i] == "matern" | cov.model[i] == "powered.exponential" | + cov.model[i] == "cauchy") & length(kappa) != 1*ns) + stop("kappa must have 1 parameter for this correlation function") + if(cov.model[i] == "matern" & kappa[i] == 0.5) cov.model[i] == "exponential" + } + if(cov.model[i] == "power") + if(any(phi[i] >= 2) | any(phi[i] <= 0)) + stop("for power model the phi parameters must be in the interval ]0,2[") + } + if(!is.null(env)){ + assign("sigmasq", sigmasq, envir=env) + assign("phi", phi, envir=env) + assign("kappa", kappa, envir=env) + assign("ns", ns, envir=env) + assign("cov.model", cov.model, envir=env) + } + if(output) + return(list(cov.model=cov.model, sigmasq=sigmasq, phi=phi, kappa=kappa, ns=ns)) + else return(invisible()) + } + +"cov.spatial" <- + function(obj, cov.model = "matern", + cov.pars = stop("no cov.pars argument provided"), + kappa = 0.5) + { + fn.env <- sys.frame(sys.nframe()) + .check.cov.model(cov.model=cov.model, cov.pars=cov.pars, kappa=kappa, + env=fn.env, output=FALSE) + phi <- get("phi", envir=fn.env) + sigmasq <- get("sigmasq", envir=fn.env) + ## + ## computing correlations/covariances + ## + # covs <- array(0, dim = dim(obj)) + covs <- obj; covs[] <- 0 + for(i in 1:get("ns", envir=fn.env)) { + if(phi[i] < 1e-16) + cov.model[i] <- "pure.nugget" + obj.sc <- obj/phi[i] + cov.values <- switch(cov.model[i], + pure.nugget = rep(0, length(obj)), + wave = (1/obj) * (phi[i] * sin(obj.sc)), + exponential = exp( - (obj.sc)), + matern = { + if(kappa[i] == 0.5) exp( - (obj.sc)) + else matern(u = obj, phi = phi[i], kappa = kappa[i])}, + gaussian = exp( - ((obj.sc)^2)), + spherical = ifelse(obj < phi[i], (1 - 1.5 * (obj.sc) + + 0.5 * (obj.sc)^3), 0), + circular = { + obj.sc[obj.sc > 1] <- 1; + ifelse(obj < phi[i], (1 - (2 * ((obj.sc) * + sqrt(1 - ((obj.sc)^2)) + + asin(obj.sc)))/pi), 0) + }, + cubic = { + ifelse(obj < phi[i], (1 - (7 * (obj.sc^2) - + 8.75 * (obj.sc^3) + + 3.5 * (obj.sc^5) - + 0.75 * (obj.sc^7))), 0) + }, + power = (obj)^phi, + powered.exponential = exp( - ((obj.sc)^kappa[i])), + cauchy = (1 + (obj.sc)^2)^(-kappa[i]), + gneiting = { + obj.sc <- 0.301187465825 * obj.sc; + t2 <- (1 - obj.sc); + t2 <- ifelse(t2 > 0, (t2^8), 0); + (1 + 8 * obj.sc + 25 * (obj.sc^2) + 32 * (obj.sc^3)) * t2 + }, + gencauchy = (1 + (obj.sc)^kappa[2])^(-kappa[1]/kappa[2]), + gneiting.matern = { + obj.sc <- 0.301187465825 * obj.sc/kappa[2] ; + t2 <- (1 - obj.sc); + t2 <- ifelse(t2 > 0, (t2^8), 0); + cov.values <- (1 + 8 * obj.sc + 25 * (obj.sc^2) + 32 * (obj.sc^3)) * t2; + cov.values * matern(u = obj, phi = phi[i], kappa = kappa[1]) + + }, + stop("wrong or no specification of cov.model") + ) + if(cov.model[i] == "power"){ + A <- (max(cov.values)/sqrt(pi))*gamma((1+phi[i])/2)*gamma(1-(phi[i]/2)) + ## 1:2 below ensures valid results for 1 and 2D + A <- A * max(gamma(phi[i]+(1+(1:2))/2)/(gamma(1+phi[i])*gamma((1+(1:2))/2))) + cov.values <- A - cov.values + cov.values <- cov.values/max(cov.values) + } + cov.values <- ifelse(obj < 1e-16, sigmasq[i], sigmasq[i] * cov.values) + covs <- covs + cov.values + } + # if(all(cov.model == "power")) + # covs <- max(covs) - covs + # else covs[obj < 1e-16] <- sum(sigmasq) + if(sum(sigmasq) < 1e-16) covs[obj < 1e-16] <- 1 + if(any(!is.finite(covs))) warning("Infinity value in cov.spatial") + if(any(is.na(covs))) warning("NA value in cov.spatial") + if(any(is.nan(covs))) warning("NaN value in cov.spatial") + return(covs) + } + +"varcov.spatial" <- + function(coords = NULL, dists.lowertri = NULL, cov.model = "matern", + kappa = 0.5, nugget = 0, cov.pars = stop("no cov.pars argument"), + inv = FALSE, det = FALSE, + func.inv = c("cholesky", "eigen", "svd", "solve"), + scaled = FALSE, only.decomposition = FALSE, + sqrt.inv = FALSE, try.another.decomposition = TRUE, + only.inv.lower.diag = FALSE, ...) + { + func.inv <- match.arg(func.inv) + cov.model <- sapply(cov.model, match.arg, choices = .geoR.cov.models) + if(only.inv.lower.diag) inv <- TRUE + if(is.null(coords) & is.null(dists.lowertri)) + stop("one of the arguments, coords or dists.lowertri must be provided") + if (!is.null(coords) & !is.null(dists.lowertri)) + stop("only ONE argument, either coords or dists.lowertri must be provided") + if (!is.null(coords)) n <- nrow(coords) + if (!is.null(dists.lowertri)) + n <- as.integer(round(0.5 * (1 + sqrt(1 + 8 * length(dists.lowertri))))) + tausq <- nugget + if (is.vector(cov.pars)) { + sigmasq <- cov.pars[1] + phi <- cov.pars[2] + } + else { + sigmasq <- cov.pars[, 1] + phi <- cov.pars[, 2] + } + ## print(c(tausq=tausq, sigmasq=sigmasq, phi=phi, kappa=kappa)) + if (!is.null(coords)) dists.lowertri <- as.vector(dist(coords)) + if (round(1e+12 * min(dists.lowertri)) == 0) + warning("Two or more pairs of data at coincident (or very close) locations. \nThis may cause crashes in some matrices operations.\n") + varcov <- matrix(0, n, n) + if (scaled) { + if (all(phi < 1e-12)) + varcov <- diag(x = (1 + (tausq/sum(sigmasq))), n) + else { + if (is.vector(cov.pars)) cov.pars.sc <- c(1, phi) + else cov.pars.sc <- cbind(1, phi) + covvec <- cov.spatial(obj = dists.lowertri, cov.model = cov.model, + kappa = kappa, cov.pars = cov.pars.sc) + varcov[lower.tri(varcov)] <- covvec + varcov <- t(varcov) + varcov[lower.tri(varcov)] <- covvec + remove("covvec") + if(sum(sigmasq) < 1e-16) diag(varcov) <- 1 + else diag(varcov) <- 1 + (tausq/sum(sigmasq)) + } + } + else { + if (all(sigmasq < 1e-10) | all(phi < 1e-10)) { + varcov <- diag(x = (tausq + sum(sigmasq)), n) + } + else { + covvec <- cov.spatial(obj = dists.lowertri, cov.model = cov.model, + kappa = kappa, cov.pars = cov.pars) + varcov[lower.tri(varcov)] <- covvec + varcov <- t(varcov) + varcov[lower.tri(varcov)] <- covvec + remove("covvec") + diag(varcov) <- tausq + sum(sigmasq) + } + } + if (inv | det | only.decomposition | sqrt.inv | only.inv.lower.diag) { + if (func.inv == "cholesky") { + varcov.sqrt <- try(chol(varcov), silent=TRUE) + if (inherits(varcov.sqrt, "try-error")) { + if (try.another.decomposition){ + cat("trying another decomposition (svd)\n") + func.inv <- "svd" + } + else { + print(varcov.sqrt[1]) + stop() + } + } + else { + if (only.decomposition | inv) remove("varcov") + if (!only.decomposition) { + if (det) cov.logdeth <- sum(log(diag(varcov.sqrt))) + if (sqrt.inv) inverse.sqrt <- solve(varcov.sqrt) + if (inv) { + invcov <- chol2inv(varcov.sqrt) + if (!sqrt.inv) remove("varcov.sqrt") + } + } + } + } + if (func.inv == "svd") { + varcov.svd <- svd(varcov, nv = 0) + cov.logdeth <- try(sum(log(sqrt(varcov.svd$d))), silent=TRUE) + if (inherits(cov.logdeth, "try-error")) { + if (try.another.decomposition){ + cat("trying another decomposition (eigen)\n") + func.inv <- "eigen" + } + else { + print(cov.logdeth[1]) + stop() + } + } + else { + if (only.decomposition | inv) remove("varcov") + if (only.decomposition) + varcov.sqrt <- crossprod(t(varcov.svd$u) * sqrt(sqrt(varcov.svd$d))) + if (inv) { + invcov <- crossprod(t(varcov.svd$u)/sqrt(varcov.svd$d)) + } + if (sqrt.inv) + inverse.sqrt <- crossprod(t(varcov.svd$u)/sqrt(sqrt(varcov.svd$d))) + } + } + if (func.inv == "solve") { + if (det) + stop("the option func.inv == \"solve\" does not allow computation of determinants. \nUse func.inv = \"chol\",\"svd\" or \"eigen\"\n") + invcov <- try(solve(varcov), silent=TRUE) + if (inherits(cov.logdeth, "try-error")) { + if (try.another.decomposition) + func.inv <- "eigen" + else { + print(invcov[1]) + stop() + } + } + remove("varcov") + } + if (func.inv == "eigen") { + varcov.eig <- try(eigen(varcov, symmetric = TRUE), silent=TRUE) + cov.logdeth <- try(sum(log(sqrt(varcov.eig$val))), silent=TRUE) + if (inherits(cov.logdeth, "try.error") | inherits(varcov.eig, "try-error")) { + diag(varcov) <- 1.0001 * diag(varcov) + varcov.eig <- try(eigen(varcov, symmetric = TRUE), silent=TRUE) + cov.logdeth <- try(sum(log(sqrt(varcov.eig$val))), silent=TRUE) + if (inherits(cov.logdeth, "try.error") | inherits(varcov.eig, "try-error")) { + return(list(crash.parms = c(tausq=tausq, sigmasq=sigmasq, phi=phi, kappa=kappa))) + } + } + else { + if (only.decomposition | inv) remove("varcov") + if (only.decomposition) + varcov.sqrt <- crossprod(t(varcov.eig$vec)* sqrt(sqrt(varcov.eig$val))) + if (inv) invcov <- crossprod(t(varcov.eig$vec)/sqrt(varcov.eig$val)) + if (sqrt.inv) + inverse.sqrt <- crossprod(t(varcov.eig$vec)/sqrt(sqrt(varcov.eig$val))) + } + } + } + if (!only.decomposition) { + if (det) { + if (inv) { + if (only.inv.lower.diag) + result <- list(lower.inverse = invcov[lower.tri(invcov)], + diag.inverse = diag(invcov), log.det.to.half = cov.logdeth) + else result <- list(inverse = invcov, log.det.to.half = cov.logdeth) + } + else { + result <- list(varcov = varcov, log.det.to.half = cov.logdeth) + } + if (sqrt.inv) + result$sqrt.inverse <- inverse.sqrt + } + else { + if (inv) { + if (only.inv.lower.diag) + result <- list(lower.inverse = invcov[lower.tri(invcov)], + diag.inverse = diag(invcov)) + else { + if (sqrt.inv) + result <- list(inverse = invcov, sqrt.inverse = inverse.sqrt) + else result <- list(inverse = invcov) + } + } + else result <- list(varcov = varcov) + } + } + else result <- list(sqrt.varcov = varcov.sqrt) + result$crash.parms <- NULL + return(result) + } \ No newline at end of file diff --git a/101/replication_package/variance_top_ranking_models.R b/101/replication_package/variance_top_ranking_models.R new file mode 100644 index 0000000000000000000000000000000000000000..7dd326f240f9cfdafec01a3dbcbc9946fbf5c8de --- /dev/null +++ b/101/replication_package/variance_top_ranking_models.R @@ -0,0 +1,75 @@ +#picking the top 2 models of boundness (with social predictors that improve the fit of the random-effects-only model) and top 4 models of informativity (with WAIC difference from the top model no lower than 10) to calculate the percentages of variance of random effects + +# script was written by Sam Passmore and Olena Shcherbakova + +n_samples = 100 + +load("output_models/models_Boundness_social.RData") + +#boundness_st ~ phy+spa+L1 +posterior = inla.hyperpar.sample(n_samples, result[[1]]) +h2 = (1 / posterior) / rowSums(1 / posterior) +h2 <- h2 %>% + as.data.frame() %>% + summarise(across(where(is.numeric), ~ mean(.x, na.rm = TRUE))) + +B_L1 <- c("boundness", "L1 speakers", h2[[1]], h2[[2]], h2[[3]], result[[1]]$waic$waic) + + +#boundness_st ~ phy+spa+L1+L1 proportion +posterior = inla.hyperpar.sample(n_samples, result[[6]]) +h2 = (1 / posterior) / rowSums(1 / posterior) +h2 <- h2 %>% + as.data.frame() %>% + summarise(across(where(is.numeric), ~ mean(.x, na.rm = TRUE))) + +B_L1_L2_prop <- c("boundness", "L1 speakers + L2 proportion", h2[[1]], h2[[2]], h2[[3]], result[[6]]$waic$waic) + + +load("output_models/models_Informativity_social.RData") + +#informativity_st ~ phy+spa+L1 +posterior = inla.hyperpar.sample(n_samples, result[[1]]) +h2 = (1 / posterior) / rowSums(1 / posterior) +h2 <- h2 %>% + as.data.frame() %>% + summarise(across(where(is.numeric), ~ mean(.x, na.rm = TRUE))) + +I_L1 <- c("informativity", "L1 speakers", h2[[1]], h2[[2]], h2[[3]], result[[1]]$waic$waic) + +#informativity_st ~ phy+spa+L1+L1 proportion +posterior = inla.hyperpar.sample(n_samples, result[[6]]) +h2 = (1 / posterior) / rowSums(1 / posterior) +h2 <- h2 %>% + as.data.frame() %>% + summarise(across(where(is.numeric), ~ mean(.x, na.rm = TRUE))) + +I_L1_L2_prop <- c("informativity", "L1 speakers + L2 proportion", h2[[1]], h2[[2]], h2[[3]], result[[6]]$waic$waic) + + +variance <- as.data.frame(rbind(B_L1, B_L1_L2_prop, I_L1, I_L1_L2_prop)) +colnames(variance) <- c("response", "sociodemographic predictor(s)", "variance for the Gaussian observations", "variance for phy_id", "variance for sp_id", "WAIC") + +variance_csv <- variance %>% + mutate(across(.cols=c(3:6), as.numeric)) %>% + mutate(across(where(is.numeric), round, 2)) %>% + mutate(across(.cols=c(3:5), function(x) x*100)) %>% + rename_with(.cols=c(3:5), ~ paste0(.x, " in %")) + + +write.csv(variance_csv, "output_tables/Table_variance_top_ranking_models.csv") + +variance_flextable <- variance %>% + mutate(across(.cols=c(3:6), as.numeric)) %>% + mutate(across(where(is.numeric), round, 2)) %>% + mutate(across(.cols=c(3:5), function(x) x*100)) %>% + rename_with(.cols=c(3:5), ~ paste0(.x, " in %")) %>% + flextable() %>% + autofit() %>% + merge_v(j=c("response")) %>% + fix_border_issues() + +save_as_docx( + "Variance in top-ranking models of boundness and informativity" = variance_flextable, + path = "output_tables/table_SM_variance_top_ranking_models.docx") + diff --git a/101/replication_package/variance_top_ranking_models_reduced.R b/101/replication_package/variance_top_ranking_models_reduced.R new file mode 100644 index 0000000000000000000000000000000000000000..e625b661380e38ad138a6e6a46e099cd2ea270f5 --- /dev/null +++ b/101/replication_package/variance_top_ranking_models_reduced.R @@ -0,0 +1,74 @@ +#picking the top 2 models of boundness (with social predictors that improve the fit of the random-effects-only model) and top 4 models of informativity (with WAIC difference from the top model no lower than 10) to calculate the percentages of variance of random effects + +# script was written by Sam Passmore and Olena Shcherbakova + +n_samples = 100 + +load("output_models_reduced/models_Boundness_social.RData") + +#boundness_st ~ phy+spa+L1 +posterior = inla.hyperpar.sample(n_samples, result[[1]]) +h2 = (1 / posterior) / rowSums(1 / posterior) +h2 <- h2 %>% + as.data.frame() %>% + summarise(across(where(is.numeric), ~ mean(.x, na.rm = TRUE))) + +B_L1 <- c("boundness", "L1 speakers", h2[[1]], h2[[2]], h2[[3]], result[[1]]$waic$waic) + + +#boundness_st ~ phy+spa+L1+L1 proportion +posterior = inla.hyperpar.sample(n_samples, result[[6]]) +h2 = (1 / posterior) / rowSums(1 / posterior) +h2 <- h2 %>% + as.data.frame() %>% + summarise(across(where(is.numeric), ~ mean(.x, na.rm = TRUE))) + +B_L1_L2_prop <- c("boundness", "L1 speakers + L2 proportion", h2[[1]], h2[[2]], h2[[3]], result[[6]]$waic$waic) + + +load("output_models_reduced/models_Informativity_social.RData") + +#informativity_st ~ phy+spa+L1 +posterior = inla.hyperpar.sample(n_samples, result[[1]]) +h2 = (1 / posterior) / rowSums(1 / posterior) +h2 <- h2 %>% + as.data.frame() %>% + summarise(across(where(is.numeric), ~ mean(.x, na.rm = TRUE))) + +I_L1 <- c("informativity", "L1 speakers", h2[[1]], h2[[2]], h2[[3]], result[[1]]$waic$waic) + +#informativity_st ~ phy+spa+L1+L1 proportion +posterior = inla.hyperpar.sample(n_samples, result[[6]]) +h2 = (1 / posterior) / rowSums(1 / posterior) +h2 <- h2 %>% + as.data.frame() %>% + summarise(across(where(is.numeric), ~ mean(.x, na.rm = TRUE))) + +I_L1_L2_prop <- c("informativity", "L1 speakers + L2 proportion", h2[[1]], h2[[2]], h2[[3]], result[[6]]$waic$waic) + + +variance <- as.data.frame(rbind(B_L1, B_L1_L2_prop, I_L1, I_L1_L2_prop)) +colnames(variance) <- c("response", "sociodemographic predictor(s)", "variance for the Gaussian observations", "variance for phy_id", "variance for sp_id", "WAIC") + +variance_csv <- variance %>% + mutate(across(.cols=c(3:6), as.numeric)) %>% + mutate(across(where(is.numeric), round, 2)) %>% + mutate(across(.cols=c(3:5), function(x) x*100)) %>% + rename_with(.cols=c(3:5), ~ paste0(.x, " in %")) + +write.csv(variance_csv, "output_tables_reduced/Table_variance_top_ranking_models.csv") + +variance_flextable <- variance %>% + mutate(across(.cols=c(3:6), as.numeric)) %>% + mutate(across(where(is.numeric), round, 2)) %>% + mutate(across(.cols=c(3:5), function(x) x*100)) %>% + rename_with(.cols=c(3:5), ~ paste0(.x, " in %")) %>% + flextable() %>% + autofit() %>% + merge_v(j=c("response")) %>% + fix_border_issues() + +save_as_docx( + "Variance in top-ranking models of boundness and informativity" = variance_flextable, + path = "output_tables_reduced/table_SM_variance_top_ranking_models.docx") + diff --git a/101/replication_package/wrangling_tree.R b/101/replication_package/wrangling_tree.R new file mode 100644 index 0000000000000000000000000000000000000000..8ae3e4c5c20de7db19a6cee287c2febb00260bed --- /dev/null +++ b/101/replication_package/wrangling_tree.R @@ -0,0 +1,43 @@ +# script was written by Hedvig Skirgård + +#Glottolog-cldf table for aggregating dialects +OUTPUTDIR_data_wrangling<- here("data_wrangling") +# create output dir if it does not exist. +if (!dir.exists(OUTPUTDIR_data_wrangling)) { dir.create(OUTPUTDIR_data_wrangling) } + +if (!file.exists(here(OUTPUTDIR_data_wrangling, "wrangled.tree"))) { + + glottolog_df <- read_tsv("data_wrangling/glottolog_cldf_wide_df.tsv", col_types = cols()) %>% + dplyr::select(Glottocode, Language_ID, Language_level_ID) %>% + mutate(Language_level_ID = if_else(is.na(Language_level_ID), Glottocode, Language_level_ID)) + + GB_languages <- read_tsv("data/GB_wide/GB_wide_strict.tsv",col_types = cols()) %>% + dplyr::select(Language_ID) #this column is already aggregated for dialects in make_wide.R + + #reading in tree + EDGE_tree <- ape::read.nexus("data/phylogenies/EDGE6635-merged-relabelled.tree") + + #subsetting the tips to those in Grambank and such that there is only one per language_level_id, i.e. merging dialects and the like. + to_keep <- EDGE_tree$tip.label %>% + as.data.frame() %>% + rename(tip.label = ".") %>% + separate(col = tip.label , into = c("Language_ID", "Name_EDGE"), remove = F, sep = 8) %>% + left_join(glottolog_df, by = "Language_ID") %>% + inner_join(GB_languages, by = "Language_ID") %>% + group_by(Language_level_ID) %>% + sample_n(1) + + #actually pruning the tree itself + pruned_tree <- ape::keep.tip(EDGE_tree, to_keep$tip.label) + + #renaming tip labels to just glottocodes + pruned_tree$tip.label <- pruned_tree$tip.label %>% + as.data.frame() %>% + rename(tip.label = ".") %>% + separate(col = tip.label , into = c("Language_ID", "Name_EDGE"), sep = 8) %>% + dplyr::select(Language_ID) %>% + .[,1] + + pruned_tree %>% + write.tree(file = here(OUTPUTDIR_data_wrangling, "wrangled.tree")) +} diff --git a/101/should_reproduce.txt b/101/should_reproduce.txt new file mode 100644 index 0000000000000000000000000000000000000000..c476e5c2510d8f716ec0f8f34ee939e61c9ff287 --- /dev/null +++ b/101/should_reproduce.txt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:baaa5318ff707002eb50cfbd71e39d7f647120f3458fd62ff70735203fc02bd7 +size 42