├── .Rbuildignore ├── .gitattributes ├── .github └── workflows │ ├── pkgdown.yml │ └── r.yml ├── .gitignore ├── ChangeLog ├── DESCRIPTION ├── LICENSE ├── LICENSE.md ├── Makefile ├── NAMESPACE ├── NEWS.md ├── R ├── RcppExports.R ├── adjmat.r ├── bass.r ├── bootnet.r ├── data.r ├── diffnet-c.R ├── diffnet-class.r ├── diffnet-indexing.r ├── diffnet-methods.r ├── egonets.R ├── formula.r ├── graph_data.r ├── igraph.r ├── imports.r ├── infect_suscept.r ├── mentor.r ├── misc.r ├── moran.r ├── netmatch.r ├── network.r ├── options.R ├── package-doc.r ├── plot_diffnet2.r ├── random_graph.R ├── rdiffnet.r ├── read_write_foreign.r ├── rewire.r ├── select_egoalter.R ├── spatial.R ├── stats.R ├── struct_equiv.R ├── struct_test.R └── survey_to_diffnet.R ├── README.Rmd ├── README.md ├── README_files ├── figure-gfm │ ├── Adopters-1.png │ ├── BoringThreshold, plot_threshold-1.png │ ├── Hazard-1.png │ ├── NiceThreshold-1.png │ ├── mosaic-1.png │ ├── plot_diffnet-1.png │ ├── plot_diffnet2 with map-1.png │ ├── plot_diffnet2-1.png │ ├── plot_infectsuscept-1.png │ └── plot_infectsuscept-2.png └── figure-markdown_github │ ├── Adopters-1.png │ ├── BoringThreshold, plot_threshold-1.png │ ├── Hazard-1.png │ ├── NiceThreshold-1.png │ ├── mosaic-1.png │ ├── plot_diffnet-1.png │ ├── plot_diffnet2 with map-1.png │ ├── plot_diffnet2-1.png │ ├── plot_infectsuscept-1.png │ └── plot_infectsuscept-2.png ├── _pkgdown.yml ├── cleanup ├── configure ├── configure.ac ├── cran-comments.md ├── data-raw ├── SAMPSON.DAT ├── SAMPSON.DAT.R ├── SAMPSON.NET ├── SAMPSON.R ├── SAMPSONL.NET ├── SAMPSONL.R ├── brfarmers.R ├── brfarmersDiffNet.R ├── data_creationfiles.R ├── fakeDynEdgelist.R ├── fakeEdgelist.R ├── fakesurvey.R ├── fakesurvey.csv ├── fakesurveyDyn.R ├── kfamily.R ├── kfamilyDiffNet.R ├── listing_duplicated_columns.r └── medInnovations.R ├── data ├── brfarmers.rdata ├── brfarmersDiffNet.rdata ├── fakeDynEdgelist.rdata ├── fakeEdgelist.rdata ├── fakesurvey.rdata ├── fakesurveyDyn.rdata ├── kfamily.rdata ├── kfamilyDiffNet.rdata ├── medInnovations.rdata └── medInnovationsDiffNet.rdata ├── docker ├── DESCRIPTION ├── Dockerfile ├── Dockerfile.r-ver ├── Makefile ├── README.md └── pkgs.R ├── inst ├── CITATION ├── NEWS └── extdata │ ├── SAMPSON.DAT │ ├── SAMPSON.NET │ ├── SAMPSONL.NET │ └── SAMPSON_W_DEGREE.vec ├── man-roxygen ├── graph_template.R └── plotting_template.R ├── man ├── approx_geodesic.Rd ├── as.array.diffnet.Rd ├── as_dgCMatrix.Rd ├── bass.Rd ├── bootnet.Rd ├── brfarmers.Rd ├── brfarmersDiffNet.Rd ├── c.diffnet.Rd ├── classify_adopters.Rd ├── classify_graph.Rd ├── cumulative_adopt_count.Rd ├── dgr.Rd ├── diag_expand.Rd ├── diffnet-arithmetic.Rd ├── diffnet-class.Rd ├── diffnet_check_attr_class.Rd ├── diffnet_index.Rd ├── diffnetmatmult.Rd ├── diffreg.Rd ├── diffusion-data.Rd ├── diffusionMap.Rd ├── drawColorKey.Rd ├── edgelist_to_adjmat.Rd ├── edges_coords.Rd ├── ego_variance.Rd ├── egonet_attrs.Rd ├── exposure.Rd ├── fakeDynEdgelist.Rd ├── fakeEdgelist.Rd ├── fakesurvey.Rd ├── fakesurveyDyn.Rd ├── figures │ ├── netdiffuser-logo.png │ └── netdiffuser-logo.svg ├── grid_distribution.Rd ├── hazard_rate.Rd ├── igraph.Rd ├── infection.Rd ├── isolated.Rd ├── kfamily.Rd ├── kfamilyDiffNet.Rd ├── matrix_compare.Rd ├── medInnovations.Rd ├── medInnovationsDiffNet.Rd ├── mentor_matching.Rd ├── moran.Rd ├── netdiffuseR-graphs.Rd ├── netdiffuseR-options.Rd ├── netdiffuseR.Rd ├── netmatch.Rd ├── network.Rd ├── nvertices.Rd ├── permute_graph.Rd ├── plot.diffnet.Rd ├── plot_adopters.Rd ├── plot_diffnet.Rd ├── plot_diffnet2.Rd ├── plot_infectsuscep.Rd ├── plot_threshold.Rd ├── pretty_within.Rd ├── rdiffnet.Rd ├── read_pajek.Rd ├── read_ucinet_head.Rd ├── recode.Rd ├── rescale_vertex_igraph.Rd ├── rewire_graph.Rd ├── rgraph_ba.Rd ├── rgraph_er.Rd ├── rgraph_ws.Rd ├── ring_lattice.Rd ├── round_to_seq.Rd ├── select_egoalter.Rd ├── struct_equiv.Rd ├── struct_test.Rd ├── summary.diffnet.Rd ├── survey_to_diffnet.Rd ├── threshold.Rd ├── toa_diff.Rd ├── toa_mat.Rd ├── transformGraphBy.Rd ├── vertex_covariate_compare.Rd ├── vertex_covariate_dist.Rd └── weighted_var.Rd ├── netdiffuseR.Rproj ├── next_release.md ├── playground ├── attrs.R ├── curved.R ├── epimodel │ ├── epimodel.r │ ├── epimodel_notes.md │ ├── epimodel_notes.rmd │ └── epimodel_notes_cache │ │ ├── html │ │ ├── __packages │ │ ├── sim_e1d340f2c40d6e3e4ed9c7061e1757d2.RData │ │ ├── sim_e1d340f2c40d6e3e4ed9c7061e1757d2.rdb │ │ └── sim_e1d340f2c40d6e3e4ed9c7061e1757d2.rdx │ │ └── markdown_github-ascii_identifiers │ │ ├── __packages │ │ ├── sim_0ea3387c274ae47647171b010a6f0453.RData │ │ ├── sim_0ea3387c274ae47647171b010a6f0453.rdb │ │ └── sim_0ea3387c274ae47647171b010a6f0453.rdx ├── exposure-ans-discussion.R ├── exposure-out-discussion.R ├── indexing.R ├── sna_sedist_function.R └── split_behavior_discussion.R ├── src ├── Makevars.in ├── Makevars.win ├── RcppExports.cpp ├── adjmat.cpp ├── adjmat.h ├── infection.cpp ├── infection.h ├── netdiffuser_extra.cpp ├── netdiffuser_extra.h ├── plot.cpp ├── plot.h ├── rgraph.cpp ├── rgraph.h ├── stats.cpp ├── stats.h ├── struct_test.cpp └── struct_test.h ├── tests ├── testthat.R └── testthat │ ├── test-adjmat.R │ ├── test-bass.r │ ├── test-bootnet.r │ ├── test-cumulative_adopt_count.R │ ├── test-dgr.R │ ├── test-diffnet-class.R │ ├── test-diffnet-indexing.R │ ├── test-diffnet-methods.R │ ├── test-egonets.R │ ├── test-examples.R │ ├── test-foreign.R │ ├── test-formula.R │ ├── test-graph_data.R │ ├── test-imports.R │ ├── test-infect_suscept.R │ ├── test-mentor.r │ ├── test-misc.R │ ├── test-moran.r │ ├── test-netdiffuser_extra.R │ ├── test-options.R │ ├── test-plot_diffnet2.R │ ├── test-random_graph.R │ ├── test-rdiffnet-parameters.R │ ├── test-rdiffnet.R │ ├── test-read_write_foreign.R │ ├── test-rewire.R │ ├── test-select_egoalter.R │ ├── test-spatial.R │ ├── test-stats.R │ ├── test-struct_equiv.R │ ├── test-struct_test.R │ └── test-survey_to_diffnet.R └── vignettes ├── analyzing-medical-innovation-data.Rmd ├── introduction-to-netdiffuser.Rmd ├── large-simulation.Rmd ├── not-lost-in-translation-importing-and-exporting-graphs.Rmd ├── rdiffnets.Rmd ├── simulating-multiple-behaviors-on-networks.Rmd └── time_discount_suscep_infect.Rmd /.Rbuildignore: -------------------------------------------------------------------------------- 1 | ^CRAN-RELEASE$ 2 | ^Meta$ 3 | ^.*\.Rproj$ 4 | ^\.Rproj\.user$ 5 | ^data-raw$ 6 | ^man-roxygen$ 7 | ^playground$ 8 | ^tutorials$ 9 | .*\.old 10 | ^doc$ 11 | ^docker$ 12 | .*\.Rhistory$ 13 | 14 | # Binary files 15 | .*\.tar\.gz 16 | .*\.zip 17 | .*\.xls 18 | .*\.doc 19 | .*\.pdf 20 | # Misc 21 | README[.]Rmd 22 | ^README\_files$ 23 | [.]travis[.]yml 24 | ^appveyor\.yml$ 25 | # Not-ready vignettes 26 | ^vignettes/simulating.+\.Rmd$ 27 | ^vignettes/structural.+\.Rmd$ 28 | ^vignettes/rdiffnets\.Rmd$ 29 | ^vignettes/large-simulation.Rmd$ 30 | # CRAN 31 | ^cran-comments\.md$ 32 | ^next_release\.md$ 33 | ^src/rgraph_scale_free.+$ 34 | makefile 35 | ^src/Makevars$ 36 | ^docs$ 37 | ^LICENSE\.md$ 38 | ^_pkgdown\.yml$ 39 | ^netdiffuseR\.tar\.gz$ 40 | ^\.github 41 | netdiffuseR\.Rcheck 42 | 43 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | 4 | # Lines added from https://github.com/krlmlr/r-appveyor/blob/master/.gitattributes 5 | data/* binary 6 | src/* text=lf 7 | R/* text=lf 8 | 9 | # Custom for Visual Studio 10 | *.cs diff=csharp 11 | 12 | # Standard to msysgit 13 | *.doc diff=astextplain 14 | *.DOC diff=astextplain 15 | *.docx diff=astextplain 16 | *.DOCX diff=astextplain 17 | *.dot diff=astextplain 18 | *.DOT diff=astextplain 19 | *.pdf diff=astextplain 20 | *.PDF diff=astextplain 21 | *.rtf diff=astextplain 22 | *.RTF diff=astextplain 23 | 24 | # Images 25 | *.png diff=exif 26 | 27 | -------------------------------------------------------------------------------- /.github/workflows/pkgdown.yml: -------------------------------------------------------------------------------- 1 | # Workflow derived from https://github.com/r-lib/actions/tree/v2/examples 2 | # Need help debugging build failures? Start at https://github.com/r-lib/actions#where-to-find-help 3 | on: 4 | push: 5 | branches: [main, prod] 6 | pull_request: 7 | branches: [main, prod] 8 | release: 9 | types: [published] 10 | workflow_dispatch: 11 | 12 | name: pkgdown 13 | 14 | jobs: 15 | build: 16 | runs-on: ubuntu-latest 17 | # Only restrict concurrency for non-PR jobs 18 | concurrency: 19 | group: pkgdown-${{ github.event_name != 'pull_request' || github.run_id }} 20 | env: 21 | GITHUB_PAT: ${{ secrets.GITHUB_TOKEN }} 22 | permissions: 23 | contents: write 24 | id-token: write 25 | pages: write 26 | steps: 27 | - uses: actions/checkout@v4 28 | 29 | - uses: r-lib/actions/setup-pandoc@v2 30 | with: 31 | pandoc-version: "2.19.2" 32 | 33 | - uses: r-lib/actions/setup-r@v2 34 | 35 | - uses: r-lib/actions/setup-r-dependencies@v2 36 | with: 37 | extra-packages: any::pkgdown 38 | 39 | - name: Install the package 40 | run: R CMD INSTALL . 41 | 42 | - name: Build site 43 | run: "pkgdown::build_site_github_pages(new_process = FALSE, install = FALSE)" 44 | shell: Rscript {0} 45 | 46 | - name: Upload artifact for GH pages deployment 47 | uses: actions/upload-pages-artifact@v3 48 | with: 49 | path: "docs/" 50 | 51 | deploy: 52 | # check builds on PRs but only deploy when main changes 53 | if: ${{ github.event_name != 'pull_request' }} 54 | needs: build 55 | runs-on: ubuntu-latest 56 | permissions: 57 | pages: write 58 | id-token: write 59 | 60 | environment: 61 | name: github-pages 62 | url: ${{ steps.deployment.outputs.page_url }} 63 | 64 | steps: 65 | - name: Deploy to GitHub pages 66 | uses: actions/deploy-pages@v4 67 | -------------------------------------------------------------------------------- /.github/workflows/r.yml: -------------------------------------------------------------------------------- 1 | # For help debugging build failures open an issue on the RStudio community with the 'github-actions' tag. 2 | # https://community.rstudio.com/new-topic?category=Package%20development&tags=github-actions 3 | on: 4 | push: 5 | branches: 6 | - main 7 | - master 8 | pull_request: 9 | branches: 10 | - main 11 | - master 12 | 13 | name: R-CMD-check 14 | 15 | jobs: 16 | R-CMD-check: 17 | runs-on: ${{ matrix.config.os }} 18 | 19 | name: ${{ matrix.config.os }} (${{ matrix.config.r }}) 20 | 21 | strategy: 22 | fail-fast: false 23 | matrix: 24 | config: 25 | - {os: windows-latest, r: 'release'} 26 | - {os: macOS-latest, r: 'release'} 27 | - {os: ubuntu-latest, r: 'release', rspm: "https://packagemanager.rstudio.com/cran/__linux__/focal/latest"} 28 | - {os: ubuntu-latest, r: 'devel', rspm: "https://packagemanager.rstudio.com/cran/__linux__/focal/latest"} 29 | 30 | env: 31 | R_REMOTES_NO_ERRORS_FROM_WARNINGS: true 32 | RSPM: ${{ matrix.config.rspm }} 33 | GITHUB_PAT: ${{ secrets.GITHUB_TOKEN }} 34 | 35 | steps: 36 | - uses: actions/checkout@v4 37 | 38 | - uses: r-lib/actions/setup-r@v2 39 | with: 40 | r-version: ${{ matrix.config.r }} 41 | 42 | - uses: r-lib/actions/setup-pandoc@v2 43 | 44 | - name: Query dependencies 45 | run: | 46 | install.packages('remotes') 47 | saveRDS(remotes::dev_package_deps(dependencies = TRUE), ".github/depends.Rds", version = 2) 48 | writeLines(sprintf("R-%i.%i", getRversion()$major, getRversion()$minor), ".github/R-version") 49 | shell: Rscript {0} 50 | 51 | - name: Restore R package cache 52 | if: runner.os != 'Windows' 53 | uses: actions/cache@v4 54 | with: 55 | path: ${{ env.R_LIBS_USER }} 56 | key: ${{ runner.os }}-${{ hashFiles('.github/R-version') }}-1-${{ hashFiles('.github/depends.Rds') }} 57 | restore-keys: ${{ runner.os }}-${{ hashFiles('.github/R-version') }}-1- 58 | 59 | - name: Install system dependencies 60 | if: runner.os == 'Linux' 61 | run: | 62 | while read -r cmd 63 | do 64 | eval sudo $cmd 65 | done < <(Rscript -e 'writeLines(remotes::system_requirements("ubuntu", "20.04"))') 66 | - name: Install dependencies 67 | run: | 68 | remotes::install_deps(dependencies = TRUE) 69 | remotes::install_cran("rcmdcheck") 70 | shell: Rscript {0} 71 | 72 | - name: Check 73 | env: 74 | _R_CHECK_CRAN_INCOMING_REMOTE_: false 75 | run: | 76 | options(crayon.enabled = TRUE) 77 | rcmdcheck::rcmdcheck(args = c("--no-manual", "--as-cran"), error_on = "error", check_dir = "check") 78 | shell: Rscript {0} 79 | 80 | - name: Upload check results 81 | if: failure() 82 | uses: actions/upload-artifact@main 83 | with: 84 | name: ${{ runner.os }}-r${{ matrix.config.r }}-results 85 | path: check 86 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | Meta 2 | doc 3 | .Rproj.user 4 | .Rhistory 5 | .RData 6 | inst/doc 7 | 8 | # Binary files 9 | *.so 10 | *.o 11 | *.xls* 12 | *.doc* 13 | *.ppt* 14 | *.ods 15 | *.zip 16 | *.gz 17 | *.tar 18 | # Tempfiles 19 | *.dta 20 | *.log 21 | *.out 22 | *.tex 23 | playground/ 24 | doc/ 25 | -------------------------------------------------------------------------------- /DESCRIPTION: -------------------------------------------------------------------------------- 1 | Package: netdiffuseR 2 | Title: Analysis of Diffusion and Contagion Processes on Networks 3 | Version: 1.22.7 4 | Authors@R: c( 5 | person("George", "Vega Yon", email="g.vegayon@gmail.com", role=c("aut", "cre"), 6 | comment=c(ORCID = "0000-0002-3171-0844", what="Rewrite functions with Rcpp, plus new features") 7 | ), 8 | person("Thomas", "Valente", email="tvalente@usc.edu", role=c("aut", "cph"), 9 | comment=c(ORCID="0000-0002-8824-5816", what="R original code")), 10 | person("Anibal", "Olivera Morales", role = c("aut", "ctb"), 11 | comment=c(ORCID="0009-0000-3736-7939", what="Multi-diffusion version")), 12 | person("Stephanie", "Dyal", email="stepharp@usc.edu", role=c("ctb"), comment="Package's first version"), 13 | person("Timothy", "Hayes", email="timothybhayes@gmail.com", role=c("ctb"), comment="Package's first version") 14 | ) 15 | Description: Empirical statistical analysis, visualization and simulation of 16 | diffusion and contagion processes on networks. The package implements algorithms 17 | for calculating network diffusion statistics such as transmission rate, hazard 18 | rates, exposure models, network threshold levels, infectiousness (contagion), 19 | and susceptibility. The package is inspired by work published in Valente, 20 | et al., (2015) ; Valente (1995) , Myers (2000) , Iyengar and others (2011) 22 | , Burt (1987) ; among others. 23 | Depends: 24 | R (>= 3.1.1) 25 | License: MIT + file LICENSE 26 | LazyData: true 27 | Imports: 28 | Rcpp (>= 0.12.1), 29 | sna, 30 | network, 31 | networkDynamic, 32 | Matrix, 33 | MASS, 34 | MatchIt, 35 | SparseM, 36 | methods, 37 | grDevices, 38 | graphics, 39 | stats, 40 | utils, 41 | boot, 42 | igraph, 43 | viridisLite 44 | Suggests: 45 | covr, 46 | testthat, 47 | knitr, 48 | rmarkdown, 49 | ape, 50 | RSiena, 51 | survival 52 | VignetteBuilder: knitr 53 | LinkingTo: Rcpp, RcppArmadillo 54 | RoxygenNote: 7.3.1 55 | Encoding: UTF-8 56 | URL: https://github.com/USCCANA/netdiffuseR, 57 | https://USCCANA.github.io/netdiffuseR/ 58 | BugReports: https://github.com/USCCANA/netdiffuseR/issues 59 | Classification/MSC: 90C35, 90B18, 91D30 60 | Collate: 61 | 'RcppExports.R' 62 | 'imports.r' 63 | 'graph_data.r' 64 | 'adjmat.r' 65 | 'bass.r' 66 | 'bootnet.r' 67 | 'data.r' 68 | 'diffnet-c.R' 69 | 'diffnet-class.r' 70 | 'diffnet-indexing.r' 71 | 'diffnet-methods.r' 72 | 'egonets.R' 73 | 'formula.r' 74 | 'igraph.r' 75 | 'infect_suscept.r' 76 | 'mentor.r' 77 | 'misc.r' 78 | 'moran.r' 79 | 'netmatch.r' 80 | 'network.r' 81 | 'options.R' 82 | 'package-doc.r' 83 | 'plot_diffnet2.r' 84 | 'rewire.r' 85 | 'random_graph.R' 86 | 'rdiffnet.r' 87 | 'read_write_foreign.r' 88 | 'select_egoalter.R' 89 | 'spatial.R' 90 | 'stats.R' 91 | 'struct_equiv.R' 92 | 'struct_test.R' 93 | 'survey_to_diffnet.R' 94 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | YEAR:2020 2 | COPYRIGHT HOLDER:Thomas W. Valente 3 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | # MIT License 2 | 3 | Copyright (c) 2018 Thomas W. Valente 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | VERSION:=$(shell Rscript -e 'x<-readLines("DESCRIPTION");cat(gsub(".+[:]\\s*", "", x[grepl("^Vers", x)]))') 2 | 3 | install: netdiffuseR_$(VERSION).tar.gz 4 | R CMD INSTALL netdiffuseR_$(VERSION).tar.gz 5 | 6 | netdiffuseR_$(VERSION).tar.gz: */*.R inst/NEWS README.md 7 | R CMD build . 8 | 9 | inst/NEWS: NEWS.md 10 | Rscript -e "rmarkdown::pandoc_convert('NEWS.md', 'plain', output='inst/NEWS')"&& \ 11 | head -n 80 inst/NEWS 12 | 13 | README.md: README.Rmd 14 | Rscript -e 'rmarkdown::render("README.Rmd")' 15 | 16 | .PHONY: check checkv clean 17 | 18 | check: netdiffuseR_$(VERSION).tar.gz 19 | R CMD check --as-cran netdiffuseR_$(VERSION).tar.gz 20 | 21 | checkv: netdiffuseR_$(VERSION).tar.gz 22 | R CMD check --as-cran --use-valgrind netdiffuseR_$(VERSION).tar.gz 23 | 24 | clean: 25 | rm -rf netdiffuseR.Rcheck 26 | 27 | man/moran.Rd: R/* src/*.cpp src/*.h 28 | Rscript --vanilla -e 'roxygen2::roxygenize()' 29 | 30 | -------------------------------------------------------------------------------- /R/imports.r: -------------------------------------------------------------------------------- 1 | #' @importFrom Rcpp evalCpp 2 | NULL 3 | 4 | #' @importFrom sna as.sociomatrix.sna 5 | #' @importFrom igraph graph_from_adjacency_matrix set_vertex_attr 6 | #' any_multiple graph_attr_names as_adj is.loop set_graph_attr V permute make_graph 7 | #' layout_nicely graph_attr list.edge.attributes graph_from_adj_list 8 | #' @importFrom network as.edgelist is.multiplex is.directed has.loops as.network 9 | #' get.network.attribute list.vertex.attributes 10 | #' @importFrom networkDynamic networkDynamic network.extract network.collapse 11 | #' @importFrom viridisLite viridis inferno magma 12 | NULL 13 | 14 | #' @useDynLib netdiffuseR, .registration = TRUE 15 | NULL 16 | 17 | # Importing from the Matrix pkg ------------------------------------------------ 18 | 19 | #' @import methods 20 | #' @importClassesFrom Matrix dgCMatrix 21 | #' @importFrom Matrix Matrix rowSums colSums 22 | #' @importMethodsFrom Matrix t 23 | NULL 24 | 25 | #' @importClassesFrom SparseM matrix.csc 26 | NULL 27 | 28 | # Importing from R CORE packages ----------------------------------------------- 29 | 30 | #' @importFrom grDevices grey rgb colorRampPalette blues9 31 | #' @importFrom graphics grid par plot points symbols text layout legend lines 32 | #' matplot plot.new plot.window hist mtext polygon image title .filled.contour 33 | #' box rect 34 | #' @importFrom stats complete.cases runif reshape setNames ftable sd pnorm var 35 | #' as.formula optim nls coef 36 | #' @importFrom utils getFromNamespace head str combn 37 | #' @importFrom boot boot 38 | #' @importFrom MASS bandwidth.nrd kde2d 39 | #' @importFrom MatchIt matchit 40 | NULL 41 | 42 | release_questions <- function() { 43 | c( 44 | "Have you updated the inst/NEWS file?", 45 | "Have you changed the version+dates in DESCRIPTION and NEWS.md?", 46 | "Have you added all new files to GIT?", 47 | "Have you clean the vignettes file (source)?" 48 | ) 49 | } 50 | -------------------------------------------------------------------------------- /R/moran.r: -------------------------------------------------------------------------------- 1 | #' Computes Moran's I correlation index 2 | #' 3 | #' Natively built for computing Moran's I on \code{dgCMatrix} objects, this 4 | #' routine allows computing the I on large sparse matrices (graphs). Part of 5 | #' its implementation was based on \code{\link[ape:Moran.I]{ape::Moran.I}}, 6 | #' which computes the I for dense matrices. 7 | #' 8 | #' @param x Numeric vector of size \eqn{n}. 9 | #' @param w Numeric matrix of size \eqn{n\times n}{n * n}. Weights. It can be 10 | #' either a object of class \code{\link{matrix}} or \code{\link[Matrix:dgCMatrix-class]{dgCMatrix}} 11 | #' from the \code{\link[Matrix]{Matrix}} package. 12 | #' @param normalize.w Logical scalar. When TRUE normalizes rowsums to one (or zero). 13 | #' @param alternative Character String. Specifies the alternative hypothesis that 14 | #' is tested against the null of no autocorrelation; must be of one \code{"two.sided"}, 15 | #' \code{"less"}, or \code{"greater"}. 16 | #' @export 17 | #' @details 18 | #' In the case that the vector \code{x} is close to constant (degenerate random 19 | #' variable), the statistic becomes irrelevant, and furthermore, the standard error 20 | #' tends to be undefined (\code{NaN}). 21 | #' 22 | #' @family statistics 23 | #' @family Functions for inference 24 | #' @return A list of class \code{diffnet_moran} with the following elements: 25 | #' \item{observed}{Numeric scalar. Observed correlation index.} 26 | #' \item{expected}{Numeric scalar. Expected correlation index equal to \eqn{-1/(N-1)}.} 27 | #' \item{sd}{Numeric scalar. Standard error under the null.} 28 | #' \item{p.value}{Numeric scalar. p-value of the specified \code{alternative}.} 29 | #' @references 30 | #' 31 | #' Moran's I. (2015, September 3). In Wikipedia, The Free Encyclopedia. 32 | #' Retrieved 06:23, December 22, 2015, from \url{https://en.wikipedia.org/w/index.php?title=Moran\%27s_I&oldid=679297766} 33 | #' 34 | #' @examples 35 | #' 36 | #' if (require("ape")) { 37 | #' 38 | #' # Generating a small random graph 39 | #' set.seed(123) 40 | #' graph <- rgraph_ba(t = 4) 41 | #' w <- approx_geodesic(graph) 42 | #' x <- rnorm(5) 43 | #' 44 | #' # Computing Moran's I 45 | #' moran(x, w) 46 | #' 47 | #' # Comparing with the ape's package version 48 | #' ape::Moran.I(x, as.matrix(w)) 49 | #' 50 | #' } 51 | #' 52 | #' @author George G. Vega Yon 53 | moran <- function(x, w, normalize.w=TRUE, alternative = "two.sided") { 54 | if (!inherits(w, "matrix") & !inherits(w, "dgCMatrix")) 55 | stop("-w- must be either a matrix or a dgCMatrix.") 56 | 57 | if (any(!is.finite(x))) 58 | stop("-x- must have only numbers.") 59 | 60 | if (inherits(w, "matrix")) 61 | w <- methods::as(w, "dgCMatrix") 62 | 63 | if (normalize.w) 64 | w <- w/(rowSums(w) + 1e-20) 65 | 66 | res <- moran_cpp(x, w) 67 | 68 | # Computing pval 69 | pv <- with(res, pnorm(observed, mean = expected, sd = sd)) 70 | 71 | # Checking alternatives 72 | alternative <- match.arg( 73 | alternative, c("two.sided", "less", "greater") 74 | ) 75 | 76 | if (alternative == "two.sided") 77 | pv <- if (res$observed <= res$expected) 78 | 2 * pv 79 | else 2 * (1 - pv) 80 | if (alternative == "greater") 81 | pv <- 1 - pv 82 | 83 | # Returning 84 | structure( 85 | c(res, p.value = pv), 86 | class = "diffnet_moran" 87 | ) 88 | 89 | } 90 | 91 | -------------------------------------------------------------------------------- /R/options.R: -------------------------------------------------------------------------------- 1 | #' \pkg{netdiffuseR} default options 2 | #' @details Set of default options used by the package. These can be retrieved 3 | #' via \code{\link{getOption}} using the prefix \code{diffnet} (see examples) 4 | #' @examples 5 | #' getOption("diffnet.undirected") 6 | #' getOption("diffnet.multiple") 7 | #' getOption("diffnet.self") 8 | #' @return The full list of options follows: 9 | #' \item{undirected}{FALSE} 10 | #' \item{self}{FALSE} 11 | #' \item{multiple}{FALSE} 12 | #' \item{tol}{1e-8 (used for package testing)} 13 | #' \item{valued}{FALSE} 14 | #' \item{outgoing}{TRUE} 15 | #' \item{keep.isolates}{TRUE} 16 | #' \item{minmax.relative.size}{\code{c(0.025, 0.05)}} 17 | #' @name netdiffuseR-options 18 | #' @author George G. Vega Yon 19 | NULL 20 | .onLoad <- function(libname, pkgname) { 21 | options( 22 | diffnet.undirected=FALSE, 23 | diffnet.self=FALSE, 24 | diffnet.multiple=FALSE, 25 | diffnet.tol=1e-8, 26 | diffnet.valued=FALSE, 27 | diffnet.outgoing=TRUE, 28 | diffnet.keep.isolates=TRUE, 29 | diffnet.minmax.relative.size = c(0.01, 0.03) 30 | ) 31 | } 32 | -------------------------------------------------------------------------------- /R/package-doc.r: -------------------------------------------------------------------------------- 1 | #' netdiffuseR 2 | #' 3 | #' Analysis of Diffusion and Contagion Processes on Networks 4 | #' 5 | #' @description 6 | #' 7 | #' Statistical analysis, visualization and simulation of diffusion and contagion 8 | #' processes on networks. The package implements algorithms for 9 | #' calculating stats such as innovation threshold levels, infectiousness 10 | #' (contagion) and susceptibility, and hazard rates as presented in Burt (1987), 11 | #' Valente (1995), and Myers (2000) (among others). 12 | #' 13 | #' You can access to the project website at 14 | #' \url{https://github.com/USCCANA/netdiffuseR} 15 | #' 16 | #' @section Acknowledgements: 17 | #' netdiffuseR was created with the support of grant R01 CA157577 from the National Cancer Institute/National Institutes of Health. 18 | #' 19 | #' @section Workshops and Tutorials: 20 | #' 21 | #' Online you can find several learning resources: 22 | #' 23 | #' \itemize{ 24 | #' \item Sunbelt 2016 \url{https://github.com/USCCANA/netdiffuser-sunbelt2016} 25 | #' \item NASN 2017 \url{https://github.com/USCCANA/netdiffuser-nasn2017} 26 | #' \item Sunbelt 2018 \url{https://github.com/USCCANA/netdiffuser-sunbelt2018} 27 | #' } 28 | #' 29 | #' @aliases netdiffuseR-package 30 | #' @name netdiffuseR 31 | #' 32 | #' @author George G. Vega Yon & Thomas W. Valente 33 | #' 34 | NULL 35 | -------------------------------------------------------------------------------- /R/spatial.R: -------------------------------------------------------------------------------- 1 | #' Creates a square matrix suitable for spatial statistics models. 2 | #' @templateVar self TRUE 3 | #' @templateVar valued TRUE 4 | #' @template graph_template 5 | #' @param nper Integer scalar. Number of time periods of the graph. 6 | #' @param ... Further arguments to be passed to the method. 7 | #' @return A square matrix of class \code{\link[Matrix:dgCMatrix-class]{dgCMatrix}} of 8 | #' size \code{(nnode(g)*nper)^2} 9 | #' @examples 10 | #' # Simple example ------------------------------------------------------------ 11 | #' set.seed(23) 12 | #' g <- rgraph_er(n=10, p=.5, t=2,undirected=TRUE) 13 | #' 14 | #' # What we've done: A list with 2 bernoulli graphs 15 | #' g 16 | #' 17 | #' # Expanding to a 20*20 matrix with structural zeros on the diagonal 18 | #' # and on cell 'off' adjacency matrix 19 | #' diag_expand(g) 20 | #' @export 21 | diag_expand <- function(...) UseMethod("diag_expand") 22 | 23 | .diag_expand <- function( 24 | graph, 25 | nper, 26 | self = getOption("diffnet.self"), 27 | valued = getOption("diffnet.valued") 28 | ) { 29 | 30 | # Checking class 31 | meta <- classify_graph(graph) 32 | 33 | # Getting the info 34 | d <- with(meta, c(n, n, nper)) 35 | if (missing(nper)) nper <- d[3] 36 | 37 | if (!nper) 38 | stop("It must be a dynamic graph. nslices() = 0.") 39 | 40 | # checking options 41 | if (!self) { 42 | graph <- Map(function(x) { 43 | Matrix::diag(x) <- rep(0,nnodes(graph)) 44 | x 45 | }, x = graph) 46 | } 47 | if (!valued) 48 | graph <- Map(function(x) { 49 | x@x <- rep(1, length(x@x)) 50 | x 51 | }, x=graph) 52 | 53 | # Structure 54 | W <- methods::new("dgCMatrix", Dim=d[1:2]*nper, p=rep(0L,d[1]*nper+1L)) 55 | 56 | # Filling 57 | for (p in 1:nper) { 58 | i <- ((p-1)*d[1]+1):(d[1]*p) 59 | j <- ((p-1)*d[2]+1):(d[2]*p) 60 | 61 | W[i,j] <- graph[[p]] 62 | } 63 | 64 | # Autolag 65 | al <- cbind(1:d[1], 1:d[2]) 66 | 67 | W 68 | } 69 | 70 | #' @export 71 | #' @rdname diag_expand 72 | diag_expand.list <- function( 73 | graph, 74 | self = is_self(graph), 75 | valued = is_valued(graph), 76 | ... 77 | ) { 78 | .diag_expand(graph, length(graph), self, valued) 79 | } 80 | 81 | 82 | #' @export 83 | #' @rdname diag_expand 84 | diag_expand.diffnet <- function( 85 | graph, 86 | self = is_self(graph), 87 | valued = is_valued(graph), 88 | ... 89 | ) { 90 | .diag_expand(graph$graph, graph$meta$nper, self, valued) 91 | } 92 | 93 | #' @export 94 | #' @rdname diag_expand 95 | diag_expand.matrix <- function( 96 | graph, 97 | nper, 98 | self = is_self(graph), 99 | valued = is_valued(graph), 100 | ...) { 101 | 102 | .diag_expand(list(methods::as(graph, "dgCMatrix")), nper, self, valued) 103 | } 104 | 105 | 106 | #' @export 107 | #' @rdname diag_expand 108 | diag_expand.array <- function( 109 | graph, 110 | self = is_self(graph), 111 | valued = is_valued(graph), 112 | ... 113 | ) { 114 | 115 | graph <- apply(graph, 3, function(x) methods::as(x, "dgCMatrix")) 116 | diag_expand(graph, nslices(graph), self, valued) 117 | 118 | } 119 | 120 | #' @export 121 | #' @rdname diag_expand 122 | diag_expand.dgCMatrix <- function( 123 | graph, 124 | nper, 125 | self = is_self(graph), 126 | valued = is_valued(graph), 127 | ...) { 128 | 129 | .diag_expand(list(graph), nper, self, valued) 130 | } 131 | -------------------------------------------------------------------------------- /README_files/figure-gfm/Adopters-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/USCCANA/netdiffuseR/1efc0be4539d23ab800187c73551624834038e00/README_files/figure-gfm/Adopters-1.png -------------------------------------------------------------------------------- /README_files/figure-gfm/BoringThreshold, plot_threshold-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/USCCANA/netdiffuseR/1efc0be4539d23ab800187c73551624834038e00/README_files/figure-gfm/BoringThreshold, plot_threshold-1.png -------------------------------------------------------------------------------- /README_files/figure-gfm/Hazard-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/USCCANA/netdiffuseR/1efc0be4539d23ab800187c73551624834038e00/README_files/figure-gfm/Hazard-1.png -------------------------------------------------------------------------------- /README_files/figure-gfm/NiceThreshold-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/USCCANA/netdiffuseR/1efc0be4539d23ab800187c73551624834038e00/README_files/figure-gfm/NiceThreshold-1.png -------------------------------------------------------------------------------- /README_files/figure-gfm/mosaic-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/USCCANA/netdiffuseR/1efc0be4539d23ab800187c73551624834038e00/README_files/figure-gfm/mosaic-1.png -------------------------------------------------------------------------------- /README_files/figure-gfm/plot_diffnet-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/USCCANA/netdiffuseR/1efc0be4539d23ab800187c73551624834038e00/README_files/figure-gfm/plot_diffnet-1.png -------------------------------------------------------------------------------- /README_files/figure-gfm/plot_diffnet2 with map-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/USCCANA/netdiffuseR/1efc0be4539d23ab800187c73551624834038e00/README_files/figure-gfm/plot_diffnet2 with map-1.png -------------------------------------------------------------------------------- /README_files/figure-gfm/plot_diffnet2-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/USCCANA/netdiffuseR/1efc0be4539d23ab800187c73551624834038e00/README_files/figure-gfm/plot_diffnet2-1.png -------------------------------------------------------------------------------- /README_files/figure-gfm/plot_infectsuscept-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/USCCANA/netdiffuseR/1efc0be4539d23ab800187c73551624834038e00/README_files/figure-gfm/plot_infectsuscept-1.png -------------------------------------------------------------------------------- /README_files/figure-gfm/plot_infectsuscept-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/USCCANA/netdiffuseR/1efc0be4539d23ab800187c73551624834038e00/README_files/figure-gfm/plot_infectsuscept-2.png -------------------------------------------------------------------------------- /README_files/figure-markdown_github/Adopters-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/USCCANA/netdiffuseR/1efc0be4539d23ab800187c73551624834038e00/README_files/figure-markdown_github/Adopters-1.png -------------------------------------------------------------------------------- /README_files/figure-markdown_github/BoringThreshold, plot_threshold-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/USCCANA/netdiffuseR/1efc0be4539d23ab800187c73551624834038e00/README_files/figure-markdown_github/BoringThreshold, plot_threshold-1.png -------------------------------------------------------------------------------- /README_files/figure-markdown_github/Hazard-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/USCCANA/netdiffuseR/1efc0be4539d23ab800187c73551624834038e00/README_files/figure-markdown_github/Hazard-1.png -------------------------------------------------------------------------------- /README_files/figure-markdown_github/NiceThreshold-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/USCCANA/netdiffuseR/1efc0be4539d23ab800187c73551624834038e00/README_files/figure-markdown_github/NiceThreshold-1.png -------------------------------------------------------------------------------- /README_files/figure-markdown_github/mosaic-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/USCCANA/netdiffuseR/1efc0be4539d23ab800187c73551624834038e00/README_files/figure-markdown_github/mosaic-1.png -------------------------------------------------------------------------------- /README_files/figure-markdown_github/plot_diffnet-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/USCCANA/netdiffuseR/1efc0be4539d23ab800187c73551624834038e00/README_files/figure-markdown_github/plot_diffnet-1.png -------------------------------------------------------------------------------- /README_files/figure-markdown_github/plot_diffnet2 with map-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/USCCANA/netdiffuseR/1efc0be4539d23ab800187c73551624834038e00/README_files/figure-markdown_github/plot_diffnet2 with map-1.png -------------------------------------------------------------------------------- /README_files/figure-markdown_github/plot_diffnet2-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/USCCANA/netdiffuseR/1efc0be4539d23ab800187c73551624834038e00/README_files/figure-markdown_github/plot_diffnet2-1.png -------------------------------------------------------------------------------- /README_files/figure-markdown_github/plot_infectsuscept-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/USCCANA/netdiffuseR/1efc0be4539d23ab800187c73551624834038e00/README_files/figure-markdown_github/plot_infectsuscept-1.png -------------------------------------------------------------------------------- /README_files/figure-markdown_github/plot_infectsuscept-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/USCCANA/netdiffuseR/1efc0be4539d23ab800187c73551624834038e00/README_files/figure-markdown_github/plot_infectsuscept-2.png -------------------------------------------------------------------------------- /_pkgdown.yml: -------------------------------------------------------------------------------- 1 | template: 2 | params: 3 | ganalytics: UA-40608305-5 4 | 5 | -------------------------------------------------------------------------------- /cleanup: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | rm -f config.* src/Makevars 4 | -------------------------------------------------------------------------------- /configure.ac: -------------------------------------------------------------------------------- 1 | # -*- Autoconf -*- 2 | # netdiffuseR configure.ac 3 | # (with some code borrowed from RcppArmadillo configure.ac 4 | # and ARTP2 configure.ac) 5 | # 6 | # Process this file with autoconf to produce a configure script. 7 | 8 | AC_PREREQ([2.69]) 9 | 10 | AC_INIT(netdiffuseR, m4_esyscmd_s([awk '/^Version:/ {print $2}' DESCRIPTION])) 11 | 12 | ## Set R_HOME, respecting an environment variable if one is set 13 | : ${R_HOME=$(R RHOME)} 14 | if test -z "${R_HOME}"; then 15 | AC_MSG_ERROR([Could not determine R_HOME.]) 16 | fi 17 | 18 | ## Use R to set CXX and CXXFLAGS 19 | CXX=$(${R_HOME}/bin/R CMD config CXX) 20 | CXXFLAGS=$("${R_HOME}/bin/R" CMD config CXXFLAGS) 21 | 22 | ## We are using C++ 23 | AC_LANG(C++) 24 | AC_REQUIRE_CPP 25 | 26 | dnl this the meat of R's m4/openmp.m4 27 | OPENMP_[]_AC_LANG_PREFIX[]FLAGS= 28 | AC_ARG_ENABLE([openmp], 29 | [AS_HELP_STRING([--disable-openmp], [do not use OpenMP])]) 30 | if test "$enable_openmp" != no; then 31 | AC_CACHE_CHECK([for $[]_AC_CC[] option to support OpenMP], 32 | [ac_cv_prog_[]_AC_LANG_ABBREV[]_openmp], 33 | [AC_LINK_IFELSE([_AC_LANG_OPENMP], 34 | [ac_cv_prog_[]_AC_LANG_ABBREV[]_openmp='none needed'], 35 | [ac_cv_prog_[]_AC_LANG_ABBREV[]_openmp='unsupported' 36 | for ac_option in -fopenmp -xopenmp -qopenmp \ 37 | -openmp -mp -omp -qsmp=omp -homp \ 38 | -fopenmp=libomp \ 39 | -Popenmp --openmp; do 40 | ac_save_[]_AC_LANG_PREFIX[]FLAGS=$[]_AC_LANG_PREFIX[]FLAGS 41 | _AC_LANG_PREFIX[]FLAGS="$[]_AC_LANG_PREFIX[]FLAGS $ac_option" 42 | AC_LINK_IFELSE([_AC_LANG_OPENMP], 43 | [ac_cv_prog_[]_AC_LANG_ABBREV[]_openmp=$ac_option]) 44 | _AC_LANG_PREFIX[]FLAGS=$ac_save_[]_AC_LANG_PREFIX[]FLAGS 45 | if test "$ac_cv_prog_[]_AC_LANG_ABBREV[]_openmp" != unsupported; then 46 | break 47 | fi 48 | done])]) 49 | case $ac_cv_prog_[]_AC_LANG_ABBREV[]_openmp in #( 50 | "none needed" | unsupported) 51 | ;; #( 52 | *) 53 | OPENMP_[]_AC_LANG_PREFIX[]FLAGS=$ac_cv_prog_[]_AC_LANG_ABBREV[]_openmp ;; 54 | esac 55 | fi 56 | 57 | AC_SUBST(OPENMP_CXXFLAGS) 58 | AC_CONFIG_FILES([src/Makevars]) 59 | AC_OUTPUT 60 | 61 | -------------------------------------------------------------------------------- /cran-comments.md: -------------------------------------------------------------------------------- 1 | ## Test environments 2 | 3 | * Local: Ubuntu 18.04.4 LTS, R 3.6.2 4 | * Travis: Ubuntu 16.04.6 LTS, R 3.6.2 5 | * Travis: Ubuntu 16.04.6 LTS, R Under development (unstable) (2020-02-10 r77788) 6 | * Travis: macOS Mojave 10.14.4, R 3.6.2 7 | * AppVeyor: Windows Server 2012 R2 x64, R 3.5.3 8 | * AppVeyor: Windows Server 2012 R2 x64, R 3.6.2 9 | * AppVeyor: Windows Server 2012 R2 x64, R Under development (unstable) (2020-02-10 r77789) 10 | 11 | ## R CMD check results 12 | 13 | * This package was taken out of CRAN due to problems regarding matrices are now 14 | arrays. This issue has been solved by changing the way in which the package 15 | was testing for classes (array vs matrix) and has been throughly tested. 16 | 17 | * No reverse dependencies to be checked. 18 | 19 | ## Reverse dependencies 20 | 21 | There are no reverse dependencies. 22 | -------------------------------------------------------------------------------- /data-raw/SAMPSON.DAT.R: -------------------------------------------------------------------------------- 1 | file.copy("data-raw/SAMPSON.DAT", "inst/extdata/") 2 | -------------------------------------------------------------------------------- /data-raw/SAMPSON.R: -------------------------------------------------------------------------------- 1 | file.copy("data-raw/SAMPSON.NET", "inst/extdata/") 2 | -------------------------------------------------------------------------------- /data-raw/SAMPSONL.NET: -------------------------------------------------------------------------------- 1 | *Vertices 18 2 | 1 "ROMUL_10" 3 | 2 "BONAVEN_5" 4 | 3 "AMBROSE_9" 5 | 4 "BERTH_6" 6 | 5 "PETER_4" 7 | 6 "LOUIS_11" 8 | 7 "VICTOR_8" 9 | 8 "WINF_12" 10 | 9 "JOHN_1" 11 | 10 "GREG_2" 12 | 11 "HUGH_14" 13 | 12 "BONI_15" 14 | 13 "MARK_7" 15 | 14 "ALBERT_16" 16 | 15 "AMAND_13" 17 | 16 "BASIL_3" 18 | 17 "ELIAS_17" 19 | 18 "SIMP_18" 20 | *Arcslist :1 "SAMPLK1" 21 | 1 3 5 14 22 | 2 1 7 14 23 | 3 1 2 17 24 | 4 5 6 10 25 | 5 4 11 13 26 | 6 1 4 9 27 | 7 2 8 16 28 | 8 1 2 9 29 | 9 5 8 16 30 | 10 4 8 14 31 | 11 5 8 14 32 | 12 1 2 14 33 | 13 5 7 18 34 | 14 1 11 12 15 35 | 15 1 2 14 36 | 16 1 2 7 37 | 17 3 13 18 38 | 18 1 2 7 39 | *Arcslist :2 "SAMPLK2" 40 | 1 2 5 8 41 | 2 1 7 12 15 42 | 3 1 17 18 43 | 4 5 6 11 44 | 5 1 4 11 45 | 6 1 4 9 46 | 7 1 2 16 47 | 8 4 6 10 48 | 9 5 8 12 49 | 10 4 5 13 50 | 11 4 5 16 51 | 12 1 2 14 52 | 13 5 7 18 53 | 14 1 2 12 15 54 | 15 1 2 5 14 55 | 16 2 7 12 56 | 17 2 3 18 57 | 18 2 13 17 58 | *Arcslist :3 "SAMPLK3" 59 | 1 3 12 14 60 | 2 1 7 12 61 | 3 1 13 17 18 62 | 4 5 6 11 63 | 5 4 9 11 64 | 6 4 5 9 65 | 7 2 12 16 66 | 8 4 6 9 67 | 9 5 8 12 68 | 10 4 5 9 13 69 | 11 5 8 14 70 | 12 1 2 7 71 | 13 5 7 18 72 | 14 1 12 15 73 | 15 2 7 12 74 | 16 2 7 15 75 | 17 2 3 18 76 | 18 2 3 17 77 | *Arcslist :4 "SAMPDLK" 78 | 3 16 17 18 79 | 4 10 13 16 17 80 | 5 9 10 11 81 | 6 9 10 16 82 | 7 10 11 16 83 | 9 1 10 13 84 | 10 5 7 15 85 | 11 5 7 17 86 | 12 5 15 16 87 | 13 4 5 7 88 | 14 5 16 17 89 | 15 4 8 10 90 | 16 4 5 10 14 91 | 17 4 5 7 92 | 18 1 5 7 93 | *Arcslist :5 "SAMPES" 94 | 2 3 5 6 95 | 3 5 7 9 96 | 4 5 6 97 | 5 1 4 6 98 | 6 2 3 99 | 7 2 4 5 100 | 8 9 10 11 101 | 9 2 7 8 102 | 10 2 7 9 103 | 11 8 9 10 12 104 | 12 9 10 11 105 | 13 8 10 12 14 106 | 14 8 10 12 13 107 | 15 2 6 13 108 | 16 9 15 17 18 109 | 17 10 15 16 18 110 | 18 10 16 17 111 | *Arcslist :6 "SAMPDES" 112 | 2 16 17 18 113 | 3 15 17 18 114 | 4 7 13 16 17 115 | 5 9 10 11 116 | 6 9 10 14 16 117 | 7 11 17 18 118 | 9 10 13 16 119 | 10 5 15 16 120 | 11 5 6 15 17 18 121 | 12 5 6 16 17 18 122 | 13 4 5 7 16 17 123 | 14 5 16 17 18 124 | 15 4 10 16 125 | 16 4 5 10 126 | 17 4 5 7 127 | 18 1 4 5 7 128 | *Arcslist :7 "SAMPIN" 129 | 2 5 6 10 130 | 3 5 9 10 131 | 4 3 5 10 132 | 5 1 4 6 133 | 6 2 3 5 134 | 7 3 5 6 9 135 | 8 9 10 13 136 | 9 8 10 13 137 | 10 8 9 13 138 | 11 8 9 10 12 139 | 12 10 11 13 140 | 13 8 10 14 141 | 14 10 12 13 142 | 15 2 6 13 143 | 16 9 15 17 144 | 17 10 16 18 145 | 18 10 16 17 146 | *Arcslist :8 "SAMPNIN" 147 | 2 16 17 18 148 | 3 8 17 18 149 | 4 13 17 18 150 | 5 9 10 11 151 | 6 13 17 18 152 | 7 8 14 15 153 | 9 1 14 18 154 | 10 5 15 155 | 11 5 15 17 18 156 | 12 5 15 16 157 | 13 4 5 7 16 17 158 | 14 5 6 16 159 | 15 4 8 10 160 | 16 4 5 10 161 | 17 4 5 7 162 | 18 4 5 6 163 | *Arcslist :9 "SAMPPR" 164 | 4 3 5 6 165 | 5 1 4 6 166 | 6 5 7 14 167 | 7 4 5 6 168 | 9 8 11 17 169 | 10 8 9 13 170 | 11 9 10 12 14 171 | 12 9 10 11 172 | 13 10 12 14 173 | 14 10 12 13 174 | 15 2 6 175 | 16 9 15 17 176 | 18 9 10 17 177 | *Arcslist :10 "SAMNPR" 178 | 4 13 15 17 18 179 | 5 10 11 13 180 | 6 11 17 18 181 | 7 16 17 18 182 | 8 11 17 18 183 | 9 6 16 18 184 | 10 16 185 | 11 5 6 16 186 | 12 5 15 16 18 187 | 13 4 5 16 188 | 14 5 15 16 17 18 189 | 15 10 17 18 190 | 16 5 10 11 191 | -------------------------------------------------------------------------------- /data-raw/SAMPSONL.R: -------------------------------------------------------------------------------- 1 | file.copy("data-raw/SAMPSONL.NET", "inst/extdata/") 2 | -------------------------------------------------------------------------------- /data-raw/brfarmers.R: -------------------------------------------------------------------------------- 1 | rm(list=ls()) 2 | library(foreign) 3 | source("data-raw/listing_duplicated_columns.r") 4 | # Preparing the data ----------------------------------------------------------- 5 | brfarmers <- read.dta("data-raw/bf_v2.dta") 6 | 7 | listing_duplicated_columns(brfarmers) 8 | # brfarmers <- subset(brfarmers, select = c(-ado)) 9 | 10 | save(brfarmers,file = "data/brfarmers.rdata", 11 | compress = "xz") 12 | -------------------------------------------------------------------------------- /data-raw/fakeDynEdgelist.R: -------------------------------------------------------------------------------- 1 | rm(list=ls()) 2 | load("data/fakesurveyDyn.rdata") 3 | 4 | diffnet <- survey_to_diffnet( 5 | dat=fakesurveyDyn, 6 | idvar = "id", 7 | netvars = c("net1", "net2", "net3"), 8 | toavar = "toa", 9 | groupvar="group", 10 | timevar = "time", 11 | undirected = FALSE, 12 | multiple=TRUE) 13 | 14 | fakeDynEdgelist <- data.frame(adjmat_to_edgelist(diffnet$graph,undirected = FALSE)) 15 | fakeDynEdgelist[,1] <- factor(diffnet$meta$ids[fakeDynEdgelist[,1]], diffnet$meta$ids) 16 | fakeDynEdgelist[,2] <- factor(diffnet$meta$ids[fakeDynEdgelist[,2]], diffnet$meta$ids) 17 | fakeDynEdgelist[,4] <- as.integer(fakeDynEdgelist[,4] ) 18 | 19 | save(fakeDynEdgelist, file="data/fakeDynEdgelist.rdata") 20 | -------------------------------------------------------------------------------- /data-raw/fakeEdgelist.R: -------------------------------------------------------------------------------- 1 | rm(list=ls()) 2 | load("data/fakesurvey.rdata") 3 | 4 | diffnet <- survey_to_diffnet( 5 | dat=fakesurvey, 6 | idvar = "id", 7 | netvars = c("net1", "net2", "net3"), 8 | toavar = "toa", 9 | groupvar="group", 10 | undirected = FALSE, 11 | multiple=TRUE) 12 | 13 | fakeEdgelist <- data.frame(adjmat_to_edgelist(diffnet$graph,undirected = FALSE)) 14 | fakeEdgelist[,1] <- factor(diffnet$meta$ids[fakeEdgelist[,1]], diffnet$meta$ids) 15 | fakeEdgelist[,2] <- factor(diffnet$meta$ids[fakeEdgelist[,2]], diffnet$meta$ids) 16 | fakeEdgelist[,4] <- as.integer(fakeEdgelist[,4] ) 17 | 18 | # Creating a unique 19 | fakeEdgelist$time <- NULL 20 | fakeEdgelist <- unique(fakeEdgelist) 21 | 22 | save(fakeEdgelist, file="data/fakeEdgelist.rdata") 23 | -------------------------------------------------------------------------------- /data-raw/fakesurvey.R: -------------------------------------------------------------------------------- 1 | rm(list=ls()) 2 | fakesurvey <- read.csv("data-raw/fakesurvey.csv") 3 | fakesurvey$note <- as.character(fakesurvey$note) 4 | save(fakesurvey, file = "data/fakesurvey.rdata") 5 | -------------------------------------------------------------------------------- /data-raw/fakesurvey.csv: -------------------------------------------------------------------------------- 1 | id,toa,group,net1,net2,net3,age,gender,note 2 | 1,1,1,NA,NA,NA,30,M,No nominations 3 | 2,5,1,3,1,NA,35,F,Nothing weird 4 | 3,5,1,NA,2,NA,31,F,Only nominates in net2 5 | 4,3,1,6,5,NA,30,M,Nominates someone who wasn't interview 6 | 5,2,1,4,4,3,40,F,Nominates 4 two times 7 | 1,4,2,3,4,8,29,F,Only nominates outsiders 8 | 2,3,2,3,NA,NA,35,M,Isolated 9 | 5,3,2,10,1,NA,50,M,Nothing weird 10 | 10,NA,2,5,1,NA,19,F,Non-adopter 11 | -------------------------------------------------------------------------------- /data-raw/fakesurveyDyn.R: -------------------------------------------------------------------------------- 1 | rm(list=ls()) 2 | 3 | fakesurvey <- read.csv("data-raw/fakesurvey.csv") 4 | fakesurvey$note <- as.character(fakesurvey$note) 5 | 6 | dat <- rbind(fakesurvey) 7 | dat$toa <- sample(1990:1991, nrow(dat), TRUE) 8 | dat <- rbind(dat, dat) 9 | 10 | dat$time <- c( 11 | rep(1990, nrow(fakesurvey)), 12 | rep(1991, nrow(fakesurvey)) 13 | ) 14 | 15 | # Aging people 16 | dat$age[dat$time==1991] <- 17 | dat$age[dat$time==1991] + 1 18 | 19 | # Changing some links (isolated wont be such anymore!) 20 | dat$net1[with(dat, which(id==2 & group == 2 & time == 1991))] <- 1 21 | dat$note[with(dat, which(id==2 & group == 2 & time == 1991))] <- "Now is not isolated!" 22 | dat$note[dat$time==1990] <- paste("First wave:",dat$note[dat$time==1990]) 23 | dat$note[dat$time==1991] <- paste("Second wave:",dat$note[dat$time==1991]) 24 | 25 | fakesurveyDyn <- dat 26 | 27 | save(fakesurveyDyn, file="data/fakesurveyDyn.rdata") 28 | 29 | # Playing with the data 30 | library(netdiffuseR) 31 | 32 | idvar <- "id" 33 | netvars <- paste0("net", 1:3) 34 | groupvar <- "group" 35 | 36 | x <- survey_to_diffnet( 37 | dat, "id", c("net1", "net2", "net3"), "toa", "group" , 38 | timevar = "time", keep.isolates = TRUE) 39 | 40 | plot_diffnet(x, vertex.cex = 1.5, displaylabels = TRUE) 41 | -------------------------------------------------------------------------------- /data-raw/kfamilyDiffNet.R: -------------------------------------------------------------------------------- 1 | rm(list=ls()) 2 | 3 | library(foreign) 4 | 5 | # kfamily <- read.dta("data-raw/kfp_v3_labels_fixed.dta") 6 | load("data/kfamily.rdata") 7 | 8 | # Subsetting 9 | netvars <- names(kfamily)[grepl("^net", names(kfamily))] 10 | 11 | # Replacing 0s with NAs 12 | for (i in netvars) 13 | kfamily[[i]] <- ifelse(kfamily[[i]]==0,NA, kfamily[[i]]) 14 | 15 | # Creating an ID 16 | for (i in c("id",netvars)) 17 | kfamily[[i]] <- kfamily[[i]] + kfamily$village*1000L 18 | 19 | surveyed <- kfamily$id 20 | 21 | length(table(unlist(kfamily[,netvars]))) 22 | 23 | # Removing farmes that are not part of the experiment, i.e. weren't 24 | # surveyed. 25 | for (i in netvars) 26 | kfamily[[i]][which(!(kfamily[[i]] %in% surveyed))] <- NA 27 | 28 | length(table(unlist(kfamily[,netvars]))) 29 | 30 | # [2016-02-24]: keep.isolates working 31 | # # Adding autoedges to farmers that are isolated 32 | # isolated <- which(apply(kfamily[, netvars], 1, function(x) all(is.na(x)))) 33 | # kfamily[isolated, netvars[1]] <- kfamily$id[isolated] 34 | 35 | length(table(unlist(kfamily[,netvars]))) 36 | 37 | # Reshaping data 38 | kfamily.long <- reshape( 39 | kfamily[, c("id",netvars)], v.names= "net", 40 | varying = netvars, 41 | timevar = "level", idvar="id", direction="long") 42 | 43 | library(netdiffuseR) 44 | 45 | # Coercing the edgelist to an adjacency matrix. Here we are assuming that the 46 | # network is constant through time. 47 | graph <- with( 48 | kfamily.long, 49 | edgelist_to_adjmat(cbind(id, net), t=11, undirected=FALSE, 50 | keep.isolates = TRUE, multiple=TRUE) 51 | ) 52 | 53 | # [2016-02-24]: keep.isolates working 54 | # # Here we are retrieving the set of individuals who actually were used in the 55 | # # network (as these are not isolated nodes) 56 | # used.vertex <- rownames(graph[[1]]) 57 | # 58 | # # Create the vector (subset) of times of adoption using only the individuals 59 | # # that are included in the adjacency matrix 60 | # toa <- kfamily$toa[kfamily$id %in% used.vertex] 61 | toa <- kfamily$toa 62 | 63 | # Creating a diffnet ----------------------------------------------------------- 64 | kfamilyDiffNet <- as_diffnet(graph, toa, vertex.static.attrs = subset(kfamily, select=c(-id,-toa)), 65 | name = "Korean Family Planning", 66 | behavior = "Family Planning Methods") 67 | # [2016-02-24]: keep.isolates working 68 | # diffnet.attrs(kfamilyDiffNet, "vertex", "static") <- as.matrix(subset(kfamily, id %in% used.vertex)) 69 | # [2016-03-05]: Deprecated 70 | # diffnet.attrs(kfamilyDiffNet, "vertex", "static") <- subset(kfamily, select=c(-id,-toa)) 71 | 72 | save(kfamilyDiffNet, file="data/kfamilyDiffNet.rdata", 73 | compress = "xz") 74 | -------------------------------------------------------------------------------- /data-raw/listing_duplicated_columns.r: -------------------------------------------------------------------------------- 1 | # This script checks which variables can be repeated... 2 | listing_duplicated_columns <- function(x) { 3 | 4 | # Fixing factors to strings 5 | x <- data.frame(lapply(x, function(y) 6 | if (is.factor(y)) as.character(y) else y 7 | ), stringsAsFactors = FALSE) 8 | 9 | k <- ncol(x) 10 | vnames <- colnames(x) 11 | ans <- NULL 12 | for (i in 1L:ncol(x)) 13 | for (j in i:ncol(x)) { 14 | if (i == j) next 15 | if (all(x[,i] == x[,j], na.rm = TRUE)) 16 | ans <- c(ans, list(c(vnames[c(i,j)]))) 17 | } 18 | 19 | do.call(rbind, ans) 20 | } 21 | 22 | -------------------------------------------------------------------------------- /data-raw/medInnovations.R: -------------------------------------------------------------------------------- 1 | rm(list=ls()) 2 | library(foreign) 3 | 4 | source("data-raw/listing_duplicated_columns.r") 5 | 6 | # Preparing the data ----------------------------------------------------------- 7 | medInnovations <- read.dta("data-raw/mi_v2.dta") 8 | # > listing_duplicated_columns(medInnovations) 9 | # [,1] [,2] 10 | # [1,] "city" "commun" 11 | # [2,] "detail" "detail2" 12 | # [3,] "ado" "adopt" 13 | # [4,] "ado" "toa" 14 | # [5,] "adopt" "toa" 15 | # medInnovations <- medInnovations[ 16 | # , 17 | # setdiff( 18 | # colnames(medInnovations), 19 | # c("commun", "detail2", "adopt", "ado")) 20 | # ] 21 | 22 | save(medInnovations, file="data/medInnovations.rdata", 23 | compress = "xz") 24 | -------------------------------------------------------------------------------- /data/brfarmers.rdata: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/USCCANA/netdiffuseR/1efc0be4539d23ab800187c73551624834038e00/data/brfarmers.rdata -------------------------------------------------------------------------------- /data/brfarmersDiffNet.rdata: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/USCCANA/netdiffuseR/1efc0be4539d23ab800187c73551624834038e00/data/brfarmersDiffNet.rdata -------------------------------------------------------------------------------- /data/fakeDynEdgelist.rdata: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/USCCANA/netdiffuseR/1efc0be4539d23ab800187c73551624834038e00/data/fakeDynEdgelist.rdata -------------------------------------------------------------------------------- /data/fakeEdgelist.rdata: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/USCCANA/netdiffuseR/1efc0be4539d23ab800187c73551624834038e00/data/fakeEdgelist.rdata -------------------------------------------------------------------------------- /data/fakesurvey.rdata: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/USCCANA/netdiffuseR/1efc0be4539d23ab800187c73551624834038e00/data/fakesurvey.rdata -------------------------------------------------------------------------------- /data/fakesurveyDyn.rdata: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/USCCANA/netdiffuseR/1efc0be4539d23ab800187c73551624834038e00/data/fakesurveyDyn.rdata -------------------------------------------------------------------------------- /data/kfamily.rdata: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/USCCANA/netdiffuseR/1efc0be4539d23ab800187c73551624834038e00/data/kfamily.rdata -------------------------------------------------------------------------------- /data/kfamilyDiffNet.rdata: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/USCCANA/netdiffuseR/1efc0be4539d23ab800187c73551624834038e00/data/kfamilyDiffNet.rdata -------------------------------------------------------------------------------- /data/medInnovations.rdata: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/USCCANA/netdiffuseR/1efc0be4539d23ab800187c73551624834038e00/data/medInnovations.rdata -------------------------------------------------------------------------------- /data/medInnovationsDiffNet.rdata: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/USCCANA/netdiffuseR/1efc0be4539d23ab800187c73551624834038e00/data/medInnovationsDiffNet.rdata -------------------------------------------------------------------------------- /docker/DESCRIPTION: -------------------------------------------------------------------------------- 1 | Package: netdiffuseR 2 | Title: Analysis of Diffusion and Contagion Processes on Networks 3 | Version: 1.22.3 4 | Authors@R: c( 5 | person("George", "Vega Yon", email="g.vegayon@gmail.com", role=c("aut", "cre"), 6 | comment=c(ORCID = "0000-0002-3171-0844", what="Rewrite functions with Rcpp, plus new features") 7 | ), 8 | person("Thomas", "Valente", email="tvalente@usc.edu", role=c("aut", "cph"), 9 | comment=c(ORCID="0000-0002-8824-5816", what="R original code")), 10 | person("Stephanie", "Dyal", email="stepharp@usc.edu", role=c("ctb"), comment="Package's first version"), 11 | person("Timothy", "Hayes", email="timothybhayes@gmail.com", role=c("ctb"), comment="Package's first version") 12 | ) 13 | Description: Empirical statistical analysis, visualization and simulation of 14 | diffusion and contagion processes on networks. The package implements algorithms 15 | for calculating network diffusion statistics such as transmission rate, hazard 16 | rates, exposure models, network threshold levels, infectiousness (contagion), 17 | and susceptibility. The package is inspired by work published in Valente, 18 | et al., (2015) ; Valente (1995) , Myers (2000) , Iyengar and others (2011) 20 | , Burt (1987) ; among others. 21 | Depends: 22 | R (>= 3.1.1) 23 | License: MIT + file LICENSE 24 | LazyData: true 25 | Date: 2021-05-21 26 | Imports: 27 | Rcpp (>= 0.12.1), 28 | sna, 29 | network, 30 | networkDynamic, 31 | Matrix, 32 | MASS, 33 | MatchIt, 34 | SparseM, 35 | methods, 36 | grDevices, 37 | graphics, 38 | stats, 39 | utils, 40 | boot, 41 | igraph, 42 | viridisLite 43 | Suggests: 44 | covr, 45 | testthat, 46 | knitr, 47 | rmarkdown, 48 | ape, 49 | RSiena, 50 | survival 51 | VignetteBuilder: knitr 52 | LinkingTo: Rcpp, RcppArmadillo 53 | RoxygenNote: 7.1.1 54 | Encoding: UTF-8 55 | URL: https://github.com/USCCANA/netdiffuseR, 56 | https://USCCANA.github.io/netdiffuseR/ 57 | BugReports: https://github.com/USCCANA/netdiffuseR/issues 58 | Classification/MSC: 90C35, 90B18, 91D30 59 | Collate: 60 | 'RcppExports.R' 61 | 'imports.r' 62 | 'graph_data.r' 63 | 'adjmat.r' 64 | 'bass.r' 65 | 'bootnet.r' 66 | 'data.r' 67 | 'diffnet-c.R' 68 | 'diffnet-class.r' 69 | 'diffnet-indexing.r' 70 | 'diffnet-methods.r' 71 | 'egonets.R' 72 | 'formula.r' 73 | 'igraph.r' 74 | 'infect_suscept.r' 75 | 'mentor.r' 76 | 'misc.r' 77 | 'moran.r' 78 | 'netmatch.r' 79 | 'network.r' 80 | 'options.R' 81 | 'package-doc.r' 82 | 'plot_diffnet2.r' 83 | 'rewire.r' 84 | 'random_graph.R' 85 | 'rdiffnet.r' 86 | 'read_write_foreign.r' 87 | 'select_egoalter.R' 88 | 'spatial.R' 89 | 'stats.R' 90 | 'struct_equiv.R' 91 | 'struct_test.R' 92 | 'survey_to_diffnet.R' 93 | -------------------------------------------------------------------------------- /docker/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM rocker/drd 2 | 3 | RUN apt-get update && apt-get install \ 4 | -y --no-install-recommends \ 5 | libssl-dev 6 | COPY pkgs.R . 7 | COPY DESCRIPTION . 8 | RUN Rscript pkgs.R && \ 9 | Rscript -e 'utils::install.packages(readLines("pkgs.txt"))' 10 | 11 | CMD ["bash"] 12 | 13 | -------------------------------------------------------------------------------- /docker/Dockerfile.r-ver: -------------------------------------------------------------------------------- 1 | ARG Rversion 2 | 3 | FROM rocker/r-ver:${Rversion} 4 | 5 | RUN Rscript -e 'utils::install.packages(c("rmarkdown", "knitr", "coda", "mvtnorm", "tinytest", "mcmc", "covr"))' 6 | 7 | CMD ["bash"] 8 | 9 | -------------------------------------------------------------------------------- /docker/Makefile: -------------------------------------------------------------------------------- 1 | build: 2 | cp ../DESCRIPTION . && \ 3 | docker build -t uscbiostats/netdiffuser:latest -f Dockerfile . 4 | push: build 5 | docker push uscbiostats/netdiffuser:latest 6 | -------------------------------------------------------------------------------- /docker/README.md: -------------------------------------------------------------------------------- 1 | To run the check in the main package folder: 2 | 3 | ```bash 4 | docker run -v$(pwd):/fmcmc-pkg/ -w/fmcmc-pkg --rm -i uscbiostats/fmcmc-dev:latest make check 5 | ``` 6 | 7 | To update the version just type 8 | 9 | ```bash 10 | make push 11 | ``` 12 | -------------------------------------------------------------------------------- /docker/pkgs.R: -------------------------------------------------------------------------------- 1 | x <- readLines("DESCRIPTION") 2 | ids <- which(grepl("^(Imports:|Suggests:|VignetteBuilder:)", x)) 3 | x <- x[setdiff((ids[1] + 1):(ids[3] - 1), ids[2])] 4 | 5 | x <- gsub("^\\s+|(?<=[[:alnum:]])(\\s|,).*", "", x, perl = TRUE) 6 | x <- setdiff(x, c("MASS", "methods", "grDevices", "graphics", "stats", "utils")) 7 | 8 | xfin <- x 9 | for (i in x) { 10 | if (require(i)) 11 | xfin <- setdiff(xfin, i) 12 | } 13 | 14 | writeLines(xfin, con = "pkgs.txt") 15 | -------------------------------------------------------------------------------- /inst/CITATION: -------------------------------------------------------------------------------- 1 | year <- sub("-.*", "", meta$Date) 2 | note <- sprintf("R package version %s", meta$Version) 3 | 4 | bibentry( 5 | header = "To cite netdiffuseR in publications use the following paper:", 6 | entry = "Article", 7 | title = "Diffusion/Contagion Processes on Social Networks", 8 | author = c( 9 | person("Thomas", "Valente"), 10 | person("George", "Vega Yon") 11 | ), 12 | journal = "Health Education & Behavior", 13 | year = "2020", 14 | month = "feb", 15 | volume = 42, 16 | issue = 2, 17 | doi = "10.1177/1090198120901497", 18 | url = "https://doi.org/10.1177/1090198120901497", 19 | issn = "1367-4803", 20 | pages = "235-248", 21 | note = "{PMID: 32090655}", 22 | bibtype = "article", 23 | textVersion = "Valente TW, Vega Yon GG. Diffusion/Contagion Processes on Social Networks. Health Education & Behavior. 2020;47(2):235-248. doi:10.1177/1090198120901497" 24 | ) 25 | 26 | 27 | bibentry(bibtype = "Manual", 28 | title = "{{netdiffuseR: Analysis of Diffusion and Contagion Processes on Networks}}", 29 | author = c( 30 | person("George", "Vega Yon", comment = c(ORCID = "0000-0002-3171-0844")), 31 | person("Thomas", "Valente", comment=c(ORCID="0000-0002-8824-5816")) 32 | ), 33 | year = year, 34 | note = note, 35 | url = "https://github.com/USCCANA/netdiffuseR", 36 | doi = "10.5281/zenodo.1039317", 37 | header = "And the actual R package:") 38 | 39 | -------------------------------------------------------------------------------- /inst/extdata/SAMPSONL.NET: -------------------------------------------------------------------------------- 1 | *Vertices 18 2 | 1 "ROMUL_10" 3 | 2 "BONAVEN_5" 4 | 3 "AMBROSE_9" 5 | 4 "BERTH_6" 6 | 5 "PETER_4" 7 | 6 "LOUIS_11" 8 | 7 "VICTOR_8" 9 | 8 "WINF_12" 10 | 9 "JOHN_1" 11 | 10 "GREG_2" 12 | 11 "HUGH_14" 13 | 12 "BONI_15" 14 | 13 "MARK_7" 15 | 14 "ALBERT_16" 16 | 15 "AMAND_13" 17 | 16 "BASIL_3" 18 | 17 "ELIAS_17" 19 | 18 "SIMP_18" 20 | *Arcslist :1 "SAMPLK1" 21 | 1 3 5 14 22 | 2 1 7 14 23 | 3 1 2 17 24 | 4 5 6 10 25 | 5 4 11 13 26 | 6 1 4 9 27 | 7 2 8 16 28 | 8 1 2 9 29 | 9 5 8 16 30 | 10 4 8 14 31 | 11 5 8 14 32 | 12 1 2 14 33 | 13 5 7 18 34 | 14 1 11 12 15 35 | 15 1 2 14 36 | 16 1 2 7 37 | 17 3 13 18 38 | 18 1 2 7 39 | *Arcslist :2 "SAMPLK2" 40 | 1 2 5 8 41 | 2 1 7 12 15 42 | 3 1 17 18 43 | 4 5 6 11 44 | 5 1 4 11 45 | 6 1 4 9 46 | 7 1 2 16 47 | 8 4 6 10 48 | 9 5 8 12 49 | 10 4 5 13 50 | 11 4 5 16 51 | 12 1 2 14 52 | 13 5 7 18 53 | 14 1 2 12 15 54 | 15 1 2 5 14 55 | 16 2 7 12 56 | 17 2 3 18 57 | 18 2 13 17 58 | *Arcslist :3 "SAMPLK3" 59 | 1 3 12 14 60 | 2 1 7 12 61 | 3 1 13 17 18 62 | 4 5 6 11 63 | 5 4 9 11 64 | 6 4 5 9 65 | 7 2 12 16 66 | 8 4 6 9 67 | 9 5 8 12 68 | 10 4 5 9 13 69 | 11 5 8 14 70 | 12 1 2 7 71 | 13 5 7 18 72 | 14 1 12 15 73 | 15 2 7 12 74 | 16 2 7 15 75 | 17 2 3 18 76 | 18 2 3 17 77 | *Arcslist :4 "SAMPDLK" 78 | 3 16 17 18 79 | 4 10 13 16 17 80 | 5 9 10 11 81 | 6 9 10 16 82 | 7 10 11 16 83 | 9 1 10 13 84 | 10 5 7 15 85 | 11 5 7 17 86 | 12 5 15 16 87 | 13 4 5 7 88 | 14 5 16 17 89 | 15 4 8 10 90 | 16 4 5 10 14 91 | 17 4 5 7 92 | 18 1 5 7 93 | *Arcslist :5 "SAMPES" 94 | 2 3 5 6 95 | 3 5 7 9 96 | 4 5 6 97 | 5 1 4 6 98 | 6 2 3 99 | 7 2 4 5 100 | 8 9 10 11 101 | 9 2 7 8 102 | 10 2 7 9 103 | 11 8 9 10 12 104 | 12 9 10 11 105 | 13 8 10 12 14 106 | 14 8 10 12 13 107 | 15 2 6 13 108 | 16 9 15 17 18 109 | 17 10 15 16 18 110 | 18 10 16 17 111 | *Arcslist :6 "SAMPDES" 112 | 2 16 17 18 113 | 3 15 17 18 114 | 4 7 13 16 17 115 | 5 9 10 11 116 | 6 9 10 14 16 117 | 7 11 17 18 118 | 9 10 13 16 119 | 10 5 15 16 120 | 11 5 6 15 17 18 121 | 12 5 6 16 17 18 122 | 13 4 5 7 16 17 123 | 14 5 16 17 18 124 | 15 4 10 16 125 | 16 4 5 10 126 | 17 4 5 7 127 | 18 1 4 5 7 128 | *Arcslist :7 "SAMPIN" 129 | 2 5 6 10 130 | 3 5 9 10 131 | 4 3 5 10 132 | 5 1 4 6 133 | 6 2 3 5 134 | 7 3 5 6 9 135 | 8 9 10 13 136 | 9 8 10 13 137 | 10 8 9 13 138 | 11 8 9 10 12 139 | 12 10 11 13 140 | 13 8 10 14 141 | 14 10 12 13 142 | 15 2 6 13 143 | 16 9 15 17 144 | 17 10 16 18 145 | 18 10 16 17 146 | *Arcslist :8 "SAMPNIN" 147 | 2 16 17 18 148 | 3 8 17 18 149 | 4 13 17 18 150 | 5 9 10 11 151 | 6 13 17 18 152 | 7 8 14 15 153 | 9 1 14 18 154 | 10 5 15 155 | 11 5 15 17 18 156 | 12 5 15 16 157 | 13 4 5 7 16 17 158 | 14 5 6 16 159 | 15 4 8 10 160 | 16 4 5 10 161 | 17 4 5 7 162 | 18 4 5 6 163 | *Arcslist :9 "SAMPPR" 164 | 4 3 5 6 165 | 5 1 4 6 166 | 6 5 7 14 167 | 7 4 5 6 168 | 9 8 11 17 169 | 10 8 9 13 170 | 11 9 10 12 14 171 | 12 9 10 11 172 | 13 10 12 14 173 | 14 10 12 13 174 | 15 2 6 175 | 16 9 15 17 176 | 18 9 10 17 177 | *Arcslist :10 "SAMNPR" 178 | 4 13 15 17 18 179 | 5 10 11 13 180 | 6 11 17 18 181 | 7 16 17 18 182 | 8 11 17 18 183 | 9 6 16 18 184 | 10 16 185 | 11 5 6 16 186 | 12 5 15 16 18 187 | 13 4 5 16 188 | 14 5 15 16 17 18 189 | 15 10 17 18 190 | 16 5 10 11 191 | -------------------------------------------------------------------------------- /inst/extdata/SAMPSON_W_DEGREE.vec: -------------------------------------------------------------------------------- 1 | *Vertices 18 2 | 81 3 | 102 4 | 74 5 | 140 6 | 198 7 | 102 8 | 109 9 | 73 10 | 120 11 | 154 12 | 101 13 | 92 14 | 117 15 | 99 16 | 98 17 | 130 18 | 109 19 | 119 20 | -------------------------------------------------------------------------------- /man-roxygen/graph_template.R: -------------------------------------------------------------------------------- 1 | #' @param graph <%= ifelse(exists("dynamic") && dynamic, "A dynamic graph", "Any class of accepted graph format") %> (see \code{\link{netdiffuseR-graphs}}). 2 | #' <%=ifelse(exists("self") && self, "@param self Logical scalar. When \\code{TRUE} autolinks (loops, self edges) are allowed (see details).", "") %> 3 | #' <%=ifelse(exists("multiple") && multiple, "@param multiple Logical scalar. When \\code{TRUE} allows multiple edges.", "") %> 4 | #' <%=ifelse(exists("valued") && valued, "@param valued Logical scalar. When \\code{TRUE} weights will be considered. Otherwise non-zero values will be replaced by ones.", "") %> 5 | #' <%=ifelse(exists("undirected") && undirected, "@param undirected Logical scalar. When \\code{TRUE} only the lower triangle of the adjacency matrix will considered (faster).", "") %> 6 | #' <%=ifelse(exists("toa") && toa, "@param toa Integer vector of length \\eqn{n} with the times of adoption.", "") %> 7 | #' <%=ifelse(exists("slice") && slice, "@param slice Integer scalar. Number of slice to use as baseline for drawing the graph.", "") %> 8 | -------------------------------------------------------------------------------- /man-roxygen/plotting_template.R: -------------------------------------------------------------------------------- 1 | #' @param vertex.size Either a numeric scalar or vector of size \eqn{n}, or any 2 | #' of the following values: "indegree", "degree", or "outdegree" (see details). 3 | #' @param minmax.relative.size Passed to \code{\link{rescale_vertex_igraph}}. 4 | #' @details 5 | #' Plotting is done via the function \code{\link[igraph:plot.igraph]{plot.igraph}}. 6 | #' 7 | #' When \code{vertex.size} is either of \code{"degree"}, \code{"indegree"}, or 8 | #' \code{"outdegree"}, \code{vertex.size} will be replace with \code{dgr(.,cmode = )} 9 | #' so that the vertex size reflects the desired degree. 10 | #' 11 | #' The argument \code{minmax.relative.size} is passed to \code{\link{rescale_vertex_igraph}} 12 | #' which adjusts \code{vertex.size} so that the largest and smallest vertices 13 | #' have a relative size of \code{minmax.relative.size[2]} and 14 | #' \code{minmax.relative.size[1]} respectively with respect to the x-axis. 15 | -------------------------------------------------------------------------------- /man/approx_geodesic.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/adjmat.r 3 | \name{approx_geodesic} 4 | \alias{approx_geodesic} 5 | \alias{Geodesic} 6 | \alias{Shortest-Path} 7 | \alias{approx_geodist} 8 | \title{Approximate Geodesic Distances} 9 | \usage{ 10 | approx_geodesic(graph, n = 6L, warn = FALSE) 11 | 12 | approx_geodist(graph, n = 6L, warn = FALSE) 13 | } 14 | \arguments{ 15 | \item{graph}{Any class of accepted graph format (see \code{\link{netdiffuseR-graphs}}).} 16 | 17 | \item{n}{Integer scalar. Degree of approximation. Bigger values increase 18 | precision (see details).} 19 | 20 | \item{warn}{Logical scalar. When \code{TRUE}, it warns if the algorithm 21 | performs less steps than required.} 22 | } 23 | \value{ 24 | A sparse matrix of class \code{\link[Matrix:dgCMatrix-class]{dgCMatrix}} of size 25 | \code{nnodes(graph)^2} with geodesic distances up to \code{n}. 26 | } 27 | \description{ 28 | Computes approximate geodesic distance matrix using graph powers and keeping 29 | the amount of memory used low. 30 | } 31 | \details{ 32 | While both \pkg{igraph} and \pkg{sna} offer very good and computationally 33 | efficient routines for computing geodesic distances, both functions return 34 | dense matrices, i.e. not sparse, which can be troublesome. Furthermore, 35 | from the perspective of social network analysis, path lengths of more than 6 steps, 36 | for example, may not be meaningful, or at least, relevant for the researcher. 37 | In such cases, \code{approx_geodesic} serves as a solution to this problem, 38 | computing geodesics up to the number of steps, \code{n}, desired, hence, 39 | if \code{n = 6}, once the algorithm finds all paths of 6 or less steps it 40 | will stop, returning a sparse matrix with zeros for those pairs of 41 | vertices for which it was not able to find a path with less than \code{n} 42 | steps. 43 | 44 | Depending on the graph size and density, \code{approx_geodesic}'s performance 45 | can be compared to that of \code{\link[sna:geodist]{sna::geodist}}. Although, 46 | as \code{n} increases, \code{geodist} becomes a better alternative. 47 | 48 | The algorithm was implemented using power graphs. At each itereation i the 49 | power graph of order \code{i} is computed, and its values are compared 50 | to the current values of the geodesic matrix (which is initialized in zero). 51 | 52 | \enumerate{ 53 | \item Initialize the output \code{ans(n, n)} 54 | \item For \code{i=1} to \code{i < n} do 55 | \enumerate{ 56 | \item Iterate through the edges of \code{G^i}, if \code{ans} has a zero 57 | value in the corresponding row+column, replace it with \code{i} 58 | \item next 59 | } 60 | \item Replace all diagonal elements with a zero and return. 61 | } 62 | 63 | This implementation can be more memory efficient that the aforementioned ones, 64 | but at the same time it can be significant slower. 65 | 66 | \code{approx_geodist} is just an allias for \code{approx_geodesic}. 67 | } 68 | \examples{ 69 | # A very simple example ----------------------------------------------------- 70 | g <- ring_lattice(10, 3) 71 | approx_geodesic(g, 6) 72 | sna::geodist(as.matrix(g))[[2]] 73 | igraph::distances( 74 | igraph::graph_from_adjacency_matrix(g, mode = "directed"), 75 | mode = "out" 76 | ) 77 | 78 | } 79 | -------------------------------------------------------------------------------- /man/as.array.diffnet.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/diffnet-methods.r 3 | \name{as.array.diffnet} 4 | \alias{as.array.diffnet} 5 | \title{Coerce a diffnet graph into an array} 6 | \usage{ 7 | \method{as.array}{diffnet}(x, ...) 8 | } 9 | \arguments{ 10 | \item{x}{A diffnet object.} 11 | 12 | \item{...}{Ignored.} 13 | } 14 | \value{ 15 | A three-dimensional array of \eqn{T} matrices of size \eqn{n\times n}{n * n}. 16 | } 17 | \description{ 18 | Coerce a diffnet graph into an array 19 | } 20 | \details{ 21 | The function takes the list of sparse matrices stored in \code{x} and creates 22 | an array with them. Attributes and other elements from the diffnet object are 23 | dropped. 24 | 25 | \code{dimnames} are obtained from the metadata of the diffnet object. 26 | } 27 | \examples{ 28 | # Creating a random diffnet object 29 | set.seed(84117) 30 | mydiffnet <- rdiffnet(30, 5) 31 | 32 | # Coercing it into an array 33 | as.array(mydiffnet) 34 | } 35 | \seealso{ 36 | \code{\link{diffnet}}. 37 | 38 | Other diffnet methods: 39 | \code{\link{\%*\%}()}, 40 | \code{\link{c.diffnet}()}, 41 | \code{\link{diffnet-arithmetic}}, 42 | \code{\link{diffnet-class}}, 43 | \code{\link{diffnet_index}}, 44 | \code{\link{plot.diffnet}()}, 45 | \code{\link{summary.diffnet}()} 46 | } 47 | \concept{diffnet methods} 48 | -------------------------------------------------------------------------------- /man/as_dgCMatrix.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/misc.r 3 | \name{as_dgCMatrix} 4 | \alias{as_dgCMatrix} 5 | \alias{as.dgCMatrix} 6 | \alias{as_spmat} 7 | \alias{as_dgCMatrix.default} 8 | \alias{as_dgCMatrix.diffnet} 9 | \alias{as_dgCMatrix.array} 10 | \alias{as_dgCMatrix.igraph} 11 | \alias{as_dgCMatrix.network} 12 | \alias{as_dgCMatrix.list} 13 | \title{Coerce a matrix-like objects to \code{dgCMatrix} (sparse matrix)} 14 | \usage{ 15 | as_dgCMatrix(x, make.dimnames = TRUE, ...) 16 | 17 | as.dgCMatrix(x, make.dimnames = TRUE, ...) 18 | 19 | as_spmat(x, make.dimnames = TRUE, ...) 20 | 21 | \method{as_dgCMatrix}{default}(x, make.dimnames = TRUE, ...) 22 | 23 | \method{as_dgCMatrix}{diffnet}(x, make.dimnames = TRUE, ...) 24 | 25 | \method{as_dgCMatrix}{array}(x, make.dimnames = TRUE, ...) 26 | 27 | \method{as_dgCMatrix}{igraph}(x, make.dimnames = TRUE, ...) 28 | 29 | \method{as_dgCMatrix}{network}(x, make.dimnames = TRUE, ...) 30 | 31 | \method{as_dgCMatrix}{list}(x, make.dimnames = TRUE, ...) 32 | } 33 | \arguments{ 34 | \item{x}{An object to be coerced into a sparse matrix.} 35 | 36 | \item{make.dimnames}{Logical scalar. When \code{TRUE}, it makes sure that the 37 | returned object has dimnames.} 38 | 39 | \item{...}{Further arguments passed to the method.} 40 | } 41 | \value{ 42 | Either a list with \code{dgCMatrix} objects or a \code{dgCMatrix} object. 43 | } 44 | \description{ 45 | This helper function allows easy coercion to sparse matrix objects 46 | from the \pkg{Matrix} package, \code{\link[Matrix:dgCMatrix-class]{dgCMatrix}}. 47 | } 48 | \details{ 49 | In the case of the \code{igraph} and \code{network} methods, \code{...} is passed to 50 | \code{\link[igraph:as_adj]{as_adj}} and \code{\link[network:as.matrix.network]{as.matrix.network}} 51 | respectively. 52 | } 53 | \examples{ 54 | 55 | set.seed(1231) 56 | x <- rgraph_er(10) 57 | 58 | # From matrix object 59 | as_dgCMatrix(as.matrix(x)) 60 | 61 | # From a network object 62 | as_dgCMatrix(network::as.network(as.matrix(x))) 63 | 64 | # From igraph object 65 | as_dgCMatrix(igraph::graph_from_adjacency_matrix(x)) 66 | 67 | # From array 68 | myarray <- array(dim=c(10,10,2)) 69 | myarray[,,1] <- as.matrix(x) 70 | myarray[,,2] <- as.matrix(x) 71 | 72 | myarray 73 | as_dgCMatrix(myarray) 74 | 75 | # From a diffnet object 76 | ans <- as_dgCMatrix(medInnovationsDiffNet) 77 | str(ans) 78 | 79 | 80 | } 81 | -------------------------------------------------------------------------------- /man/brfarmersDiffNet.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/data.r 3 | \name{brfarmersDiffNet} 4 | \alias{brfarmersDiffNet} 5 | \title{\code{diffnet} version of the Brazilian Farmers data} 6 | \format{ 7 | A \code{\link{diffnet}} class object. 8 | } 9 | \description{ 10 | A directed dynamic graph with 692 vertices and 21 time periods. The attributes 11 | in the graph are static and described in \code{\link{brfarmers}}. 12 | } 13 | \seealso{ 14 | Other diffusion datasets: 15 | \code{\link{brfarmers}}, 16 | \code{\link{diffusion-data}}, 17 | \code{\link{fakeDynEdgelist}}, 18 | \code{\link{fakeEdgelist}}, 19 | \code{\link{fakesurvey}}, 20 | \code{\link{fakesurveyDyn}}, 21 | \code{\link{kfamily}}, 22 | \code{\link{kfamilyDiffNet}}, 23 | \code{\link{medInnovations}}, 24 | \code{\link{medInnovationsDiffNet}} 25 | } 26 | \concept{diffusion datasets} 27 | -------------------------------------------------------------------------------- /man/c.diffnet.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/diffnet-c.R 3 | \name{c.diffnet} 4 | \alias{c.diffnet} 5 | \title{Combine diffnet objects} 6 | \usage{ 7 | \method{c}{diffnet}(..., recursive = FALSE) 8 | } 9 | \arguments{ 10 | \item{...}{diffnet objects to be concatenated.} 11 | 12 | \item{recursive}{Ignored.} 13 | } 14 | \value{ 15 | A new \code{diffnet} object with as many vertices as the sum of each 16 | concatenated diffnet objects' number of vertices. 17 | } 18 | \description{ 19 | Combining \code{\link{diffnet}} objects that share time periods and attributes names, but 20 | vertices ids (only valid for diffnet objects that have an empty intersection 21 | between vertices ids). 22 | } 23 | \details{ 24 | The diffnet objects in \code{...} must fulfill the following conditions: 25 | \enumerate{ 26 | \item Have the same time range, 27 | \item have the same vertex attributes, and 28 | \item have an empty intersection of vertices ids, 29 | } 30 | 31 | The meta data regarding \code{undirected}, \code{value}, and \code{multiple} 32 | are set to \code{TRUE} if any of the concatenating diffnet objects has that 33 | meta equal to \code{TRUE}. 34 | 35 | The resulting diffnet object's columns in the vertex attributes ordering (both 36 | dynamic and static) will coincide with the first diffnet's ordering. 37 | } 38 | \examples{ 39 | # Calculate structural equivalence exposure by city ------------------------- 40 | data(medInnovationsDiffNet) 41 | 42 | # Subsetting diffnets 43 | city1 <- medInnovationsDiffNet[medInnovationsDiffNet[["city"]] == 1] 44 | city2 <- medInnovationsDiffNet[medInnovationsDiffNet[["city"]] == 2] 45 | city3 <- medInnovationsDiffNet[medInnovationsDiffNet[["city"]] == 3] 46 | city4 <- medInnovationsDiffNet[medInnovationsDiffNet[["city"]] == 4] 47 | 48 | # Computing exposure in each one 49 | city1[["expo_se"]] <- exposure(city1, alt.graph="se", valued=TRUE) 50 | city2[["expo_se"]] <- exposure(city2, alt.graph="se", valued=TRUE) 51 | city3[["expo_se"]] <- exposure(city3, alt.graph="se", valued=TRUE) 52 | city4[["expo_se"]] <- exposure(city4, alt.graph="se", valued=TRUE) 53 | 54 | # Concatenating all 55 | diffnet <- c(city1, city2, city3, city4) 56 | diffnet 57 | 58 | 59 | } 60 | \seealso{ 61 | Other diffnet methods: 62 | \code{\link{\%*\%}()}, 63 | \code{\link{as.array.diffnet}()}, 64 | \code{\link{diffnet-arithmetic}}, 65 | \code{\link{diffnet-class}}, 66 | \code{\link{diffnet_index}}, 67 | \code{\link{plot.diffnet}()}, 68 | \code{\link{summary.diffnet}()} 69 | } 70 | \concept{diffnet methods} 71 | -------------------------------------------------------------------------------- /man/classify_graph.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/graph_data.r 3 | \name{classify_graph} 4 | \alias{classify_graph} 5 | \title{Analyze an R object to identify the class of graph (if any)} 6 | \usage{ 7 | classify_graph(graph) 8 | } 9 | \arguments{ 10 | \item{graph}{Any class of accepted graph format (see \code{\link{netdiffuseR-graphs}}).} 11 | } 12 | \value{ 13 | Whe the object fits any of the accepted graph formats, a list of attributes including 14 | \item{type}{Character scalar. Whether is a static or a dynamic graph} 15 | \item{class}{Character scalar. The class of the original object} 16 | \item{ids}{Character vector. Labels of the vertices} 17 | \item{pers}{Integer vector. Labels of the time periods} 18 | \item{nper}{Integer scalar. Number of time periods} 19 | \item{n}{Integer scalar. Number of vertices in the graph} 20 | Otherwise returns with error. 21 | } 22 | \description{ 23 | Analyze an R object to identify the class of graph (if any) 24 | } 25 | \details{ 26 | This function analyzes an R object and tries to classify it among the 27 | accepted classes in \pkg{netdiffuseR}. If the object fails to fall in one of 28 | the types of graphs the function returns with an error indicating what (and 29 | when possible, where) the problem lies. 30 | 31 | The function was designed to be used with \code{\link{as_diffnet}}. 32 | } 33 | \seealso{ 34 | \code{\link{as_diffnet}}, \code{\link{netdiffuseR-graphs}} 35 | } 36 | \author{ 37 | George G. Vega Yon 38 | } 39 | -------------------------------------------------------------------------------- /man/cumulative_adopt_count.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/stats.R 3 | \name{cumulative_adopt_count} 4 | \alias{cumulative_adopt_count} 5 | \title{Cummulative count of adopters} 6 | \usage{ 7 | cumulative_adopt_count(obj) 8 | } 9 | \arguments{ 10 | \item{obj}{A \eqn{n\times T}{n * T} matrix (Cumulative adoption matrix obtained from 11 | \code{\link{toa_mat}}) or a \code{\link{diffnet}} object.} 12 | } 13 | \value{ 14 | A \eqn{3\times T}{3 * T} matrix, where its rows contain the number of adoptes, the proportion of 15 | adopters and the rate of adoption respectively, for earch period of time. 16 | } 17 | \description{ 18 | For each time period, calculates the number of adopters, the proportion of adopters, 19 | and the adoption rate. 20 | } 21 | \details{ 22 | The rate of adoption--returned in the 3rd row out the resulting 23 | matrix--is calculated as 24 | 25 | \deqn{\frac{q_t - q_{t-1}}{q_{t-1}}}{[q(t) - q(t-1)]/q(t-1)} 26 | 27 | where \eqn{q_i}{q(i)} is the number of adopters in time \eqn{t}. Note that 28 | it is only calculated fot \eqn{t>1}. 29 | } 30 | \seealso{ 31 | Other statistics: 32 | \code{\link{bass}}, 33 | \code{\link{classify_adopters}()}, 34 | \code{\link{dgr}()}, 35 | \code{\link{ego_variance}()}, 36 | \code{\link{exposure}()}, 37 | \code{\link{hazard_rate}()}, 38 | \code{\link{infection}()}, 39 | \code{\link{moran}()}, 40 | \code{\link{struct_equiv}()}, 41 | \code{\link{threshold}()}, 42 | \code{\link{vertex_covariate_dist}()} 43 | } 44 | \author{ 45 | George G. Vega Yon & Thomas W. Valente 46 | } 47 | \concept{statistics} 48 | \keyword{univar} 49 | -------------------------------------------------------------------------------- /man/diag_expand.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/spatial.R 3 | \name{diag_expand} 4 | \alias{diag_expand} 5 | \alias{diag_expand.list} 6 | \alias{diag_expand.diffnet} 7 | \alias{diag_expand.matrix} 8 | \alias{diag_expand.array} 9 | \alias{diag_expand.dgCMatrix} 10 | \title{Creates a square matrix suitable for spatial statistics models.} 11 | \usage{ 12 | diag_expand(...) 13 | 14 | \method{diag_expand}{list}(graph, self = is_self(graph), valued = is_valued(graph), ...) 15 | 16 | \method{diag_expand}{diffnet}(graph, self = is_self(graph), valued = is_valued(graph), ...) 17 | 18 | \method{diag_expand}{matrix}(graph, nper, self = is_self(graph), valued = is_valued(graph), ...) 19 | 20 | \method{diag_expand}{array}(graph, self = is_self(graph), valued = is_valued(graph), ...) 21 | 22 | \method{diag_expand}{dgCMatrix}(graph, nper, self = is_self(graph), valued = is_valued(graph), ...) 23 | } 24 | \arguments{ 25 | \item{...}{Further arguments to be passed to the method.} 26 | 27 | \item{graph}{Any class of accepted graph format (see \code{\link{netdiffuseR-graphs}}).} 28 | 29 | \item{self}{Logical scalar. When \code{TRUE} autolinks (loops, self edges) are allowed (see details).} 30 | 31 | \item{valued}{Logical scalar. When \code{TRUE} weights will be considered. Otherwise non-zero values will be replaced by ones.} 32 | 33 | \item{nper}{Integer scalar. Number of time periods of the graph.} 34 | } 35 | \value{ 36 | A square matrix of class \code{\link[Matrix:dgCMatrix-class]{dgCMatrix}} of 37 | size \code{(nnode(g)*nper)^2} 38 | } 39 | \description{ 40 | Creates a square matrix suitable for spatial statistics models. 41 | } 42 | \examples{ 43 | # Simple example ------------------------------------------------------------ 44 | set.seed(23) 45 | g <- rgraph_er(n=10, p=.5, t=2,undirected=TRUE) 46 | 47 | # What we've done: A list with 2 bernoulli graphs 48 | g 49 | 50 | # Expanding to a 20*20 matrix with structural zeros on the diagonal 51 | # and on cell 'off' adjacency matrix 52 | diag_expand(g) 53 | } 54 | -------------------------------------------------------------------------------- /man/diffnet-arithmetic.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/diffnet-methods.r 3 | \name{diffnet-arithmetic} 4 | \alias{diffnet-arithmetic} 5 | \alias{^.diffnet} 6 | \alias{graph_power} 7 | \alias{/.diffnet} 8 | \alias{-.diffnet} 9 | \alias{*.diffnet} 10 | \alias{&.diffnet} 11 | \alias{|.diffnet} 12 | \title{\code{diffnet} Arithmetic and Logical Operators} 13 | \usage{ 14 | \method{^}{diffnet}(x, y) 15 | 16 | graph_power(x, y, valued = getOption("diffnet.valued", FALSE)) 17 | 18 | \method{/}{diffnet}(y, x) 19 | 20 | \method{-}{diffnet}(x, y) 21 | 22 | \method{*}{diffnet}(x, y) 23 | 24 | \method{&}{diffnet}(x, y) 25 | 26 | \method{|}{diffnet}(x, y) 27 | } 28 | \arguments{ 29 | \item{x}{A \code{diffnet} class object.} 30 | 31 | \item{y}{Integer scalar. Power of the network} 32 | 33 | \item{valued}{Logical scalar. When FALSE all non-zero entries of the adjacency 34 | matrices are set to one.} 35 | } 36 | \value{ 37 | A diffnet class object 38 | } 39 | \description{ 40 | Addition, subtraction, network power of diffnet and logical operators such as 41 | \code{&} and \code{|} as objects 42 | } 43 | \details{ 44 | Using binary operators, ease data management process with diffnet. 45 | 46 | By default the binary operator \code{^} assumes that the graph is valued, 47 | hence the power is computed using a weighted edges. Otherwise, if more control 48 | is needed, the user can use \code{graph_power} instead. 49 | } 50 | \examples{ 51 | # Computing two-steps away threshold with the Brazilian farmers data -------- 52 | data(brfarmersDiffNet) 53 | 54 | expo1 <- threshold(brfarmersDiffNet) 55 | expo2 <- threshold(brfarmersDiffNet^2) 56 | 57 | # Computing correlation 58 | cor(expo1,expo2) 59 | 60 | # Drawing a qqplot 61 | qqplot(expo1, expo2) 62 | 63 | # Working with inverse ------------------------------------------------------ 64 | brf2_step <- brfarmersDiffNet^2 65 | brf2_step <- 1/brf2_step 66 | 67 | # Removing the first 3 vertex of medInnovationsDiffnet ---------------------- 68 | data(medInnovationsDiffNet) 69 | 70 | # Using a diffnet object 71 | first3Diffnet <- medInnovationsDiffNet[1:3,,] 72 | medInnovationsDiffNet - first3Diffnet 73 | 74 | # Using indexes 75 | medInnovationsDiffNet - 1:3 76 | 77 | # Using ids 78 | medInnovationsDiffNet - as.character(1001:1003) 79 | } 80 | \seealso{ 81 | Other diffnet methods: 82 | \code{\link{\%*\%}()}, 83 | \code{\link{as.array.diffnet}()}, 84 | \code{\link{c.diffnet}()}, 85 | \code{\link{diffnet-class}}, 86 | \code{\link{diffnet_index}}, 87 | \code{\link{plot.diffnet}()}, 88 | \code{\link{summary.diffnet}()} 89 | } 90 | \concept{diffnet methods} 91 | -------------------------------------------------------------------------------- /man/diffnet_check_attr_class.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/diffnet-indexing.r 3 | \name{diffnet_check_attr_class} 4 | \alias{diffnet_check_attr_class} 5 | \title{Infer whether \code{value} is dynamic or static.} 6 | \usage{ 7 | diffnet_check_attr_class(value, meta) 8 | } 9 | \arguments{ 10 | \item{value}{Either a matrix, data frame or a list. Attribute values.} 11 | 12 | \item{meta}{A list. A diffnet object's meta data.} 13 | } 14 | \value{ 15 | The value object either as a data frame (if static) or as a list 16 | of data frames (if dynamic). If \code{value} does not follows the permitted 17 | types of \code{\link{diffnet_index}}, then returns with error. 18 | } 19 | \description{ 20 | Intended for internal use only, this function is used in \code{\link{diffnet_index}} 21 | methods. 22 | } 23 | -------------------------------------------------------------------------------- /man/diffnetmatmult.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/diffnet-methods.r 3 | \name{\%*\%} 4 | \alias{\%*\%} 5 | \alias{\%*\%.default} 6 | \alias{\%*\%.diffnet} 7 | \title{Matrix multiplication} 8 | \usage{ 9 | x \%*\% y 10 | 11 | \method{\%*\%}{default}(x, y) 12 | 13 | \method{\%*\%}{diffnet}(x, y) 14 | } 15 | \arguments{ 16 | \item{x}{Numeric or complex matrices or vectors, or \code{diffnet} objects.} 17 | 18 | \item{y}{Numeric or complex matrices or vectors, or \code{diffnet} objects.} 19 | } 20 | \value{ 21 | In the case of \code{diffnet} objects performs matrix multiplication 22 | via \code{\link{mapply}} using \code{x$graph} and \code{y$graph} as arguments, 23 | returnling a \code{diffnet}. Otherwise returns the default according to 24 | \code{\link[base:matmult]{\%*\%}}. 25 | } 26 | \description{ 27 | Matrix multiplication methods, including \code{\link{diffnet}} 28 | objects. This function creates a generic method for \code{\link[base:matmult]{\%*\%}} 29 | allowing for multiplying diffnet objects. 30 | } 31 | \details{ 32 | This function can be usefult to generate alternative graphs, for 33 | example, users could compute the n-steps graph by doing \code{net \%*\% net} 34 | (see examples). 35 | } 36 | \examples{ 37 | # Finding the Simmelian Ties network ---------------------------------------- 38 | 39 | # Random diffnet graph 40 | set.seed(773) 41 | net <- rdiffnet(100, 4, seed.graph='small-world', rgraph.args=list(k=8)) 42 | netsim <- net 43 | 44 | # According to Dekker (2006), Simmelian ties can be computed as follows 45 | netsim <- net * t(net) # Keeping mutal 46 | netsim <- netsim * (netsim \%*\% netsim) 47 | 48 | # Checking out differences (netsim should have less) 49 | nlinks(net) 50 | nlinks(netsim) 51 | 52 | mapply(`-`, nlinks(net), nlinks(netsim)) 53 | 54 | } 55 | \seealso{ 56 | Other diffnet methods: 57 | \code{\link{as.array.diffnet}()}, 58 | \code{\link{c.diffnet}()}, 59 | \code{\link{diffnet-arithmetic}}, 60 | \code{\link{diffnet-class}}, 61 | \code{\link{diffnet_index}}, 62 | \code{\link{plot.diffnet}()}, 63 | \code{\link{summary.diffnet}()} 64 | } 65 | \concept{diffnet methods} 66 | -------------------------------------------------------------------------------- /man/diffreg.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/formula.r 3 | \name{diffreg} 4 | \alias{diffreg} 5 | \title{Diffusion regression model} 6 | \usage{ 7 | diffreg(model, type = c("logit", "probit")) 8 | } 9 | \arguments{ 10 | \item{model}{An object of class formula where the right-hand-side is an object of 11 | class \code{\link[=diffnet]{diffnet}}} 12 | 13 | \item{type}{Character scalar. Either \code{"probit"} or \code{"logit"}.} 14 | } 15 | \value{ 16 | An object of class \code{\link[stats:glm]{glm}}. 17 | } 18 | \description{ 19 | A wrapper of \code{glm}, this function estimates a lagged regression model of 20 | adoption as a function of exposure and other controls as especified by the 21 | user. 22 | } 23 | \details{ 24 | The model must be in the following form: 25 | 26 | \preformatted{ 27 | ~ exposure + covariate1 + covariate2 + ... 28 | } 29 | 30 | Where \code{exposure} can be especified either as a simple term, or as a 31 | call to the exposure function, e.g. to compute exposure with a lag of 32 | length 2, the formula could be: 33 | 34 | \preformatted{ 35 | ~ exposure(lags = 2) + covariate1 + covariate2 + ... 36 | } 37 | 38 | When no argument is passed to \code{exposure}, the function sets a lag 39 | of length 1 by default (see the \emph{Lagged regression} section). 40 | 41 | This is a wrapper of \code{\link[stats:glm]{glm}}. The function does the 42 | following steps: 43 | \enumerate{ 44 | \item Compute exposure by calling \code{exposure} on the LHS (dependent variable). 45 | \item Modify the formula so that the model is on adoption as a function of 46 | exposure and whatever covariates the user specifies. 47 | \item Selects either \code{"probit"} or \code{"logit"} and prepares the call 48 | to \code{glm}. This includes passing the following line: 49 | \preformatted{ 50 | subset = ifelse(is.na(toa), TRUE, toa >= per) 51 | } 52 | This results in including observations that either did not adopted or up to 53 | the time of adoption. 54 | \item Estimates the model. 55 | } 56 | 57 | The data passed to \code{glm} is obtained by using \code{\link{as.data.frame.diffnet}}. 58 | } 59 | \section{Lagged regression}{ 60 | 61 | 62 | The model estimated is a lagged regression model that has two main assumptions: 63 | \enumerate{ 64 | \item The network is exogenous to the behavior (no selection effect) 65 | \item The influence effect (diffusion) happens in a lagged fasion, hence, 66 | exposure is computed lagged. 67 | } 68 | 69 | If either of these two assumptions is not met, then the model becomes endogenous, 70 | ans so inference becomes invalid. 71 | 72 | In the case of the first assumption, the user can overcome the non-exogeneity 73 | problem by providing an alternative network. This can be done by especifying 74 | \code{alt.graph} in the \code{exposure} function so that the network becomes 75 | exogenous to the adoption. 76 | } 77 | 78 | \examples{ 79 | data("medInnovationsDiffNet") 80 | 81 | # Default model 82 | ans <- diffreg( 83 | medInnovationsDiffNet ~ exposure + factor(city) + proage + per) 84 | summary(ans) 85 | } 86 | -------------------------------------------------------------------------------- /man/drawColorKey.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/misc.r 3 | \name{drawColorKey} 4 | \alias{drawColorKey} 5 | \title{Draw a color key in the current device} 6 | \usage{ 7 | drawColorKey( 8 | x, 9 | tick.marks = pretty_within(x), 10 | labels = tick.marks, 11 | main = NULL, 12 | key.pos = c(0.925, 0.975, 0.05, 0.95), 13 | pos = 2, 14 | nlevels = length(tick.marks), 15 | color.palette = viridisLite::viridis(nlevels), 16 | tick.width = c(0.01, 0.0075), 17 | add.box = TRUE, 18 | na.col = NULL, 19 | na.height = 0.1, 20 | na.lab = "n/a", 21 | ... 22 | ) 23 | } 24 | \arguments{ 25 | \item{x}{A numeric vector with the data (it is used to extract the range).} 26 | 27 | \item{tick.marks}{A numeric vector indicating the levels to be included in the axis.} 28 | 29 | \item{labels}{Character vector. When provided, specifies using different 30 | labels for the tick marks than those provided by \code{tick.marjks}.} 31 | 32 | \item{main}{Character scalar. Title of the key.} 33 | 34 | \item{key.pos}{A numeric vector of length 4 with relative coordinates of the 35 | key (as \% of the plotting area, see \code{\link[graphics:par]{par("usr")}})} 36 | 37 | \item{pos}{Integer scalar. Position of the axis as in \code{\link[graphics:text]{text}}.} 38 | 39 | \item{nlevels}{Integer scalar. Number of levels (colors) to include in the color key.} 40 | 41 | \item{color.palette}{Color palette of \code{length(nlevels)}.} 42 | 43 | \item{tick.width}{Numeric vector of length 2 indicating the length of the inner 44 | and outer tick marks as percentage of the axis.} 45 | 46 | \item{add.box}{Logical scalar. When \code{TRUE} adds a box around the key.} 47 | 48 | \item{na.col}{Character scalar. If specified, adds an aditional box indicating the NA color.} 49 | 50 | \item{na.height}{Numeric scalar. Relative height of the NA box. Only use if 51 | \code{na.col} is not \code{NULL}.} 52 | 53 | \item{na.lab}{Character scalar. Label of the \code{NA} block. Only use if 54 | \code{na.col} is not \code{NULL}.} 55 | 56 | \item{...}{Further arguments to be passed to \code{\link[graphics:rect]{rect}}} 57 | } 58 | \value{ 59 | Invisible \code{NULL}. 60 | } 61 | \description{ 62 | Draw a color key in the current device 63 | } 64 | \examples{ 65 | set.seed(166) 66 | x <- rnorm(100) 67 | col <- colorRamp(c("lightblue", "yellow", "red"))((x - min(x))/(max(x) - min(x))) 68 | col <- rgb(col, maxColorValue = 255) 69 | plot(x, col=col, pch=19) 70 | drawColorKey(x, nlevels = 100, border="transparent", 71 | main="Key\nLike A\nBoss") 72 | } 73 | \seealso{ 74 | Other visualizations: 75 | \code{\link{dgr}()}, 76 | \code{\link{diffusionMap}()}, 77 | \code{\link{grid_distribution}()}, 78 | \code{\link{hazard_rate}()}, 79 | \code{\link{plot_adopters}()}, 80 | \code{\link{plot_diffnet}()}, 81 | \code{\link{plot_diffnet2}()}, 82 | \code{\link{plot_infectsuscep}()}, 83 | \code{\link{plot_threshold}()}, 84 | \code{\link{rescale_vertex_igraph}()} 85 | } 86 | \author{ 87 | George G. Vega Yon 88 | } 89 | \concept{visualizations} 90 | \keyword{misc} 91 | -------------------------------------------------------------------------------- /man/ego_variance.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/RcppExports.R 3 | \name{ego_variance} 4 | \alias{ego_variance} 5 | \title{Computes variance of \eqn{Y} at ego level} 6 | \usage{ 7 | ego_variance(graph, Y, funname, all = FALSE) 8 | } 9 | \arguments{ 10 | \item{graph}{A matrix of size \eqn{n\times n}{n*n} of class \code{dgCMatrix}.} 11 | 12 | \item{Y}{A numeric vector of length \eqn{n}.} 13 | 14 | \item{funname}{Character scalar. Comparison to make (see \code{\link{vertex_covariate_compare}}).} 15 | 16 | \item{all}{Logical scalar. When \code{FALSE} (default) \eqn{f_i} is mean at 17 | ego level. Otherwise is fix for all i (see details).} 18 | } 19 | \value{ 20 | A numeric vector of length \eqn{n}. 21 | } 22 | \description{ 23 | Computes variance of \eqn{Y} at ego level 24 | } 25 | \details{ 26 | For each vertex \eqn{i} the variance is computed as follows 27 | 28 | \deqn{% 29 | (\sum_j a_{ij})^{-1}\sum_j a_{ij} \left[f(y_i,y_j) - f_i\right]^2 30 | }{% 31 | (sum_j a(ij))^(-1) * \sum_j a(ij) * [f(y(i),y(j)) - f(i)]^2 32 | } 33 | 34 | Where \eqn{a_{ij}}{a(ij)} is the ij-th element of \code{graph}, \eqn{f} is 35 | the function specified in \code{funname}, and, if \code{all=FALSE} 36 | \eqn{f_i = \sum_j a_{ij}f(y_i,y_j)^2/\sum_ja_{ij}}{f(i)=\sum_j a(ij)f(y(i), y(j))^2/\sum_j a(ij)}, 37 | otherwise \eqn{f_i = f_j = \frac{1}{n^2}\sum_{i,j}f(y_i,y_j)}{f(i)=f(j)=(1/n^2)\sum_(i,j) f(y_i,y_j)} 38 | 39 | 40 | This is an auxiliary function for \code{\link{struct_test}}. The idea is 41 | to compute an adjusted measure of disimilarity between vertices, so the 42 | closest in terms of \eqn{f} is \eqn{i} to its neighbors, the smaller the 43 | relative variance. 44 | } 45 | \seealso{ 46 | \code{\link{struct_test}} 47 | 48 | Other statistics: 49 | \code{\link{bass}}, 50 | \code{\link{classify_adopters}()}, 51 | \code{\link{cumulative_adopt_count}()}, 52 | \code{\link{dgr}()}, 53 | \code{\link{exposure}()}, 54 | \code{\link{hazard_rate}()}, 55 | \code{\link{infection}()}, 56 | \code{\link{moran}()}, 57 | \code{\link{struct_equiv}()}, 58 | \code{\link{threshold}()}, 59 | \code{\link{vertex_covariate_dist}()} 60 | } 61 | \concept{statistics} 62 | -------------------------------------------------------------------------------- /man/fakeDynEdgelist.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/data.r 3 | \name{fakeDynEdgelist} 4 | \alias{fakeDynEdgelist} 5 | \title{Fake dynamic edgelist} 6 | \format{ 7 | A data frame with 22 rows and 4 variables 8 | \describe{ 9 | \item{ego}{Nominating individual} 10 | \item{alter}{Nominated individual} 11 | \item{value}{Strength of the tie} 12 | \item{time}{Integer with the time of the spell} 13 | } 14 | } 15 | \source{ 16 | Generated for the package 17 | } 18 | \description{ 19 | A data frame used for examples in reading edgelist format networks. This 20 | edgelist can be merged with the dataset \code{\link{fakesurveyDyn}}. 21 | } 22 | \seealso{ 23 | Other diffusion datasets: 24 | \code{\link{brfarmers}}, 25 | \code{\link{brfarmersDiffNet}}, 26 | \code{\link{diffusion-data}}, 27 | \code{\link{fakeEdgelist}}, 28 | \code{\link{fakesurvey}}, 29 | \code{\link{fakesurveyDyn}}, 30 | \code{\link{kfamily}}, 31 | \code{\link{kfamilyDiffNet}}, 32 | \code{\link{medInnovations}}, 33 | \code{\link{medInnovationsDiffNet}} 34 | } 35 | \author{ 36 | George G. Vega Yon 37 | } 38 | \concept{diffusion datasets} 39 | -------------------------------------------------------------------------------- /man/fakeEdgelist.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/data.r 3 | \name{fakeEdgelist} 4 | \alias{fakeEdgelist} 5 | \title{Fake static edgelist} 6 | \format{ 7 | A data frame with 11 rows and 3 variables 8 | \describe{ 9 | \item{ego}{Nominating individual} 10 | \item{alter}{Nominated individual} 11 | \item{value}{Strength of the tie} 12 | } 13 | } 14 | \source{ 15 | Generated for the package 16 | } 17 | \description{ 18 | A data frame used for examples in reading edgelist format networks. This 19 | edgelist can be merged with the dataset \code{\link{fakesurvey}}. 20 | } 21 | \seealso{ 22 | Other diffusion datasets: 23 | \code{\link{brfarmers}}, 24 | \code{\link{brfarmersDiffNet}}, 25 | \code{\link{diffusion-data}}, 26 | \code{\link{fakeDynEdgelist}}, 27 | \code{\link{fakesurvey}}, 28 | \code{\link{fakesurveyDyn}}, 29 | \code{\link{kfamily}}, 30 | \code{\link{kfamilyDiffNet}}, 31 | \code{\link{medInnovations}}, 32 | \code{\link{medInnovationsDiffNet}} 33 | } 34 | \author{ 35 | George G. Vega Yon 36 | } 37 | \concept{diffusion datasets} 38 | -------------------------------------------------------------------------------- /man/fakesurvey.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/data.r 3 | \name{fakesurvey} 4 | \alias{fakesurvey} 5 | \title{Fake survey data} 6 | \format{ 7 | A data frame with 9 rows and 9 variables 8 | \describe{ 9 | \item{id}{Unique id at group level} 10 | \item{toa}{Time of adoption} 11 | \item{group}{Group id} 12 | \item{net1}{Network nomination 1} 13 | \item{net2}{Network nomination 2} 14 | \item{net3}{Network nomination 3} 15 | \item{age}{Age of the respondent} 16 | \item{gender}{Gende of the respondent} 17 | \item{note}{Descroption of the respondent} 18 | } 19 | } 20 | \source{ 21 | Generated for the package. 22 | } 23 | \description{ 24 | This data frame is used to ilustrate some of the functions of the package, 25 | in particular, the \code{\link{survey_to_diffnet}} function. This dataset 26 | can be merged with the \code{\link{fakeEdgelist}}. 27 | } 28 | \seealso{ 29 | Other diffusion datasets: 30 | \code{\link{brfarmers}}, 31 | \code{\link{brfarmersDiffNet}}, 32 | \code{\link{diffusion-data}}, 33 | \code{\link{fakeDynEdgelist}}, 34 | \code{\link{fakeEdgelist}}, 35 | \code{\link{fakesurveyDyn}}, 36 | \code{\link{kfamily}}, 37 | \code{\link{kfamilyDiffNet}}, 38 | \code{\link{medInnovations}}, 39 | \code{\link{medInnovationsDiffNet}} 40 | } 41 | \author{ 42 | George G. Vega Yon 43 | } 44 | \concept{diffusion datasets} 45 | -------------------------------------------------------------------------------- /man/fakesurveyDyn.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/data.r 3 | \name{fakesurveyDyn} 4 | \alias{fakesurveyDyn} 5 | \title{Fake longitudinal survey data} 6 | \format{ 7 | A data frame with 18 rows and 10 variables 8 | \describe{ 9 | \item{id}{Unique id at group level} 10 | \item{toa}{Time of adoption} 11 | \item{group}{Group id} 12 | \item{net1}{Network nomination 1} 13 | \item{net2}{Network nomination 2} 14 | \item{net3}{Network nomination 3} 15 | \item{age}{Age of the respondent} 16 | \item{gender}{Gende of the respondent} 17 | \item{note}{Descroption of the respondent} 18 | \item{time}{Timing of the wave} 19 | } 20 | } 21 | \source{ 22 | Generated for the package. 23 | } 24 | \description{ 25 | This data frame is used to ilustrate some of the functions of the package, 26 | in particular, the \code{\link{survey_to_diffnet}} function. This dataset 27 | can be merged with the \code{\link{fakeDynEdgelist}}. 28 | } 29 | \seealso{ 30 | Other diffusion datasets: 31 | \code{\link{brfarmers}}, 32 | \code{\link{brfarmersDiffNet}}, 33 | \code{\link{diffusion-data}}, 34 | \code{\link{fakeDynEdgelist}}, 35 | \code{\link{fakeEdgelist}}, 36 | \code{\link{fakesurvey}}, 37 | \code{\link{kfamily}}, 38 | \code{\link{kfamilyDiffNet}}, 39 | \code{\link{medInnovations}}, 40 | \code{\link{medInnovationsDiffNet}} 41 | } 42 | \author{ 43 | George G. Vega Yon 44 | } 45 | \concept{diffusion datasets} 46 | -------------------------------------------------------------------------------- /man/figures/netdiffuser-logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/USCCANA/netdiffuseR/1efc0be4539d23ab800187c73551624834038e00/man/figures/netdiffuser-logo.png -------------------------------------------------------------------------------- /man/grid_distribution.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/RcppExports.R 3 | \name{grid_distribution} 4 | \alias{grid_distribution} 5 | \title{Distribution over a grid} 6 | \usage{ 7 | grid_distribution(x, y, nlevels = 100L) 8 | } 9 | \arguments{ 10 | \item{x}{Numeric vector of size \eqn{n}} 11 | 12 | \item{y}{Numeric vector of size \eqn{n}} 13 | 14 | \item{nlevels}{Integer scalar. Number of bins to return} 15 | } 16 | \value{ 17 | Returns a list with three elements 18 | \item{x}{Numeric vector of size \code{nlevels} with the class marks for x} 19 | \item{y}{Numeric vector of size \code{nlevels} with the class marks for y} 20 | \item{z}{Numeric matrix of size \code{nlevels} by \code{nlevels} with the distribution % 21 | of the elements in terms of frequency} 22 | } 23 | \description{ 24 | Distribution of pairs over a grid of fix size. 25 | } 26 | \details{ 27 | This function ment for internal use only. 28 | } 29 | \section{Examples}{ 30 | 31 | \preformatted{ 32 | # Generating random vectors of size 100 33 | x <- rnorm(100) 34 | y <- rnorm(100) 35 | 36 | # Calculating distribution 37 | grid_distribution(x,y,20) 38 | } 39 | } 40 | 41 | \seealso{ 42 | Used by \code{\link{plot_infectsuscep}} 43 | 44 | Other visualizations: 45 | \code{\link{dgr}()}, 46 | \code{\link{diffusionMap}()}, 47 | \code{\link{drawColorKey}()}, 48 | \code{\link{hazard_rate}()}, 49 | \code{\link{plot_adopters}()}, 50 | \code{\link{plot_diffnet}()}, 51 | \code{\link{plot_diffnet2}()}, 52 | \code{\link{plot_infectsuscep}()}, 53 | \code{\link{plot_threshold}()}, 54 | \code{\link{rescale_vertex_igraph}()} 55 | } 56 | \concept{visualizations} 57 | \keyword{dplot} 58 | \keyword{misc} 59 | -------------------------------------------------------------------------------- /man/igraph.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/igraph.r 3 | \name{igraph} 4 | \alias{igraph} 5 | \alias{diffnet_to_igraph} 6 | \alias{igraph_to_diffnet} 7 | \title{Coercion between graph classes} 8 | \usage{ 9 | diffnet_to_igraph(graph, slices = 1:nslices(graph)) 10 | 11 | igraph_to_diffnet( 12 | graph = NULL, 13 | graph.list = NULL, 14 | toavar, 15 | t0 = NULL, 16 | t1 = NULL, 17 | ... 18 | ) 19 | } 20 | \arguments{ 21 | \item{graph}{Either a \code{\link{diffnet}} or \code{\link[igraph:igraph]{igraph}} graph object.} 22 | 23 | \item{slices}{An integer vector indicating the slices to subset.} 24 | 25 | \item{graph.list}{A list of \code{igraph} objects.} 26 | 27 | \item{toavar}{Character scalar. Name of the attribute that holds the times of adoption.} 28 | 29 | \item{t0}{Integer scalar. Passed to \code{\link[=diffnet-class]{new_diffnet}}.} 30 | 31 | \item{t1}{Integer scalar. Passed to \code{\link[=diffnet-class]{new_diffnet}}.} 32 | 33 | \item{...}{Further arguments passed to \code{\link{as_diffnet}}.} 34 | } 35 | \value{ 36 | Either a list of \code{length(slices)} \code{igraph} 37 | (\code{diffnet_to_igraph}), or a \code{diffnet} object (\code{igraph_to_diffnet}) 38 | objects. 39 | } 40 | \description{ 41 | Coercion between graph classes 42 | } 43 | \examples{ 44 | # Reading the medical innovation data into igraph -------------------------- 45 | x <- diffnet_to_igraph(medInnovationsDiffNet[,,1:4]) 46 | 47 | # Fetching the times of adoption 48 | igraph::vertex_attr(x[[1]], "toa") 49 | } 50 | \seealso{ 51 | Other Foreign: 52 | \code{\link{network}}, 53 | \code{\link{read_pajek}()}, 54 | \code{\link{read_ucinet_head}()} 55 | } 56 | \concept{Foreign} 57 | -------------------------------------------------------------------------------- /man/isolated.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/adjmat.r 3 | \name{isolated} 4 | \alias{isolated} 5 | \alias{drop_isolated} 6 | \title{Find and remove isolated vertices} 7 | \usage{ 8 | isolated( 9 | graph, 10 | undirected = getOption("diffnet.undirected", FALSE), 11 | self = getOption("diffnet.self", FALSE) 12 | ) 13 | 14 | drop_isolated( 15 | graph, 16 | undirected = getOption("diffnet.undirected", FALSE), 17 | self = getOption("diffnet.self", FALSE) 18 | ) 19 | } 20 | \arguments{ 21 | \item{graph}{Any class of accepted graph format (see \code{\link{netdiffuseR-graphs}}).} 22 | 23 | \item{undirected}{Logical scalar. When \code{TRUE} only the lower triangle of the adjacency matrix will considered (faster).} 24 | 25 | \item{self}{Logical scalar. When \code{TRUE} autolinks (loops, self edges) are allowed (see details).} 26 | } 27 | \value{ 28 | When \code{graph} is an adjacency matrix: 29 | \item{isolated}{an matrix of size \eqn{n\times 1}{n*1} with 1's where a node is isolated} 30 | \item{drop_isolated}{a modified graph excluding isolated vertices.} 31 | 32 | Otherwise, when \code{graph} is a list 33 | \item{isolated}{an matrix of size \eqn{n\times T}{n*T} with 1's where a node is isolated} 34 | \item{drop_isolated}{a modified graph excluding isolated vertices.} 35 | } 36 | \description{ 37 | Find and remove unconnected vertices from the graph. 38 | } 39 | \examples{ 40 | # Generating random graph 41 | set.seed(123) 42 | adjmat <- rgraph_er() 43 | 44 | # Making nodes 1 and 4 isolated 45 | adjmat[c(1,4),] <- 0 46 | adjmat[,c(1,4)] <- 0 47 | adjmat 48 | 49 | # Finding isolated nodes 50 | iso <- isolated(adjmat) 51 | iso 52 | 53 | # Removing isolated nodes 54 | drop_isolated(adjmat) 55 | 56 | 57 | # Now with a dynamic graph 58 | graph <- rgraph_er(n=10, t=3) 59 | 60 | # Making 1 and 5 isolated 61 | graph <- lapply(graph, "[<-", i=c(1,5), j=1:10, value=0) 62 | graph <- lapply(graph, "[<-", i=1:10, j=c(1,5), value=0) 63 | graph 64 | 65 | isolated(graph) 66 | drop_isolated(graph) 67 | } 68 | \seealso{ 69 | Other data management functions: 70 | \code{\link{diffnet-class}}, 71 | \code{\link{edgelist_to_adjmat}()}, 72 | \code{\link{egonet_attrs}()}, 73 | \code{\link{survey_to_diffnet}()} 74 | } 75 | \author{ 76 | George G. Vega Yon 77 | } 78 | \concept{data management functions} 79 | \keyword{manip} 80 | -------------------------------------------------------------------------------- /man/kfamilyDiffNet.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/data.r 3 | \name{kfamilyDiffNet} 4 | \alias{kfamilyDiffNet} 5 | \title{\code{diffnet} version of the Korean Family Planning data} 6 | \format{ 7 | A \code{\link{diffnet}} class object. 8 | } 9 | \description{ 10 | A directed dynamic graph with 1,047 vertices and 11 time periods. The attributes 11 | in the graph are static and described in \code{\link{kfamily}}. 12 | } 13 | \seealso{ 14 | Other diffusion datasets: 15 | \code{\link{brfarmers}}, 16 | \code{\link{brfarmersDiffNet}}, 17 | \code{\link{diffusion-data}}, 18 | \code{\link{fakeDynEdgelist}}, 19 | \code{\link{fakeEdgelist}}, 20 | \code{\link{fakesurvey}}, 21 | \code{\link{fakesurveyDyn}}, 22 | \code{\link{kfamily}}, 23 | \code{\link{medInnovations}}, 24 | \code{\link{medInnovationsDiffNet}} 25 | } 26 | \concept{diffusion datasets} 27 | -------------------------------------------------------------------------------- /man/matrix_compare.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/stats.R 3 | \name{matrix_compare} 4 | \alias{matrix_compare} 5 | \alias{binary-functions} 6 | \alias{compare_matrix} 7 | \title{Non-zero element-wise comparison between two sparse matrices} 8 | \usage{ 9 | matrix_compare(A, B, fun) 10 | 11 | compare_matrix(A, B, fun) 12 | } 13 | \arguments{ 14 | \item{A}{A matrix of size \code{n*m} of class \code{\link[Matrix:dgCMatrix-class]{dgCMatrix}}.} 15 | 16 | \item{B}{A matrix of size \code{n*m} of class \code{\link[Matrix:dgCMatrix-class]{dgCMatrix}}.} 17 | 18 | \item{fun}{A function that receives 2 arguments and returns a scalar.} 19 | } 20 | \value{ 21 | An object of class \code{dgCMatrix} of size \code{n*m}. 22 | } 23 | \description{ 24 | Taking advantage of matrix sparseness, the function only evaluates 25 | \code{fun} between pairs of elements of \code{A} and \code{B} where 26 | either \code{A} or \code{B} have non-zero values. This can be helpful 27 | to implement other binary operators between sparse matrices that may 28 | not be implemented in the \pkg{Matrix} package. 29 | } 30 | \details{ 31 | Instead of comparing element by element, the function 32 | loops through each matrix non-zero elements to make the comparisons, which 33 | in the case of sparse matrices can be more efficient (faster). Algorithmically 34 | it can be described as follows: 35 | 36 | \preformatted{ 37 | # Matrix initialization 38 | init ans[n,m]; 39 | 40 | # Looping through non-zero elements of A 41 | for e_A in E_A: 42 | ans[e_A] = fun(A[e_A], B[e_A]) 43 | 44 | # Looping through non-zero elements of B and applying the function 45 | # in e_B only if it was not applied while looping in E_A. 46 | for e_B in E_B: 47 | if (ans[e_B] == Empty) 48 | ans[e_B] = fun(A[e_B], B[e_B]) 49 | 50 | } 51 | 52 | \code{compare_matrix} is just an alias for \code{matrix_compare}. 53 | } 54 | \examples{ 55 | # These two should yield the same results ----------------------------------- 56 | 57 | # Creating two random matrices 58 | set.seed(89) 59 | A <- rgraph_ba(t = 9, m = 4) 60 | B <- rgraph_ba(t = 9, m = 4) 61 | A;B 62 | 63 | # Comparing 64 | ans0 <- matrix_compare(A,B, function(a,b) (a+b)/2) 65 | 66 | ans1 <- matrix(0, ncol=10, nrow=10) 67 | for (i in 1:10) 68 | for (j in 1:10) 69 | ans1[i,j] <- mean(c(A[i,j], B[i,j])) 70 | 71 | # Are these equal? 72 | all(ans0[] == ans1[]) # Should yield TRUE 73 | 74 | } 75 | \seealso{ 76 | Other dyadic-level comparison functions: 77 | \code{\link{vertex_covariate_compare}()}, 78 | \code{\link{vertex_covariate_dist}()} 79 | } 80 | \concept{dyadic-level comparison functions} 81 | -------------------------------------------------------------------------------- /man/medInnovationsDiffNet.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/data.r 3 | \name{medInnovationsDiffNet} 4 | \alias{medInnovationsDiffNet} 5 | \title{\code{diffnet} version of the Medical Innovation data} 6 | \format{ 7 | A \code{\link{diffnet}} class object. 8 | } 9 | \description{ 10 | A directed dynamic graph with 125 vertices and 18 time periods. The attributes 11 | in the graph are static and described in \code{\link{medInnovations}}. 12 | } 13 | \seealso{ 14 | Other diffusion datasets: 15 | \code{\link{brfarmers}}, 16 | \code{\link{brfarmersDiffNet}}, 17 | \code{\link{diffusion-data}}, 18 | \code{\link{fakeDynEdgelist}}, 19 | \code{\link{fakeEdgelist}}, 20 | \code{\link{fakesurvey}}, 21 | \code{\link{fakesurveyDyn}}, 22 | \code{\link{kfamily}}, 23 | \code{\link{kfamilyDiffNet}}, 24 | \code{\link{medInnovations}} 25 | } 26 | \concept{diffusion datasets} 27 | -------------------------------------------------------------------------------- /man/moran.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/moran.r 3 | \name{moran} 4 | \alias{moran} 5 | \title{Computes Moran's I correlation index} 6 | \usage{ 7 | moran(x, w, normalize.w = TRUE, alternative = "two.sided") 8 | } 9 | \arguments{ 10 | \item{x}{Numeric vector of size \eqn{n}.} 11 | 12 | \item{w}{Numeric matrix of size \eqn{n\times n}{n * n}. Weights. It can be 13 | either a object of class \code{\link{matrix}} or \code{\link[Matrix:dgCMatrix-class]{dgCMatrix}} 14 | from the \code{\link[Matrix]{Matrix}} package.} 15 | 16 | \item{normalize.w}{Logical scalar. When TRUE normalizes rowsums to one (or zero).} 17 | 18 | \item{alternative}{Character String. Specifies the alternative hypothesis that 19 | is tested against the null of no autocorrelation; must be of one \code{"two.sided"}, 20 | \code{"less"}, or \code{"greater"}.} 21 | } 22 | \value{ 23 | A list of class \code{diffnet_moran} with the following elements: 24 | \item{observed}{Numeric scalar. Observed correlation index.} 25 | \item{expected}{Numeric scalar. Expected correlation index equal to \eqn{-1/(N-1)}.} 26 | \item{sd}{Numeric scalar. Standard error under the null.} 27 | \item{p.value}{Numeric scalar. p-value of the specified \code{alternative}.} 28 | } 29 | \description{ 30 | Natively built for computing Moran's I on \code{dgCMatrix} objects, this 31 | routine allows computing the I on large sparse matrices (graphs). Part of 32 | its implementation was based on \code{\link[ape:Moran.I]{ape::Moran.I}}, 33 | which computes the I for dense matrices. 34 | } 35 | \details{ 36 | In the case that the vector \code{x} is close to constant (degenerate random 37 | variable), the statistic becomes irrelevant, and furthermore, the standard error 38 | tends to be undefined (\code{NaN}). 39 | } 40 | \examples{ 41 | 42 | if (require("ape")) { 43 | 44 | # Generating a small random graph 45 | set.seed(123) 46 | graph <- rgraph_ba(t = 4) 47 | w <- approx_geodesic(graph) 48 | x <- rnorm(5) 49 | 50 | # Computing Moran's I 51 | moran(x, w) 52 | 53 | # Comparing with the ape's package version 54 | ape::Moran.I(x, as.matrix(w)) 55 | 56 | } 57 | 58 | } 59 | \references{ 60 | Moran's I. (2015, September 3). In Wikipedia, The Free Encyclopedia. 61 | Retrieved 06:23, December 22, 2015, from \url{https://en.wikipedia.org/w/index.php?title=Moran\%27s_I&oldid=679297766} 62 | } 63 | \seealso{ 64 | Other statistics: 65 | \code{\link{bass}}, 66 | \code{\link{classify_adopters}()}, 67 | \code{\link{cumulative_adopt_count}()}, 68 | \code{\link{dgr}()}, 69 | \code{\link{ego_variance}()}, 70 | \code{\link{exposure}()}, 71 | \code{\link{hazard_rate}()}, 72 | \code{\link{infection}()}, 73 | \code{\link{struct_equiv}()}, 74 | \code{\link{threshold}()}, 75 | \code{\link{vertex_covariate_dist}()} 76 | 77 | Other Functions for inference: 78 | \code{\link{bootnet}()}, 79 | \code{\link{struct_test}()} 80 | } 81 | \author{ 82 | George G. Vega Yon 83 | } 84 | \concept{Functions for inference} 85 | \concept{statistics} 86 | -------------------------------------------------------------------------------- /man/netdiffuseR-graphs.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/graph_data.r 3 | \name{netdiffuseR-graphs} 4 | \alias{netdiffuseR-graphs} 5 | \title{Network data formats} 6 | \value{ 7 | No return value (this manual entry only provides information). 8 | } 9 | \description{ 10 | List of accepted graph formats 11 | } 12 | \details{ 13 | The \pkg{netdiffuseR} package can handle different types of graph 14 | objects. Two general classes are defined across the package's functions: 15 | static graphs, and dynamic graphs. 16 | \itemize{ 17 | \item{In the case of \strong{static graphs}, these are represented as adjacency 18 | matrices of size \eqn{n\times n}{n * n} and can be either \code{\link{matrix}} 19 | (dense matrices) or \code{\link[Matrix:dgCMatrix-class]{dgCMatrix}} 20 | (sparse matrix from the \pkg{\link[Matrix:Matrix]{Matrix}} package). While 21 | most of the package functions are defined for both classes, the default output 22 | graph is sparse, i.e. \code{dgCMatrix}.} 23 | \item{With respect to \strong{dynamic graphs}, these are represented by either 24 | a \code{\link{diffnet}} object, an \code{\link{array}} of size 25 | \eqn{n\times n \times T}{n * n * T}, or a list of size \eqn{T} 26 | with sparse matrices (class \code{dgCMatrix}) of size \eqn{n\times n}{n * n}. 27 | Just like the static graph case, while most of the functions accept both 28 | graph types, the default output is \code{dgCMatrix}.} 29 | } 30 | } 31 | \section{diffnet objects}{ 32 | 33 | In the case of \code{diffnet}-class objects, the following arguments can be omitted 34 | when calling fuictions suitable for graph objects: 35 | \itemize{ 36 | \item{\code{toa}: Time of Adoption vector} 37 | \item{\code{adopt}: Adoption Matrix} 38 | \item{\code{cumadopt}: Cumulative Adoption Matrix} 39 | \item{\code{undirected}: Whether the graph is directed or not} 40 | } 41 | } 42 | 43 | \section{Objects' names}{ 44 | 45 | When possible, \pkg{netdiffuseR} will try to reuse graphs dimensional names, 46 | this is, \code{\link{rownames}}, \code{\link{colnames}}, \code{\link{dimnames}} 47 | and \code{\link{names}} (in the case of dynamic graphs as lists). Otherwise, 48 | when no names are provided, these will be created from scratch. 49 | } 50 | 51 | \author{ 52 | George G. Vega Yon 53 | } 54 | \concept{graph formats} 55 | -------------------------------------------------------------------------------- /man/netdiffuseR-options.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/options.R 3 | \name{netdiffuseR-options} 4 | \alias{netdiffuseR-options} 5 | \title{\pkg{netdiffuseR} default options} 6 | \value{ 7 | The full list of options follows: 8 | \item{undirected}{FALSE} 9 | \item{self}{FALSE} 10 | \item{multiple}{FALSE} 11 | \item{tol}{1e-8 (used for package testing)} 12 | \item{valued}{FALSE} 13 | \item{outgoing}{TRUE} 14 | \item{keep.isolates}{TRUE} 15 | \item{minmax.relative.size}{\code{c(0.025, 0.05)}} 16 | } 17 | \description{ 18 | \pkg{netdiffuseR} default options 19 | } 20 | \details{ 21 | Set of default options used by the package. These can be retrieved 22 | via \code{\link{getOption}} using the prefix \code{diffnet} (see examples) 23 | } 24 | \examples{ 25 | getOption("diffnet.undirected") 26 | getOption("diffnet.multiple") 27 | getOption("diffnet.self") 28 | } 29 | \author{ 30 | George G. Vega Yon 31 | } 32 | -------------------------------------------------------------------------------- /man/netdiffuseR.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/package-doc.r 3 | \name{netdiffuseR} 4 | \alias{netdiffuseR} 5 | \alias{netdiffuseR-package} 6 | \title{netdiffuseR} 7 | \description{ 8 | Statistical analysis, visualization and simulation of diffusion and contagion 9 | processes on networks. The package implements algorithms for 10 | calculating stats such as innovation threshold levels, infectiousness 11 | (contagion) and susceptibility, and hazard rates as presented in Burt (1987), 12 | Valente (1995), and Myers (2000) (among others). 13 | 14 | You can access to the project website at 15 | \url{https://github.com/USCCANA/netdiffuseR} 16 | } 17 | \details{ 18 | Analysis of Diffusion and Contagion Processes on Networks 19 | } 20 | \section{Acknowledgements}{ 21 | 22 | netdiffuseR was created with the support of grant R01 CA157577 from the National Cancer Institute/National Institutes of Health. 23 | } 24 | 25 | \section{Workshops and Tutorials}{ 26 | 27 | 28 | Online you can find several learning resources: 29 | 30 | \itemize{ 31 | \item Sunbelt 2016 \url{https://github.com/USCCANA/netdiffuser-sunbelt2016} 32 | \item NASN 2017 \url{https://github.com/USCCANA/netdiffuser-nasn2017} 33 | \item Sunbelt 2018 \url{https://github.com/USCCANA/netdiffuser-sunbelt2018} 34 | } 35 | } 36 | 37 | \author{ 38 | George G. Vega Yon & Thomas W. Valente 39 | } 40 | -------------------------------------------------------------------------------- /man/nvertices.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/diffnet-methods.r 3 | \name{nvertices} 4 | \alias{nvertices} 5 | \alias{nnodes} 6 | \alias{nedges} 7 | \alias{nlinks} 8 | \alias{nslices} 9 | \title{Count the number of vertices/edges/slices in a graph} 10 | \usage{ 11 | nvertices(graph) 12 | 13 | nnodes(graph) 14 | 15 | nedges(graph) 16 | 17 | nlinks(graph) 18 | 19 | nslices(graph) 20 | } 21 | \arguments{ 22 | \item{graph}{Any class of accepted graph format (see \code{\link{netdiffuseR-graphs}}).} 23 | } 24 | \value{ 25 | For \code{nvertices} and \code{nslices}, an integer scalar equal to the number 26 | of vertices and slices in the graph. Otherwise, from \code{nedges}, either a list 27 | of size \eqn{t} with the counts of edges (non-zero elements in the adjacency matrices) at 28 | each time period, or, when \code{graph} is static, a single scalar with 29 | such number. 30 | } 31 | \description{ 32 | Count the number of vertices/edges/slices in a graph 33 | } 34 | \details{ 35 | \code{nnodes} and \code{nlinks} are just aliases for \code{nvertices} and 36 | \code{nedges} respectively. 37 | } 38 | \examples{ 39 | # Creating a dynamic graph (we will use this for all the classes) ----------- 40 | set.seed(13133) 41 | diffnet <- rdiffnet(100, 4) 42 | 43 | # Lets use the first time period as a static graph 44 | graph_mat <- diffnet$graph[[1]] 45 | graph_dgCMatrix <- methods::as(graph_mat, "dgCMatrix") 46 | 47 | # Now lets generate the other dynamic graphs 48 | graph_list <- diffnet$graph 49 | graph_array <- as.array(diffnet) # using the as.array method for diffnet objects 50 | 51 | # Now we can compare vertices counts 52 | nvertices(diffnet) 53 | nvertices(graph_list) 54 | nvertices(graph_array) 55 | 56 | nvertices(graph_mat) 57 | nvertices(graph_dgCMatrix) 58 | 59 | # ... and edges count 60 | nedges(diffnet) 61 | nedges(graph_list) 62 | nedges(graph_array) 63 | 64 | nedges(graph_mat) 65 | nedges(graph_dgCMatrix) 66 | } 67 | -------------------------------------------------------------------------------- /man/permute_graph.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/rewire.r 3 | \name{permute_graph} 4 | \alias{permute_graph} 5 | \alias{CUG} 6 | \alias{QAP} 7 | \alias{rewire_permute} 8 | \alias{rewire_qap} 9 | \title{Permute the values of a matrix} 10 | \usage{ 11 | permute_graph(graph, self = FALSE, multiple = FALSE) 12 | 13 | rewire_permute(graph, self = FALSE, multiple = FALSE) 14 | 15 | rewire_qap(graph) 16 | } 17 | \arguments{ 18 | \item{graph}{Any class of accepted graph format (see \code{\link{netdiffuseR-graphs}}).} 19 | 20 | \item{self}{Logical scalar. When \code{TRUE} autolinks (loops, self edges) are allowed (see details).} 21 | 22 | \item{multiple}{Logical scalar. When \code{TRUE} allows multiple edges.} 23 | } 24 | \value{ 25 | A permuted version of \code{graph}. 26 | } 27 | \description{ 28 | \code{permute_graph} Shuffles the values of a matrix either considering 29 | \emph{loops} and \emph{multiple} links (which are processed as cell values 30 | different than 1/0). \code{rewire_qap} generates a new graph \code{graph}\eqn{'} 31 | that is isomorphic to \code{graph}. 32 | } 33 | \examples{ 34 | # Simple example ------------------------------------------------------------ 35 | set.seed(1231) 36 | g <- rgraph_ba(t=9) 37 | g 38 | 39 | # These preserve the density 40 | permute_graph(g) 41 | permute_graph(g) 42 | 43 | # These are isomorphic to g 44 | rewire_qap(g) 45 | rewire_qap(g) 46 | 47 | } 48 | \references{ 49 | Anderson, B. S., Butts, C., & Carley, K. (1999). The interaction of size and 50 | density with graph-level indices. Social Networks, 21(3), 239–267. 51 | \doi{10.1016/S0378-8733(99)00011-8} 52 | 53 | Mantel, N. (1967). The detection of disease clustering and a generalized 54 | regression approach. Cancer Research, 27(2), 209–20. 55 | } 56 | \seealso{ 57 | This function can be used as null distribution in \code{struct_test} 58 | 59 | Other simulation functions: 60 | \code{\link{rdiffnet}()}, 61 | \code{\link{rewire_graph}()}, 62 | \code{\link{rgraph_ba}()}, 63 | \code{\link{rgraph_er}()}, 64 | \code{\link{rgraph_ws}()}, 65 | \code{\link{ring_lattice}()} 66 | } 67 | \author{ 68 | George G. Vega Yon 69 | } 70 | \concept{simulation functions} 71 | -------------------------------------------------------------------------------- /man/plot.diffnet.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/diffnet-methods.r 3 | \name{plot.diffnet} 4 | \alias{plot.diffnet} 5 | \title{S3 plotting method for diffnet objects.} 6 | \usage{ 7 | \method{plot}{diffnet}( 8 | x, 9 | y = NULL, 10 | t = 1, 11 | vertex.color = c(adopt = "steelblue", noadopt = "white"), 12 | vertex.size = "degree", 13 | main = "Diffusion network in time \%d", 14 | minmax.relative.size = getOption("diffnet.minmax.relative.size", c(0.01, 0.04)), 15 | ... 16 | ) 17 | } 18 | \arguments{ 19 | \item{x}{An object of class \code{\link[=diffnet-class]{diffnet}}} 20 | 21 | \item{y}{Ignored.} 22 | 23 | \item{t}{Integer scalar indicating the time slice to plot.} 24 | 25 | \item{vertex.color}{Character scalar/vector. Color of the vertices.} 26 | 27 | \item{vertex.size}{Either a numeric scalar or vector of size \eqn{n}, or any 28 | of the following values: "indegree", "degree", or "outdegree" (see details).} 29 | 30 | \item{main}{Character. A title template to be passed to sprintf.} 31 | 32 | \item{minmax.relative.size}{Passed to \code{\link{rescale_vertex_igraph}}.} 33 | 34 | \item{...}{Further arguments passed to \code{\link[igraph:plot.igraph]{plot.igraph}}.} 35 | } 36 | \value{ 37 | A matrix with the coordinates of the vertices. 38 | } 39 | \description{ 40 | S3 plotting method for diffnet objects. 41 | } 42 | \details{ 43 | Plotting is done via the function \code{\link[igraph:plot.igraph]{plot.igraph}}. 44 | 45 | When \code{vertex.size} is either of \code{"degree"}, \code{"indegree"}, or 46 | \code{"outdegree"}, \code{vertex.size} will be replace with \code{dgr(.,cmode = )} 47 | so that the vertex size reflects the desired degree. 48 | 49 | The argument \code{minmax.relative.size} is passed to \code{\link{rescale_vertex_igraph}} 50 | which adjusts \code{vertex.size} so that the largest and smallest vertices 51 | have a relative size of \code{minmax.relative.size[2]} and 52 | \code{minmax.relative.size[1]} respectively with respect to the x-axis. 53 | } 54 | \examples{ 55 | 56 | data(medInnovationsDiffNet) 57 | plot(medInnovationsDiffNet) 58 | 59 | 60 | } 61 | \seealso{ 62 | Other diffnet methods: 63 | \code{\link{\%*\%}()}, 64 | \code{\link{as.array.diffnet}()}, 65 | \code{\link{c.diffnet}()}, 66 | \code{\link{diffnet-arithmetic}}, 67 | \code{\link{diffnet-class}}, 68 | \code{\link{diffnet_index}}, 69 | \code{\link{summary.diffnet}()} 70 | } 71 | \author{ 72 | George G. Vega Yon 73 | } 74 | \concept{diffnet methods} 75 | -------------------------------------------------------------------------------- /man/plot_adopters.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/diffnet-methods.r 3 | \name{plot_adopters} 4 | \alias{plot_adopters} 5 | \title{Visualize adopters and cumulative adopters} 6 | \usage{ 7 | plot_adopters( 8 | obj, 9 | freq = FALSE, 10 | what = c("adopt", "cumadopt"), 11 | add = FALSE, 12 | include.legend = TRUE, 13 | include.grid = TRUE, 14 | pch = c(21, 24), 15 | type = c("b", "b"), 16 | ylim = if (!freq) c(0, 1) else NULL, 17 | lty = c(1, 1), 18 | col = c("black", "black"), 19 | bg = c("tomato", "gray"), 20 | xlab = "Time", 21 | ylab = ifelse(freq, "Frequency", "Proportion"), 22 | main = "Adopters and Cumulative Adopters", 23 | ... 24 | ) 25 | } 26 | \arguments{ 27 | \item{obj}{Either a diffnet object or a cumulative a doption matrix.} 28 | 29 | \item{freq}{Logical scalar. When TRUE frequencies are plotted instead of proportions.} 30 | 31 | \item{what}{Character vector of length 2. What to plot.} 32 | 33 | \item{add}{Logical scalar. When TRUE lines and dots are added to the current graph.} 34 | 35 | \item{include.legend}{Logical scalar. When TRUE a legend of the graph is plotted.} 36 | 37 | \item{include.grid}{Logical scalar. When TRUE, the grid of the graph is drawn} 38 | 39 | \item{pch}{Integer vector of length 2. See \code{\link{matplot}}.} 40 | 41 | \item{type}{Character vector of length 2. See \code{\link{matplot}}.} 42 | 43 | \item{ylim}{Numeric vector of length 2. Sets the plotting limit for the y-axis.} 44 | 45 | \item{lty}{Numeric vector of length 2. See \code{\link{matplot}}.} 46 | 47 | \item{col}{Character vector of length 2. See \code{\link{matplot}}.} 48 | 49 | \item{bg}{Character vector of length 2. See \code{\link{matplot}}.} 50 | 51 | \item{xlab}{Character scalar. Name of the x-axis.} 52 | 53 | \item{ylab}{Character scalar. Name of the y-axis.} 54 | 55 | \item{main}{Character scalar. Title of the plot} 56 | 57 | \item{...}{Further arguments passed to \code{\link{matplot}}.} 58 | } 59 | \value{ 60 | A matrix as described in \code{\link{cumulative_adopt_count}}. 61 | } 62 | \description{ 63 | Visualize adopters and cumulative adopters 64 | } 65 | \examples{ 66 | # Generating a random diffnet ----------------------------------------------- 67 | set.seed(821) 68 | diffnet <- rdiffnet(100, 5, seed.graph="small-world", seed.nodes="central") 69 | 70 | plot_adopters(diffnet) 71 | 72 | # Alternatively, we can use a TOA Matrix 73 | toa <- sample(c(NA, 2010L,2015L), 20, TRUE) 74 | mat <- toa_mat(toa) 75 | plot_adopters(mat$cumadopt) 76 | } 77 | \seealso{ 78 | Other visualizations: 79 | \code{\link{dgr}()}, 80 | \code{\link{diffusionMap}()}, 81 | \code{\link{drawColorKey}()}, 82 | \code{\link{grid_distribution}()}, 83 | \code{\link{hazard_rate}()}, 84 | \code{\link{plot_diffnet}()}, 85 | \code{\link{plot_diffnet2}()}, 86 | \code{\link{plot_infectsuscep}()}, 87 | \code{\link{plot_threshold}()}, 88 | \code{\link{rescale_vertex_igraph}()} 89 | } 90 | \author{ 91 | George G. Vega Yon 92 | } 93 | \concept{visualizations} 94 | -------------------------------------------------------------------------------- /man/pretty_within.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/misc.r 3 | \name{pretty_within} 4 | \alias{pretty_within} 5 | \title{Pretty numbers within a range.} 6 | \usage{ 7 | pretty_within(x, min.n = 5, xrange = range(x, na.rm = TRUE), ...) 8 | } 9 | \arguments{ 10 | \item{x}{Numeric vector passed to \code{\link[base:pretty]{pretty}}.} 11 | 12 | \item{min.n}{Integer scalar passed to \code{\link[base:pretty]{pretty}}.} 13 | 14 | \item{xrange}{Numeric vector of length 2. Indicates the range in which the 15 | output vector should lie on.} 16 | 17 | \item{...}{Further arguments passed to the method. 18 | 19 | The only difference with \code{pretty} is that this function subsets the 20 | resulting vector as 21 | 22 | \code{tick[(tick >= xrange[1]) & (tick <= xrange[2])]}} 23 | } 24 | \value{ 25 | A vector sequence of `n + 1` round values in the specified range. 26 | } 27 | \description{ 28 | A wrapper for \code{\link[base:pretty]{pretty}}. 29 | } 30 | \examples{ 31 | # Simple example ------------------------------------------------------------ 32 | set.seed(3331) 33 | x <- runif(10) 34 | pretty(x) 35 | pretty_within(x) 36 | range(x) 37 | } 38 | \keyword{misc} 39 | -------------------------------------------------------------------------------- /man/read_pajek.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/read_write_foreign.r 3 | \name{read_pajek} 4 | \alias{read_pajek} 5 | \alias{read_net} 6 | \alias{read_dl} 7 | \alias{read_ml} 8 | \title{Read foreign graph formats} 9 | \source{ 10 | From the pajek manual \url{http://mrvar.fdv.uni-lj.si/pajek/pajekman.pdf} 11 | } 12 | \usage{ 13 | read_pajek(x) 14 | 15 | read_ml(x) 16 | } 17 | \arguments{ 18 | \item{x}{Character scalar. Path to the file to be imported.} 19 | } 20 | \value{ 21 | In the case of \code{read_pajek}, a list with three elements 22 | \item{vertices}{A data frame with \eqn{n} rows and two columns: id and label} 23 | \item{edges}{If not null, a list of data frames with three columns: ego, alter, w (weight)} 24 | \item{edgelist}{If not null, a list of data frame with three columns: ego, alter, w (weight)} 25 | 26 | For \code{read_ml}, a list with two elements: 27 | \item{adjmat}{An array with the graph} 28 | \item{meta}{A list with metadata} 29 | } 30 | \description{ 31 | Reading pajek and Ucinet files, this function returns weighted edgelists in the form of 32 | data frames including a data frame of the vertices. (function on development) 33 | } 34 | \details{ 35 | Since .net files allow working with multi-relational networks (more than one 36 | class of edge), the function returns lists of edges and edgeslist with the corresponding 37 | tag on the .net file. For example, if the .net file contains 38 | 39 | \preformatted{ 40 | *Arcslist :9 "SAMPPR" 41 | ... 42 | *Arcslist :10 "SAMNPR" 43 | } 44 | 45 | The output will include data frames of edgelists with those tags. 46 | } 47 | \examples{ 48 | # From .net: Sampson monastery data from UCINET dataset --------------------- 49 | 50 | # Reading the arcs/edges format 51 | path <- system.file("extdata", "SAMPSON.NET", package = "netdiffuseR") 52 | SAMPSON <- read_pajek(path) 53 | 54 | # Reading the arcslist/edgelist format 55 | path <- system.file("extdata", "SAMPSONL.NET", package = "netdiffuseR") 56 | SAMPSONL <- read_pajek(path) 57 | 58 | # From DL (UCINET): Sampson monastery data (again) -------------------------- 59 | path <- system.file("extdata", "SAMPSON.DAT", package = "netdiffuseR") 60 | SAMPSONL <- read_ml(path) 61 | 62 | } 63 | \seealso{ 64 | Other Foreign: 65 | \code{\link{igraph}}, 66 | \code{\link{network}}, 67 | \code{\link{read_ucinet_head}()} 68 | } 69 | \author{ 70 | George G. Vega Yon 71 | } 72 | \concept{Foreign} 73 | -------------------------------------------------------------------------------- /man/read_ucinet_head.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/read_write_foreign.r 3 | \name{read_ucinet_head} 4 | \alias{read_ucinet_head} 5 | \alias{ucinet} 6 | \alias{UCINET} 7 | \alias{read_ucinet} 8 | \title{Reads UCINET files} 9 | \usage{ 10 | read_ucinet_head(f) 11 | 12 | read_ucinet(f, echo = FALSE) 13 | } 14 | \arguments{ 15 | \item{f}{Character scalar. Name of the header file. e.g. \code{mydata.##h}.} 16 | 17 | \item{echo}{Logical scalar. When \code{TRUE} shows a message.} 18 | } 19 | \value{ 20 | An array including dimnames (if there are) and the following attributes: 21 | \item{headerversion}{Character scalar} 22 | \item{year}{Integer. Year the file was created} 23 | \item{month}{Integer. Month of the year the file was created.} 24 | \item{day}{Integer. Day of the month the file was created.} 25 | \item{dow}{Integer. Day of the week the file was created.} 26 | \item{labtype}{} 27 | \item{infile.dt}{Character scalar. Type of data of the array.} 28 | \item{dim}{Integer vector. Dimensions of the array.} 29 | \item{tit}{Character scalar. Title of the file.} 30 | \item{haslab}{Logical vector. Whether each dim has a label.} 31 | } 32 | \description{ 33 | Reads UCINET files 34 | 35 | Read UCINET files (binary) 36 | } 37 | \seealso{ 38 | Other Foreign: 39 | \code{\link{igraph}}, 40 | \code{\link{network}}, 41 | \code{\link{read_pajek}()} 42 | } 43 | \concept{Foreign} 44 | -------------------------------------------------------------------------------- /man/recode.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/misc.r 3 | \name{recode} 4 | \alias{recode} 5 | \alias{recode.data.frame} 6 | \alias{recode.matrix} 7 | \title{Recodes an edgelist such that ids go from 1 to n} 8 | \usage{ 9 | recode(data, ...) 10 | 11 | \method{recode}{data.frame}(data, ...) 12 | 13 | \method{recode}{matrix}(data, ...) 14 | } 15 | \arguments{ 16 | \item{data}{Edgelist as either a matrix or dataframe with ego and alter} 17 | 18 | \item{...}{Further arguments for the method (ignored)} 19 | } 20 | \value{ 21 | A recoded edgelist as a two-column matrix/data.frame depending 22 | on the class of \code{data}. The output includes an attribute called "recode" 23 | which contains a two column data.frame providing a mapping between the 24 | previous code and the new code (see the examples) 25 | } 26 | \description{ 27 | Recodes an edgelist such that ids go from 1 to n 28 | } 29 | \details{ 30 | Required for using most of the package's functions, as ids are used 31 | as a reference for accessing elements in adjacency matrices. 32 | } 33 | \examples{ 34 | # Simple example ------------------------------------------------------------ 35 | edgelist <- cbind(c(1,1,3,6),c(4,3,200,1)) 36 | edgelist 37 | recoded_edgelist <- recode(edgelist) 38 | recoded_edgelist 39 | 40 | # Retrieving the "recode" attribute 41 | attr(recoded_edgelist, "recode") 42 | } 43 | \seealso{ 44 | \code{\link{edgelist_to_adjmat}} 45 | } 46 | \author{ 47 | George G. Vega Yon 48 | } 49 | \keyword{misc} 50 | -------------------------------------------------------------------------------- /man/rgraph_er.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/random_graph.R 3 | \name{rgraph_er} 4 | \alias{rgraph_er} 5 | \alias{bernoulli} 6 | \title{Erdos-Renyi model} 7 | \usage{ 8 | rgraph_er( 9 | n = 10, 10 | t = 1, 11 | p = 0.01, 12 | undirected = getOption("diffnet.undirected"), 13 | weighted = FALSE, 14 | self = getOption("diffnet.self"), 15 | as.edgelist = FALSE 16 | ) 17 | } 18 | \arguments{ 19 | \item{n}{Integer. Number of vertices} 20 | 21 | \item{t}{Integer. Number of time periods} 22 | 23 | \item{p}{Double. Probability of a link between ego and alter.} 24 | 25 | \item{undirected}{Logical scalar. Whether the graph is undirected or not.} 26 | 27 | \item{weighted}{Logical. Whether the graph is weighted or not.} 28 | 29 | \item{self}{Logical. Whether it includes self-edges.} 30 | 31 | \item{as.edgelist}{Logical. When TRUE the graph is presented as an edgelist 32 | instead of an adjacency matrix.} 33 | } 34 | \value{ 35 | A graph represented by an adjacency matrix (if \code{t=1}), or an array of 36 | adjacency matrices (if \code{t>1}). 37 | } 38 | \description{ 39 | Generates a bernoulli random graph. 40 | } 41 | \details{ 42 | For each pair of nodes \eqn{\{i,j\}}{{i,j}}, an edge is created 43 | with probability \eqn{p}, this is, \eqn{Pr\{Link i-j\} = Pr\{x"} or \code{"greater"}, 33 | \code{"<"} or \code{"smaller"}, \code{">="} or \code{"greaterequal"}, 34 | \code{"<="} or \code{"smallerequal"}, \code{"=="} or \code{"equal"}. 35 | } 36 | \examples{ 37 | 38 | # Basic example ------------------------------------------------------------ 39 | set.seed(1313) 40 | G <- rgraph_ws(10, 4, .2) 41 | x <- rnorm(10) 42 | 43 | vertex_covariate_compare(G, x, "distance") 44 | vertex_covariate_compare(G, x, "^2") 45 | vertex_covariate_compare(G, x, ">=") 46 | vertex_covariate_compare(G, x, "<=") 47 | } 48 | \seealso{ 49 | Other dyadic-level comparison functions: 50 | \code{\link{matrix_compare}()}, 51 | \code{\link{vertex_covariate_dist}()} 52 | } 53 | \concept{dyadic-level comparison functions} 54 | -------------------------------------------------------------------------------- /man/vertex_covariate_dist.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/RcppExports.R, R/stats.R 3 | \name{vertex_covariate_dist} 4 | \alias{vertex_covariate_dist} 5 | \alias{p-norm} 6 | \alias{mahalanobis} 7 | \alias{minkowski} 8 | \alias{vertex_mahalanobis_dist} 9 | \title{Computes covariate distance between connected vertices} 10 | \usage{ 11 | vertex_covariate_dist(graph, X, p = 2) 12 | 13 | vertex_mahalanobis_dist(graph, X, S) 14 | } 15 | \arguments{ 16 | \item{graph}{A square matrix of size \eqn{n} of class dgCMatrix.} 17 | 18 | \item{X}{A numeric matrix of size \eqn{n \times K}{n * K}. Vertices attributes} 19 | 20 | \item{p}{Numeric scalar. Norm to compute} 21 | 22 | \item{S}{Square matrix of size \code{ncol(x)}. Usually the var-covar matrix.} 23 | } 24 | \value{ 25 | A matrix of size \eqn{n\times n}{n * n} of class \code{dgCMatrix}. Will 26 | be symmetric only if \code{graph} is symmetric. 27 | } 28 | \description{ 29 | Computes covariate distance between connected vertices 30 | } 31 | \details{ 32 | Faster than \code{\link{dist}}, these functions compute distance metrics 33 | between pairs of vertices that are connected (otherwise skip). 34 | 35 | The function \code{vertex_covariate_dist} is the simil of \code{\link{dist}} 36 | and returns p-norms (Minkowski distance). It is implemented as follows (for 37 | each pair of vertices): 38 | 39 | \deqn{% 40 | D_{ij} = \left(\sum_{k=1}^K \left|X_{ik} - X_{jk}\right|^{p} \right)^{1/p}\mbox{ if }graph_{i,j}\neq 0 41 | }{% 42 | D(i,j) = [\sum_k abs(X(i,k) - X(j,k))^p]^(1/p) if graph(i,j) != 0 43 | } 44 | 45 | In the case of mahalanobis distance, for each pair of vertex \eqn{(i,j)}, the 46 | distance is computed as follows: 47 | 48 | \deqn{% 49 | D_{ij} = \left( (X_i - X_j)\times S \times (X_i - X_j)' \right)^{1/2}\mbox{ if }graph_{i,j}\neq 0 50 | }{% 51 | D(i,j) = sqrt[(X(i) - X(j)) \%*\% S \%*\% t(X(i) - X(j))] if graph(i,j) != 0 52 | } 53 | } 54 | \examples{ 55 | # Distance (aka p norm) ----------------------------------------------------- 56 | set.seed(123) 57 | G <- rgraph_ws(20, 4, .1) 58 | X <- matrix(runif(40), ncol=2) 59 | 60 | vertex_covariate_dist(G, X)[1:5, 1:5] 61 | 62 | # Mahalanobis distance ------------------------------------------------------ 63 | S <- var(X) 64 | 65 | M <- vertex_mahalanobis_dist(G, X, S) 66 | 67 | # Example with diffnet objects ---------------------------------------------- 68 | 69 | data(medInnovationsDiffNet) 70 | X <- cbind( 71 | medInnovationsDiffNet[["proage"]], 72 | medInnovationsDiffNet[["attend"]] 73 | ) 74 | 75 | S <- var(X, na.rm=TRUE) 76 | ans <- vertex_mahalanobis_dist(medInnovationsDiffNet, X, S) 77 | 78 | } 79 | \references{ 80 | Mahalanobis distance. (2016, September 27). In Wikipedia, The Free Encyclopedia. 81 | Retrieved 20:31, September 27, 2016, from 82 | \url{https://en.wikipedia.org/w/index.php?title=Mahalanobis_distance&oldid=741488252} 83 | } 84 | \seealso{ 85 | \code{\link[stats:mahalanobis]{mahalanobis}} in the stats package. 86 | 87 | Other statistics: 88 | \code{\link{bass}}, 89 | \code{\link{classify_adopters}()}, 90 | \code{\link{cumulative_adopt_count}()}, 91 | \code{\link{dgr}()}, 92 | \code{\link{ego_variance}()}, 93 | \code{\link{exposure}()}, 94 | \code{\link{hazard_rate}()}, 95 | \code{\link{infection}()}, 96 | \code{\link{moran}()}, 97 | \code{\link{struct_equiv}()}, 98 | \code{\link{threshold}()} 99 | 100 | Other dyadic-level comparison functions: 101 | \code{\link{matrix_compare}()}, 102 | \code{\link{vertex_covariate_compare}()} 103 | } 104 | \author{ 105 | George G. Vega Yon 106 | } 107 | \concept{dyadic-level comparison functions} 108 | \concept{statistics} 109 | -------------------------------------------------------------------------------- /man/weighted_var.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/plot_diffnet2.r 3 | \name{weighted_var} 4 | \alias{weighted_var} 5 | \alias{wvar} 6 | \title{Computes weighted variance} 7 | \usage{ 8 | weighted_var(x, w) 9 | 10 | wvar(x, w) 11 | } 12 | \arguments{ 13 | \item{x}{A numeric vector of length \eqn{n}.} 14 | 15 | \item{w}{A numeric vector of length \eqn{n}.} 16 | } 17 | \value{ 18 | Numeric scalar with the weighted variance. 19 | } 20 | \description{ 21 | Computes weighted variance 22 | } 23 | \details{ 24 | \code{weighted_variance} implements weighted variance computation 25 | in the following form: 26 | \deqn{% 27 | \frac{\sum_i w_i'(x_i - \bar x)^2}{(1-n)} 28 | }{% 29 | sum[w(i)'(x(i) - w.mean(x))^2/(1-n)] 30 | } 31 | 32 | where \eqn{w_i'=w_i/\sum_i w_i}{w(i)' = w(i)/sum(w)}, and 33 | \eqn{\bar x = \sum_i w_i'x_i}{w.mean(x)=sum[w(i)'*x(i)]}. 34 | } 35 | \seealso{ 36 | This function is used in \code{\link{diffmap}}. 37 | } 38 | -------------------------------------------------------------------------------- /netdiffuseR.Rproj: -------------------------------------------------------------------------------- 1 | Version: 1.0 2 | 3 | RestoreWorkspace: No 4 | SaveWorkspace: No 5 | AlwaysSaveHistory: Default 6 | 7 | EnableCodeIndexing: Yes 8 | UseSpacesForTab: Yes 9 | NumSpacesForTab: 2 10 | Encoding: UTF-8 11 | 12 | RnwWeave: knitr 13 | LaTeX: pdfLaTeX 14 | 15 | AutoAppendNewline: Yes 16 | StripTrailingWhitespace: Yes 17 | 18 | BuildType: Package 19 | PackageUseDevtools: Yes 20 | PackageInstallArgs: --no-multiarch --with-keep.source 21 | PackageCheckArgs: --as-cran --no-vignettes 22 | PackageRoxygenize: rd,collate,namespace 23 | -------------------------------------------------------------------------------- /next_release.md: -------------------------------------------------------------------------------- 1 | # Development road 2 | 3 | The following document details expectations for the comming versions. There is no guarantee on the implementation of any of the points here. 4 | 5 | # CRAN 1.16.4: Expected 6 | 7 | ## Polishing 8 | 9 | - Review manuals: Description of arguments and name of the functions. 10 | - ~~Aliases creation: `select_egoalter` `table_...`~~ 11 | - New meta on the diffnet class: 12 | * ~~name: 'A diffnet network'~~ 13 | * ~~description 'Diffnet network with no description'~~ 14 | * timestamp (maybe auto update) 'DATE' 15 | * author: 'user' 16 | * netdiffuseR.version: 1.16.6 17 | Plus some other stuff: 18 | * coordinates (xyz) 19 | * colors 20 | * vertex size 21 | 22 | ## Testing 23 | 24 | - `survey_to_diffnet`, ~~`edgelist_to_adjmat`~~ 25 | - ~~`diffnet_as_igraph`, `igraph_as_diffnet`~~ 26 | 27 | 28 | ## Developing 29 | 30 | - ~~`diffnet_to_networkDynamic`, `networkDynamic_to_diffnet`. Need to reach out the author of Carter Butts: Is there any way to access networkDynamic objects formal definition??~~ 31 | 32 | - ~~`rewire_dgr_preserve`: A brief comparison on igraph and netdiffuseR rewiring algorithms shows that igraph has no significan speed improvement in small-medium graphs. This may be due to having a similar rewiring algorithm. The dgr preserve should work in a similar fashion and should incorporate the call to `std::remove` method.~~ 33 | 34 | - ~~Raise the level of `ARMA_BIT_64INT`: Create a toy package in which, by simulations, we create big sparse matrices of class `dgCMatrix` do read/write operations both from R and from C++.~~ 35 | 36 | - `read_ucinet` and rename `read_ucinet` to `read_dl`. And write versions of it. It will be useful to ask Steven B. if is there any way of using UCINET to analyze dynamic data. 37 | 38 | - `read_net` Talk with the developer to see is they have more information (aditional reference) on the data formatting for dynamic graphs and attributes. Recall UCINET's documents provided with spreadsheets pointing to data types and structure. 39 | 40 | ## Improving 41 | 42 | - ~~`rdiffnet`:~~ 43 | Set initial adopters by providing a vector: 44 | - logical 45 | - integer (of length n) 46 | - integer (of random length) 47 | - character (ids, rownames) 48 | 49 | - What happens in `survey_to_diffnet` when a data.frame is provided, but se set to fill data and the checking done over the dimmensions of the data? 50 | 51 | ## Examples 52 | 53 | - Include the survival analysis example: Maybe use the recidivism data mixed with social data? Find a paper where someone does that 54 | - Include a probit/logit model 55 | - ~~Write down an example with the function `select_egoalter` and rename it.~~ 56 | -------------------------------------------------------------------------------- /playground/attrs.R: -------------------------------------------------------------------------------- 1 | rm(list=ls()) 2 | library(netdiffuseR) 3 | set.seed(123) 4 | diffnet <- rdiffnet(20, 5, seed.graph = "small-world", rewire.args = list(p=.2)) 5 | 6 | 7 | 8 | get_egonet_attrs <- function(...) UseMethod("get_egonet_attrs") 9 | 10 | get_egonet_attrs.default <-function(graph, attrs, i=1:ncol(graph), what=c("indegree")) { 11 | lapply(i, function(x) { 12 | index <- graph[x,] 13 | print(index) 14 | attrs[index] 15 | }) 16 | } 17 | 18 | get_egonet_attrs.list <- function(graph, attrs, i, t=1:length(graph), what) { 19 | # Checking list length 20 | if (any(!(t %in% 1:length(graph)))) stop("-t- must be within 1 and T.") 21 | 22 | lapply(graph[t], function(g) get_egonet_attrs(g, attrs, i, what)) 23 | } 24 | 25 | get_egonet_attrs.diffnet <- function(graph, i=1:graph$meta$n, t=1:length(graph$graph), what=c("indegree")) { 26 | get_egonet_attrs.list(graph$graph, attrs = graph$toa, i = i, t = t, what) 27 | } 28 | 29 | # plot(diffnet, vertex.cex = 1, displaylabels = TRUE) 30 | x <- get_egonet_attrs(diffnet, i=6) 31 | -------------------------------------------------------------------------------- /playground/epimodel/epimodel.r: -------------------------------------------------------------------------------- 1 | rm(list = ls()) 2 | 3 | library(EpiModel) 4 | 5 | set.seed(12345) 6 | 7 | nw <- network::network.initialize(n = 1e3, directed = FALSE) 8 | nw <- network::set.vertex.attribute(nw, "risk", rep(0:1, each=500)) 9 | 10 | formation <- ~edges + nodefactor("risk") + nodematch("risk") + concurrent 11 | 12 | target.stats <- c(250, 375, 225, 100) 13 | coef.diss <- dissolution_coefs(dissolution = ~offset(edges), duration = 80) 14 | coef.diss 15 | 16 | # Step 1 17 | est1 <- netest(nw, formation, target.stats, coef.diss) 18 | 19 | # Step 2 20 | dx <- netdx(est1, nsims=10, nsteps = 1000) 21 | dx 22 | 23 | # Step 3 24 | init <- init.net(i.num = 50) 25 | param <- param.net(inf.prob = 0.1, act.rate=5, rec.rate = .02) 26 | control <- control.net(type = "SIS", nsteps=500, nsims = 10, epi.by = "risk") 27 | 28 | sim1 <- netsim(est1, param, init, control) 29 | 30 | 31 | plot(sim1) 32 | summary(sim1, at = 500) 33 | 34 | plot(sim1, y = c("i.num.risk0", "i.num.risk1"), legend=TRUE) 35 | 36 | oldpar <- par(no.readonly = TRUE) 37 | par(mfrow=c(1, 2)) 38 | plot(sim1, type="network", at=1, col.status = TRUE) 39 | plot(sim1, type="network", at=500, col.status = TRUE) 40 | par(oldpar) 41 | -------------------------------------------------------------------------------- /playground/epimodel/epimodel_notes_cache/html/__packages: -------------------------------------------------------------------------------- 1 | base 2 | methods 3 | datasets 4 | utils 5 | grDevices 6 | graphics 7 | stats 8 | deSolve 9 | network 10 | networkDynamic 11 | statnet.common 12 | ergm 13 | tergm 14 | EpiModel 15 | sna 16 | -------------------------------------------------------------------------------- /playground/epimodel/epimodel_notes_cache/html/sim_e1d340f2c40d6e3e4ed9c7061e1757d2.RData: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/USCCANA/netdiffuseR/1efc0be4539d23ab800187c73551624834038e00/playground/epimodel/epimodel_notes_cache/html/sim_e1d340f2c40d6e3e4ed9c7061e1757d2.RData -------------------------------------------------------------------------------- /playground/epimodel/epimodel_notes_cache/html/sim_e1d340f2c40d6e3e4ed9c7061e1757d2.rdb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/USCCANA/netdiffuseR/1efc0be4539d23ab800187c73551624834038e00/playground/epimodel/epimodel_notes_cache/html/sim_e1d340f2c40d6e3e4ed9c7061e1757d2.rdb -------------------------------------------------------------------------------- /playground/epimodel/epimodel_notes_cache/html/sim_e1d340f2c40d6e3e4ed9c7061e1757d2.rdx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/USCCANA/netdiffuseR/1efc0be4539d23ab800187c73551624834038e00/playground/epimodel/epimodel_notes_cache/html/sim_e1d340f2c40d6e3e4ed9c7061e1757d2.rdx -------------------------------------------------------------------------------- /playground/epimodel/epimodel_notes_cache/markdown_github-ascii_identifiers/__packages: -------------------------------------------------------------------------------- 1 | base 2 | deSolve 3 | network 4 | networkDynamic 5 | statnet.common 6 | ergm 7 | tergm 8 | EpiModel 9 | sna 10 | -------------------------------------------------------------------------------- /playground/epimodel/epimodel_notes_cache/markdown_github-ascii_identifiers/sim_0ea3387c274ae47647171b010a6f0453.RData: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/USCCANA/netdiffuseR/1efc0be4539d23ab800187c73551624834038e00/playground/epimodel/epimodel_notes_cache/markdown_github-ascii_identifiers/sim_0ea3387c274ae47647171b010a6f0453.RData -------------------------------------------------------------------------------- /playground/epimodel/epimodel_notes_cache/markdown_github-ascii_identifiers/sim_0ea3387c274ae47647171b010a6f0453.rdb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/USCCANA/netdiffuseR/1efc0be4539d23ab800187c73551624834038e00/playground/epimodel/epimodel_notes_cache/markdown_github-ascii_identifiers/sim_0ea3387c274ae47647171b010a6f0453.rdb -------------------------------------------------------------------------------- /playground/epimodel/epimodel_notes_cache/markdown_github-ascii_identifiers/sim_0ea3387c274ae47647171b010a6f0453.rdx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/USCCANA/netdiffuseR/1efc0be4539d23ab800187c73551624834038e00/playground/epimodel/epimodel_notes_cache/markdown_github-ascii_identifiers/sim_0ea3387c274ae47647171b010a6f0453.rdx -------------------------------------------------------------------------------- /playground/exposure-ans-discussion.R: -------------------------------------------------------------------------------- 1 | # Set dimensions 2 | n <- 4 # Number of nodes 3 | t <- 3 # Number of time steps 4 | q <- 2 # Number of contagions 5 | 6 | 7 | # ORIGINAL: Graph -> n x n 8 | # attrs -> n x T 9 | # cumadopt-> n x T 10 | # ans -> n x T 11 | # 12 | # so (attrs * cumadopt) -> n x T 13 | # (graph %*% (attrs * cumadopt)) -> n x T 14 | # 15 | # normalization: as.vector(ans/( graph %*% attrs + 1e-20 )) 16 | # so (graph %*% attrs) -> n x T 17 | 18 | graph <- matrix(c(0, 1, 0, 0, 19 | 1, 0, 1, 0, 20 | 0, 1, 0, 1, 21 | 0, 0, 1, 0), nrow = n, byrow = TRUE) 22 | 23 | attrs <- matrix(c(1, 2, 3, 24 | 4, 5, 6, 25 | 7, 8, 9, 26 | 10,11,12), nrow = n) 27 | 28 | cumadopt <- array(c(1,2,3, 29 | 4,5,6, 30 | 7,8,9, 31 | 10,11,12), dim = c(n,t)) 32 | 33 | ans <- ( graph %*% (attrs * cumadopt) ) 34 | dim(ans) # n x t 35 | 36 | ans_norm <- ans/( graph %*% attrs + 1e-20 ) 37 | class(ans_norm) # "matrix" "array" 38 | dim(ans_norm) # n x t 39 | 40 | ans_norm_vec <- as.vector(ans/( graph %*% attrs + 1e-20 )) 41 | class(ans_norm_vec) # "numeric" 42 | dim(ans_norm_vec) # NULL, only a vector o length 4x3=12 43 | 44 | # NEW: Graph -> n x n 45 | # attrs -> n x T 46 | # cumadopt-> n x T x q 47 | # ans -> n x T x q 48 | # 49 | # so (graph %*% (attrs * cumadopt)) -> n x T x q 50 | # 51 | # normalization 52 | # so (graph %*% attrs) -> n x T 53 | 54 | 55 | cumadopt <- array(c(1,2,3, 56 | 4,5,6, 57 | 7,8,9, 58 | 10,11,12, 59 | # Second contagion 60 | 2,4,6, 61 | 8,10,12, 62 | 14,16,18, 63 | 20,22,24), dim = c(n,t,q)) 64 | 65 | # ANS 66 | 67 | ans <- apply(cumadopt, MARGIN=3, function(ca) graph %*% (attrs * ca)) 68 | ans <- array(ans, dim = c(n,t,q)) 69 | dim(ans) 70 | 71 | # NORMALIZATION 72 | 73 | den <- graph %*% attrs 74 | dim(den) 75 | 76 | ans/( graph %*% attrs + 1e-20 ) # Error 77 | 78 | # TRY THIS 79 | 80 | ans_norm <- apply(cumadopt, MARGIN=3, function(ca) graph %*% (attrs * ca) / ( graph %*% attrs + 1e-20 )) 81 | ans <- array(ans, dim = c(n,t,q)) 82 | dim(ans) 83 | 84 | # OR THIS 85 | 86 | 87 | 88 | ans <- array(0, dim = c(ncol(graph),dim(cumadopt)[2],dim(cumadopt)[3])) 89 | norm <- graph %*% attrs + 1e-20 90 | 91 | normalized <- TRUE 92 | 93 | for (k in seq_len(q)) { 94 | if (normalized) { 95 | ans[,,k] <- graph %*% (attrs * cumadopt[,,k]) / norm 96 | } else { 97 | ans[,,k] <- graph %*% (attrs * cumadopt[,,k]) 98 | } 99 | } 100 | 101 | as.vector(ans) 102 | 103 | 104 | ans 105 | dim(ans) 106 | -------------------------------------------------------------------------------- /playground/sna_sedist_function.R: -------------------------------------------------------------------------------- 1 | sedist<-function(dat,g=c(1:dim(dat)[1]),method="hamming",joint.analysis=FALSE,mode="digraph",diag=FALSE,code.diss=FALSE){ 2 | #First, prepare the data 3 | dat<-as.sociomatrix.sna(dat,simplify=TRUE) 4 | if(is.list(dat)) 5 | stop("sedist requires input graphs to be of identical order.") 6 | if(length(dim(dat))>2){ 7 | n<-dim(dat)[2] 8 | m<-length(g) 9 | d<-dat[g,,,drop=FALSE] 10 | }else{ 11 | n<-dim(dat)[2] 12 | m<-1 13 | d<-array(dim=c(m,n,n)) 14 | d[1,,]<-dat 15 | } 16 | if(!diag) 17 | d<-diag.remove(d) 18 | #Are we conducting a joint analysis? 19 | if(joint.analysis){ 20 | o<-array(dim=c(1,n,n)) 21 | #Build the data matrix 22 | v<-vector() 23 | for(i in 1:n) 24 | v<-cbind(v,c(as.vector(d[,i,]),as.vector(d[,,i]))) 25 | #Proceed by method 26 | if(method=="correlation"){ 27 | o[1,,]<-cor(v,use="pairwise") 28 | #Reverse code? 29 | if(code.diss) 30 | o<--o 31 | }else if(method=="euclidean"){ 32 | for(i in 1:n) 33 | for(j in 1:n) 34 | o[1,i,j]<-sqrt(sum((v[,i]-v[,j])^2,na.rm=TRUE)) 35 | }else if(method=="hamming"){ 36 | for(i in 1:n) 37 | for(j in 1:n) 38 | o[1,i,j]<-sum(abs(v[,i]-v[,j]),na.rm=TRUE) 39 | }else if(method=="gamma"){ 40 | for(i in 1:n) 41 | for(j in 1:n){ 42 | concord<-sum(as.numeric(v[,i]==v[,j]),na.rm=TRUE) 43 | discord<-sum(as.numeric(v[,i]!=v[,j]),na.rm=TRUE) 44 | o[1,i,j]<-(concord-discord)/(concord+discord) 45 | } 46 | #Reverse code? 47 | if(code.diss) 48 | o<--o 49 | }else if(method=="exact"){ 50 | for(i in 1:n) 51 | for(j in 1:n) 52 | o[1,i,j]<-as.numeric(any(v[!(is.na(v[,i])|is.na(v[,j])),i]!=v[!(is.na(v[,i])|is.na(v[,j])),j])) 53 | } 54 | }else{ #Analyze each graph seperately 55 | o<-array(dim=c(m,n,n)) 56 | for(k in 1:m){ 57 | #Build the data matrix 58 | v<-vector() 59 | for(i in 1:n) 60 | v<-cbind(v,c(as.vector(d[k,i,]),as.vector(d[k,,i]))) 61 | #Proceed by method 62 | if(method=="correlation"){ 63 | o[k,,]<-cor(v,use="pairwise") 64 | o[k,,][is.na(o[k,,])]<-0 65 | #Reverse code? 66 | if(code.diss) 67 | o[k,,]<--o[k,,] 68 | }else if(method=="euclidean"){ 69 | for(i in 1:n) 70 | for(j in 1:n) 71 | o[k,i,j]<-sqrt(sum((v[,i]-v[,j])^2,na.rm=TRUE)) 72 | }else if(method=="hamming"){ 73 | for(i in 1:n) 74 | for(j in 1:n) 75 | o[k,i,j]<-sum(abs(v[,i]-v[,j]),na.rm=TRUE) 76 | }else if(method=="gamma"){ 77 | for(i in 1:n) 78 | for(j in 1:n){ 79 | concord<-sum(as.numeric(v[,i]==v[,j]),na.rm=TRUE) 80 | discord<-sum(as.numeric(v[,i]!=v[,j]),na.rm=TRUE) 81 | o[k,i,j]<-(concord-discord)/(concord+discord) 82 | } 83 | #Reverse code? 84 | if(code.diss) 85 | o[k,,]<--o[k,,] 86 | }else if(method=="exact"){ 87 | for(i in 1:n) 88 | for(j in 1:n) 89 | o[k,i,j]<-as.numeric(any(v[!(is.na(v[,i])|is.na(v[,j])),i]!=v[!(is.na(v[,i])|is.na(v[,j])),j])) 90 | } 91 | } 92 | } 93 | #Dump the output 94 | if(dim(o)[1]==1) 95 | as.matrix(o[1,,]) 96 | else 97 | o 98 | } 99 | -------------------------------------------------------------------------------- /src/Makevars.in: -------------------------------------------------------------------------------- 1 | PKG_LIBS = $(LAPACK_LIBS) $(BLAS_LIBS) $(FLIBS) @OPENMP_CXXFLAGS@ 2 | 3 | # This is necesary since ARMADILLO now supports OpenMP 4 | PKG_CXXFLAGS=@OPENMP_CXXFLAGS@ -DARMA_64BIT_WORD -DSTRICT_R_HEADERS 5 | 6 | # For testing 7 | #PKG_CXXFLAGS=-Wall 8 | 9 | -------------------------------------------------------------------------------- /src/Makevars.win: -------------------------------------------------------------------------------- 1 | PKG_LIBS = $(LAPACK_LIBS) $(BLAS_LIBS) $(FLIBS) $(SHLIB_OPENMP_CXXFLAGS) 2 | # 1.2.4 Using C++11 code 3 | 4 | # This is necesary since ARMADILLO now supports OpenMP 5 | PKG_CXXFLAGS=$(SHLIB_OPENMP_CXXFLAGS) -DARMA_64BIT_WORD -DSTRICT_R_HEADERS 6 | 7 | # For testing 8 | #PKG_CXXFLAGS=-Wall 9 | 10 | -------------------------------------------------------------------------------- /src/adjmat.h: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * adjmat.h header function for adjmat.cpp 3 | *******************************************************************************/ 4 | // [[Rcpp::depends(RcppArmadillo)]] 5 | #include 6 | 7 | #ifndef NETDIFFUSER_ADJMAT_ 8 | #define NETDIFFUSER_ADJMAT_ 9 | 10 | using namespace Rcpp; 11 | 12 | 13 | arma::sp_mat edgelist_to_adjmat_cpp( 14 | const arma::mat & edgelist, 15 | NumericVector weights = NumericVector::create(), 16 | int n = 0, 17 | bool undirected = false, 18 | bool self = false, 19 | bool multiple = false 20 | ); 21 | 22 | arma::mat adjmat_to_edgelist_cpp( 23 | const arma::sp_mat & adjmat, 24 | bool undirected = true 25 | ); 26 | 27 | IntegerMatrix toa_diff_cpp( 28 | const IntegerVector & year 29 | ); 30 | 31 | 32 | List egonet_attrs_cpp( 33 | const arma::sp_mat & graph, 34 | const arma::uvec V, 35 | bool outer=true, 36 | bool self=true, 37 | bool valued=true 38 | ); 39 | 40 | arma::sp_umat approx_geodesicCpp( 41 | const arma::sp_mat & G, 42 | int n = 6, 43 | bool warn = false 44 | ); 45 | #endif 46 | -------------------------------------------------------------------------------- /src/infection.h: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * infection.h header function for infection.cpp 3 | *******************************************************************************/ 4 | // [[Rcpp::depends(RcppArmadillo)]] 5 | #include 6 | 7 | #ifndef NETDIFFUSER_INFECTSUSCEPT_ 8 | #define NETDIFFUSER_INFECTSUSCEPT_ 9 | 10 | using namespace Rcpp; 11 | 12 | arma::mat infection_cpp( 13 | List graph, 14 | const arma::colvec & times, 15 | bool normalize = true, 16 | int K = 1, 17 | double r = 0.5, 18 | bool expdiscount = false, 19 | int n=0, 20 | int T=0, 21 | bool valued=false, 22 | bool outgoing=true 23 | ); 24 | 25 | arma::mat susceptibility_cpp( 26 | List graph, 27 | const arma::colvec & times, 28 | bool normalize = true, 29 | int K = 1, 30 | double r = 0.5, 31 | bool expdiscount = false, 32 | int n=0, 33 | int T=0, 34 | bool valued=false, 35 | bool outgoing=true 36 | ); 37 | 38 | DataFrame select_egoalter_cpp( 39 | const arma::sp_mat & adjmat_t0, 40 | const arma::sp_mat & adjmat_t1, 41 | const NumericVector & adopt_t0, 42 | const NumericVector & adopt_t1 43 | ); 44 | 45 | 46 | #endif 47 | -------------------------------------------------------------------------------- /src/netdiffuser_extra.h: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * netdiffuser_extra.h header function for netdiffuser_extra.cpp 3 | *******************************************************************************/ 4 | // [[Rcpp::depends(RcppArmadillo)]] 5 | #include 6 | 7 | #ifndef NETDIFFUSER_EXTRA_ 8 | #define NETDIFFUSER_EXTRA_ 9 | 10 | using namespace Rcpp; 11 | 12 | arma::sp_mat sp_trimatl(const arma::sp_mat & x); 13 | 14 | int unif_rand_w_exclusion(int n, int e); 15 | 16 | arma::sp_mat sp_as_undirected(const arma::sp_mat & x); 17 | 18 | typedef double (*funcPtr)(double y0, double y1); 19 | 20 | double st_dist(double y0, double y1); 21 | double st_quaddist(double y0, double y1); 22 | double st_greater(double y0, double y1); 23 | double st_greaterequal(double y0, double y1); 24 | double st_smaller(double y0, double y1); 25 | double st_smallerequal(double y0, double y1); 26 | double st_equal(double y0, double y1); 27 | double st_min(double y0, double y1); 28 | double st_max(double y0, double y1); 29 | double st_mean(double y0, double y1); 30 | 31 | void st_getfun(std::string funname, funcPtr & fun); 32 | 33 | arma::sp_mat bootnet_fillself( 34 | arma::sp_mat & graph, const IntegerVector & index, const NumericVector & E 35 | ); 36 | 37 | #endif 38 | -------------------------------------------------------------------------------- /src/plot.h: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * plot.h header function for plot.cpp 3 | *******************************************************************************/ 4 | // [[Rcpp::depends(RcppArmadillo)]] 5 | #include 6 | 7 | #ifndef NETDIFFUSER_PLOT_ 8 | #define NETDIFFUSER_PLOT_ 9 | 10 | using namespace Rcpp; 11 | 12 | arma::vec seq_cpp(double from, double to, int lengthout); 13 | 14 | List grid_distribution(const arma::vec & x, const arma::vec & y, int nlevels=100); 15 | 16 | arma::mat edges_arrow( 17 | const double & x0, 18 | const double & y0, 19 | const double & x1, 20 | const double & y1, 21 | const double & height, 22 | const double & width, 23 | const double beta = 1.5707963267949, // PI/2 24 | NumericVector dev = NumericVector::create(), 25 | NumericVector ran = NumericVector::create() 26 | ); 27 | 28 | NumericMatrix edges_coords( 29 | const arma::sp_mat & graph, 30 | const arma::colvec & toa, 31 | const arma::colvec & x, 32 | const arma::colvec & y, 33 | const arma::colvec & vertex_cex, 34 | bool undirected=true, 35 | bool no_contemporary=true, 36 | NumericVector dev = NumericVector::create(), 37 | NumericVector ran = NumericVector::create() 38 | ); 39 | 40 | List vertices_coords( 41 | const arma::colvec & x, 42 | const arma::colvec & y, 43 | const arma::colvec & size, 44 | const arma::colvec & nsides, 45 | const arma::colvec & rot, 46 | NumericVector dev = NumericVector::create(), 47 | NumericVector ran = NumericVector::create() 48 | ); 49 | #endif 50 | -------------------------------------------------------------------------------- /src/rgraph.h: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * rgraph.h header function for rgraph.cpp: Functions for gerating random graphs 3 | * and rewiring graphs. 4 | *******************************************************************************/ 5 | 6 | // [[Rcpp::depends(RcppArmadillo)]] 7 | 8 | #include 9 | #ifndef NETDIFFUSER_RGRAPH_ 10 | #define NETDIFFUSER_RGRAPH_ 11 | using namespace Rcpp; 12 | 13 | arma::sp_mat rgraph_er_cpp( 14 | int n=10, 15 | double p = 0.3, 16 | bool undirected=true, 17 | bool weighted=false, 18 | bool self=false 19 | ); 20 | 21 | arma::sp_mat ring_lattice( 22 | int n, 23 | int k, 24 | bool undirected=true 25 | ); 26 | 27 | arma::sp_mat rewire_swap( 28 | const arma::sp_mat & graph, 29 | int nsteps=100, 30 | bool self=false, 31 | bool multiple=false, 32 | bool undirected=false, 33 | double pr_rewire=0.5 //,bool althexagons=false 34 | ); 35 | 36 | arma::sp_mat rewire_endpoints( 37 | const arma::sp_mat & graph, 38 | double p, 39 | bool both_ends=false, 40 | bool self=false, 41 | bool multiple=false, 42 | bool undirected=false 43 | ); 44 | 45 | arma::sp_mat permute_graph_cpp( 46 | const arma::sp_mat & x, 47 | bool self = false, 48 | bool multiple = false 49 | ); 50 | 51 | arma::sp_mat rgraph_ba_cpp( 52 | arma::sp_mat graph, 53 | arma::colvec dgr, 54 | int m = 1, 55 | int t = 10, 56 | bool self=true 57 | ); 58 | 59 | arma::sp_mat rgraph_ba_new_cpp( 60 | int m0 = 1, 61 | int m = 1, 62 | int t = 10, 63 | bool self=true 64 | ); 65 | 66 | arma::sp_mat rgraph_sf_homo( 67 | const arma::colvec & eta, 68 | const arma::sp_mat & graph, 69 | const arma::colvec & dgr, 70 | int m = 1, 71 | int t = 10, 72 | bool self=true 73 | ); 74 | 75 | arma::sp_mat rgraph_sf_homo_new( 76 | const arma::colvec & eta, 77 | int m0 = 1, 78 | int m = 1, 79 | int t = 10, 80 | bool self=true 81 | ); 82 | 83 | #endif 84 | -------------------------------------------------------------------------------- /src/stats.h: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * stats.hpp header function for stats.cpp 3 | *******************************************************************************/ 4 | // [[Rcpp::depends(RcppArmadillo)]] 5 | #include 6 | #ifndef NETDIFFUSER_STATS_ 7 | #define NETDIFFUSER_STATS_ 8 | using namespace Rcpp; 9 | 10 | arma::sp_mat vertex_covariate_dist( 11 | const arma::sp_mat & graph, 12 | const NumericMatrix & X, 13 | double p=2.0 14 | ); 15 | 16 | arma::sp_mat vertex_mahalanobis_dist_cpp( 17 | const arma::sp_mat & graph, 18 | const arma::mat & X, 19 | const arma::mat & W 20 | ); 21 | 22 | arma::sp_mat vertex_covariate_compare( 23 | const arma::sp_mat & graph, 24 | const NumericVector & X, 25 | std::string symbol 26 | ); 27 | 28 | List moran_cpp( 29 | const arma::colvec & x, 30 | const arma::sp_mat & w 31 | ); 32 | 33 | List struct_equiv_cpp( 34 | const arma::sp_mat & gdist, 35 | double v = 1.0 36 | ); 37 | #endif 38 | -------------------------------------------------------------------------------- /src/struct_test.h: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | * struct_test.h header function for struct_test.cpp 3 | *******************************************************************************/ 4 | #include 5 | using namespace Rcpp; 6 | 7 | 8 | #ifndef NETDIFFUSER_STRUCT_TEST_ 9 | #define NETDIFFUSER_STRUCT_TEST_ 10 | 11 | double struct_test_mean(NumericVector & y, std::string funname, bool self=false); 12 | double struct_test_var(NumericVector & y, std::string funname, bool self=false); 13 | NumericVector ego_variance(const arma::sp_mat & graph, const NumericVector & Y, 14 | std::string funname); 15 | // NumericVector hatf(const arma::sp_mat & G, const NumericVector & Y, 16 | // std::string funname); 17 | 18 | #endif 19 | -------------------------------------------------------------------------------- /tests/testthat.R: -------------------------------------------------------------------------------- 1 | library(testthat) 2 | library(netdiffuseR) 3 | 4 | Sys.setenv("R_TESTS" = "") 5 | 6 | test_check("netdiffuseR", reporter = "summary") 7 | -------------------------------------------------------------------------------- /tests/testthat/test-bass.r: -------------------------------------------------------------------------------- 1 | context("Bass Diffusion model") 2 | 3 | suppressWarnings(RNGversion("3.5.0")) 4 | set.seed(1122333) 5 | dat <- rdiffnet(200, 20) 6 | 7 | # ------------------------------------------------------------------------------ 8 | test_that("bass fits the right thing", { 9 | ans0 <- coef(fitbass(dat)) 10 | 11 | dat <- cumulative_adopt_count(dat)["prop",] 12 | Times <- 1:length(dat) 13 | 14 | # Objective function 15 | objf <- function(par, Times, dat) { 16 | sum((dat - bass_F(Times, par[1], par[2]))^2) 17 | } 18 | 19 | # Gradient of objf 20 | grad <- function(par, Times, dat) { 21 | g <- bass_dF(par[1], par[2], Times) 22 | val <- (bass_F(Times, par[1], par[2]) - dat) 23 | c(sum(g[1,]*val), sum(g[2,]*val)) 24 | } 25 | 26 | # Fitting using optim 27 | ans1 <- stats::optim( 28 | c(p = dat[1], q = .5), 29 | objf, grad, method="L-BFGS-B", lower = 1e-5, Times = Times, dat = dat 30 | )$par 31 | 32 | # Expectations 33 | expect_equal(unname(ans1), unname(ans0), tol = .001) 34 | }) 35 | 36 | test_that("diffnet_bass methods", { 37 | ans <- fitbass(dat) 38 | 39 | expect_silent(plot(ans)) 40 | expect_output(print(ans), "Nonlinear") 41 | }) 42 | -------------------------------------------------------------------------------- /tests/testthat/test-cumulative_adopt_count.R: -------------------------------------------------------------------------------- 1 | context("Cumulative adopt count, and hazard rate") 2 | 3 | # Generating the data ---------------------------------------------------------- 4 | 5 | # Common data 6 | set.seed(4912) 7 | toa <- sample(c(2001L:2005L, NA), 10, TRUE) 8 | nper <- max(toa, na.rm = TRUE) - min(toa, na.rm = TRUE) + 1 9 | graph <- lapply(1:nper, function(x) rgraph_ba(t=9)) 10 | 11 | # Creating a diffnet 12 | diffnet <- as_diffnet(graph, toa, undirected = TRUE) 13 | 14 | # Calculating numbers 15 | adopt <- toa_mat(toa) 16 | count <- cumulative_adopt_count(adopt$cumadopt) 17 | count_dn <- cumulative_adopt_count(diffnet) 18 | 19 | # Cumadopt --------------------------------------------------------------------- 20 | test_that("Cumulative adopters", { 21 | 22 | # Manual calculations 23 | count_hand <- sapply(diffnet$meta$pers, function(x) sum(!is.na(toa) & toa <= x)) 24 | count_hand <-rbind( 25 | count_hand, 26 | count_hand/length(toa) 27 | ) 28 | 29 | count_hand <- as.numeric(rbind( 30 | count_hand, 31 | c(0,(count_hand[1,2:nper] - count_hand[1,1:(nper-1)])/count_hand[1,1:(nper-1)]) 32 | )) 33 | 34 | expect_equal( 35 | as.numeric(count), count_hand, tolerance=getOption("diffnet.tol"), 36 | check.attributes=FALSE, scale=1, info="Using default") 37 | expect_equal( 38 | as.numeric(count_dn), count_hand, tolerance=getOption("diffnet.tol"), 39 | check.attributes=FALSE, scale=1, info="Using diffnet object") 40 | 41 | }) 42 | 43 | # Hazard rate ------------------------------------------------------------------ 44 | test_that("Hazard rate", { 45 | 46 | hr <- as.numeric(hazard_rate(adopt$cumadopt)) 47 | hr_dn <- as.numeric(hazard_rate(diffnet)) 48 | 49 | hr_hand <- as.numeric( 50 | c(0,(count[1,2:nper] - count[1,1:(nper-1)])/(length(toa) - count[1,1:(nper-1)]))) 51 | 52 | expect_equal(hr, hr_hand, tolerance=getOption("diffnet.tol"), scale=1) 53 | expect_equal(hr_dn, hr_hand, tolerance=getOption("diffnet.tol"), scale=1) 54 | }) 55 | -------------------------------------------------------------------------------- /tests/testthat/test-diffnet-indexing.R: -------------------------------------------------------------------------------- 1 | context("Checking diffnet-indexing") 2 | 3 | # Dynamic attributes ----------------------------------------------------------- 4 | 5 | test_that("Dynamic attributes assignment work", { 6 | # Preparing the data 7 | suppressWarnings(RNGversion("3.5.0")) 8 | set.seed(13213) 9 | x <- rdiffnet(20, 5) 10 | 11 | # Calculating exposure 12 | expoM <- exposure(x) 13 | expoL <- lapply(seq_len(x$meta$nper), function(x) expoM[,x,drop=FALSE]) 14 | expoD <- do.call(rbind, expoL) 15 | 16 | # Adding data 17 | x[["expoM"]] <- expoM 18 | x[["expoL"]] <- expoL 19 | x[["expoD"]] <- expoD 20 | 21 | # Checking 22 | eM <- x[["expoM"]] 23 | eL <- x[["expoL"]] 24 | eD <- x[["expoD"]] 25 | expect_equal(eM, eL) 26 | expect_equal(eL, eD) 27 | 28 | expect_error(x[["expoM"]] <- expoM[-1,], "incorrect size") 29 | expect_error(x[["expoM"]] <- {expoL[[2]] <- "a";expoL}, "Not all elements") 30 | 31 | # Removing data 32 | expect_warning(x[["davinci"]] <- NULL) 33 | ans0 <- x 34 | ans0[["real_threshold"]] <- NULL 35 | expect_error(ans0[["real_threshold"]], "No dynamic or static") 36 | 37 | ans0 <- x 38 | ans0[["expoM"]] <- NULL 39 | expect_error(ans0[["expoM"]], "No dynamic or static") 40 | 41 | 42 | }) 43 | 44 | # Slices of a diffnet object --------------------------------------------------- 45 | 46 | test_that("Getting slices", { 47 | suppressWarnings(RNGversion("3.5.0")) 48 | set.seed(5554) 49 | x <- rdiffnet(50,5) 50 | 51 | # Adding labels 52 | x <- as_diffnet(x$graph, toa = (2001:2005)[diffnet.toa(x)], t0=2001, t1=2005) 53 | 54 | # Subslices 55 | s_int <- 2L:4L 56 | s_log <- c(FALSE, TRUE, TRUE, TRUE, FALSE) 57 | s_lab <- as.character(2002:2004) 58 | 59 | # Should be equivalent 60 | expect_equal(x[,,s_int], x[,,s_log]) 61 | expect_equal(x[,,s_int], x[,,s_lab]) 62 | }) 63 | 64 | # Subsetting a diffnet object -------------------------------------------------- 65 | test_that("Subsetting diffnet objects", { 66 | # Generating the data 67 | suppressWarnings(RNGversion("3.5.0")) 68 | set.seed(101) 69 | graph <- rdiffnet(100, 10, seed.nodes = "central") 70 | 71 | # Testing i subset 72 | i <- sample.int(100, 50) 73 | j <- 3:8 74 | 75 | subg_i <- graph[i,] 76 | subg_j <- graph[,,j] 77 | 78 | expect_equal(subg_j[i,], subg_i[,,j], info = "The order doesn't matters") 79 | expect_equal(graph[i,,j], subg_i[,,j], info = "The order doesn't matters 2") 80 | expect_error(graph[,,c(1, 6:10)], "k- must represent a range") 81 | }) 82 | 83 | 84 | # Replacing values ------------------------------------------------------------- 85 | test_that("[<-.diffnet method", { 86 | suppressWarnings(RNGversion("3.5.0")) 87 | set.seed(1231) 88 | g <- rdiffnet(20, 3) 89 | 90 | ans0 <- g 91 | ans0$graph <- lapply(ans0$graph, function(x) {x[1,1] <- 10;x}) 92 | ans1 <- g 93 | ans1[1,1] <- 10 94 | 95 | expect_equal(ans0, ans1) 96 | 97 | ans0 <- g 98 | ans0$graph <- lapply(ans0$graph, function(x) {x[1,] <- 10;x}) 99 | ans1 <- g 100 | ans1[1,] <- 10 101 | 102 | expect_equal(ans0, ans1) 103 | 104 | ans0 <- g 105 | ans0$graph <- lapply(ans0$graph, function(x) {x[,1] <- 10;x}) 106 | ans1 <- g 107 | ans1[,1] <- 10 108 | 109 | expect_equal(ans0, ans1) 110 | 111 | ans0 <- g 112 | ans0$graph[[1]][,1] <- 10 113 | ans1 <- g 114 | ans1[,1,1] <- 10 115 | 116 | expect_equal(ans0, ans1) 117 | }) 118 | 119 | 120 | -------------------------------------------------------------------------------- /tests/testthat/test-egonets.R: -------------------------------------------------------------------------------- 1 | context("Egonets") 2 | 3 | test_that("Simple extraction throught clases", { 4 | set.seed(1931) 5 | # Generating data ---------- 6 | n <- 50 7 | t <- 10 8 | diffnet <- rdiffnet(50,10, seed.graph = "small-world") 9 | 10 | # Adding attributes 11 | 12 | # Dynamic 13 | diffnet[["unif"]] <- runif(n*t) 14 | diffnet[["bool"]] <- runif(n*t) > .5 15 | 16 | # Static 17 | diffnet[["d"]] <- rowMeans(dgr(diffnet)) 18 | diffnet[["threshold"]] <- threshold(diffnet) 19 | 20 | 21 | # Computing egonets 22 | en_diffnet_dn <- egonet_attrs(diffnet, fun=function(x) { 23 | sum(x[,"threshold"] * x[,"d"], na.rm=TRUE)/sum(x[,"d"], na.rm=TRUE) 24 | }) 25 | 26 | en_diffnet_ar <- egonet_attrs(as.array(diffnet), attrs=diffnet.attrs(diffnet), fun=function(x) { 27 | sum(x[,"threshold"] * x[,"d"], na.rm=TRUE)/sum(x[,"d"], na.rm=TRUE) 28 | }) 29 | 30 | en_list <- egonet_attrs(diffnet$graph, diffnet.attrs(diffnet), fun=function(x) { 31 | sum(x[,"threshold"] * x[,"d"], na.rm=TRUE)/sum(x[,"d"], na.rm=TRUE) 32 | }) 33 | 34 | expect_equal(en_diffnet_dn, en_diffnet_ar) 35 | expect_equal(en_diffnet_dn, en_list) 36 | 37 | en_dgCMatrix <- egonet_attrs( 38 | diffnet$graph[[1]], 39 | diffnet.attrs(diffnet)[[1]], 40 | fun=function(x) { 41 | sum(x[,"threshold"] * x[,"d"], na.rm=TRUE)/sum(x[,"d"], na.rm=TRUE) 42 | }) 43 | 44 | en_matrix <- egonet_attrs( 45 | as.matrix(diffnet$graph[[1]]), 46 | diffnet.attrs(diffnet)[[1]], 47 | fun=function(x) { 48 | sum(x[,"threshold"] * x[,"d"], na.rm=TRUE)/sum(x[,"d"], na.rm=TRUE) 49 | }) 50 | 51 | expect_equal(en_dgCMatrix, en_matrix) 52 | }) 53 | 54 | test_that("Error messages", { 55 | set.seed(1313131312) 56 | graph <- rdiffnet(100, 20) 57 | 58 | expect_error(egonet_attrs(graph, attrs=1), "must be a list") 59 | expect_error(egonet_attrs(graph, attrs=vector("list",18)), "as many elements as") 60 | expect_error(egonet_attrs(graph, attrs=vector("list", 20), V = -1), "out of range") 61 | expect_error(egonet_attrs(graph, attrs=vector("list", 20), V = NA), "is empty") 62 | }) 63 | -------------------------------------------------------------------------------- /tests/testthat/test-examples.R: -------------------------------------------------------------------------------- 1 | # context("Running examples") 2 | # 3 | # test_examples() 4 | -------------------------------------------------------------------------------- /tests/testthat/test-foreign.R: -------------------------------------------------------------------------------- 1 | context("Foreign function") 2 | 3 | test_that("igraph back and forth", { 4 | # Checking dynamic 5 | set.seed(1) 6 | dn0 <- rdiffnet(n=100, t=4) 7 | 8 | ig <- diffnet_to_igraph(dn0) 9 | dn1 <- igraph_to_diffnet(graph.list = ig, toavar="toa") 10 | 11 | attrs0 <- as.data.frame(dn0) 12 | attrs1 <- as.data.frame(dn1) 13 | 14 | dn1$vertex.static.attrs <- dn1$vertex.dyn.attrs[[1]] 15 | dn1$vertex.dyn.attrs <- NULL 16 | dn0$vertex.dyn.attrs <- NULL 17 | 18 | expect_equal(dn0, dn1) 19 | 20 | expect_equal(attrs0, attrs1) 21 | 22 | # CHecking static 23 | set.seed(2) 24 | dn0 <- rdiffnet(n=100, t=4, rewire = FALSE) 25 | ig <- diffnet_to_igraph(dn0) 26 | dn1 <- igraph_to_diffnet(ig[[1]], toavar="toa", t0 = 1, t1 = 4) 27 | 28 | attrs0 <- as.data.frame(dn0) 29 | attrs1 <- as.data.frame(dn1) 30 | 31 | expect_equal(dn0, dn1) 32 | 33 | expect_equal(attrs0, attrs1) 34 | }) 35 | 36 | 37 | test_that("network back and forth", { 38 | # Getting the data 39 | set.seed(1) 40 | dn0 <- rdiffnet(n=100, t=4) 41 | 42 | net <- diffnet_to_network(dn0) 43 | ndy <- diffnet_to_networkDynamic(dn0, netdyn.args = list(verbose=FALSE)) 44 | 45 | dn1 <- network_to_diffnet(graph.list = net, toavar="toa") 46 | dn2 <- networkDynamic_to_diffnet(ndy, toavar="toa") 47 | 48 | dn0$graph <- as.array(dn0) 49 | dn1$graph <- as.array(dn1) 50 | dn2$graph <- as.array(dn2) 51 | 52 | attrs0 <- as.data.frame(dn0) 53 | attrs1 <- as.data.frame(dn1) 54 | attrs2 <- as.data.frame(dn2) 55 | 56 | dn0$vertex.static.attrs <- NULL 57 | dn0$vertex.dyn.attrs <- NULL 58 | dn1$vertex.static.attrs <- NULL 59 | dn1$vertex.dyn.attrs <- NULL 60 | dn2$vertex.static.attrs <- NULL 61 | dn2$vertex.dyn.attrs <- NULL 62 | 63 | expect_equal(dn0, dn1) 64 | expect_equal(dn0, dn2) 65 | 66 | expect_equal(attrs0, attrs1[,colnames(attrs0)]) 67 | expect_equal(attrs0, attrs2[,colnames(attrs0)]) 68 | }) 69 | -------------------------------------------------------------------------------- /tests/testthat/test-formula.R: -------------------------------------------------------------------------------- 1 | context("Diffusion Regression") 2 | 3 | test_that("Errors and warnings", { 4 | 5 | data("medInnovationsDiffNet") 6 | expect_error(diffreg(~exposure), "not a `diffnet`") 7 | expect_error(diffreg(medInnovationsDiffNet~proage), "No `exposure`") 8 | 9 | expect_warning( 10 | diffreg(medInnovationsDiffNet~proage+exposure(lags = 0) + factor(per)), 11 | "not lagged" 12 | ) 13 | expect_warning( 14 | diffreg(medInnovationsDiffNet~proage+exposure), 15 | "naturally increases over time" 16 | ) 17 | 18 | 19 | }) 20 | -------------------------------------------------------------------------------- /tests/testthat/test-graph_data.R: -------------------------------------------------------------------------------- 1 | context("Graph objects") 2 | 3 | test_that("Checking that -graph- argument correctly passes", { 4 | 5 | # From the adjmat.R file ----------------------------------------------------- 6 | # expect_error(edgelist_to_adjmat(1), "No method for") 7 | # expect_error(edgelist_to_adjmat("a"), "No method for") 8 | expect_error(adjmat_to_edgelist(1), "No method for") 9 | expect_error(adjmat_to_edgelist("a"), "No method for") 10 | }) 11 | 12 | # ------------------------------------------------------------------------------ 13 | test_that("Graph class analysis", { 14 | # Generic error 15 | expect_error(classify_graph(1), "Not an object") 16 | 17 | # Static graphs 18 | expect_error(classify_graph(matrix(nrow = 0, ncol=0)), "Empty") 19 | expect_error(classify_graph(matrix(nrow = 2, ncol=1)), "square") 20 | expect_error(classify_graph(matrix(TRUE,nrow = 2, ncol=2)), "numeric") 21 | expect_output( print(classify_graph(matrix(1,nrow = 1, ncol=1))) , "static") 22 | 23 | # Dynamic graphs (simple) 24 | expect_error(classify_graph(array(dim = c(1,0,3))), "square") 25 | expect_error(classify_graph(array(dim = c(1,0,0))), "length 2") 26 | expect_error(classify_graph(array(TRUE,dim = c(1,1,2))), "numeric") 27 | 28 | # Dynamic graphs (complex) 29 | graph <- sapply(3:6,rgraph_ba) 30 | expect_error(classify_graph(graph), "dimensions .* slices .* equal") 31 | 32 | graph <- sapply(1:3,function(x) rgraph_ba()) 33 | expect_output( print(classify_graph(graph)) , "dynamic") 34 | 35 | graph <- array(unlist(lapply(graph, as.matrix)), dim=c(11,11,3)) 36 | expect_output( print(classify_graph(graph)) , "dynamic") 37 | 38 | } 39 | ) 40 | 41 | # ------------------------------------------------------------------------------ 42 | test_that("As generic graph", { 43 | 44 | g <- rgraph_ba(t=19) 45 | 46 | # igraph case 47 | ig <- igraph::graph_from_adjacency_matrix(g) 48 | ans0 <- netdiffuseR:::as_generic_graph.igraph(ig) 49 | expect_equal(igraph::as_adj(ig), ans0$graph[[1]]) 50 | 51 | # network case 52 | nw <- network::network(as.matrix(g), loops=TRUE) 53 | ans1 <- netdiffuseR:::as_generic_graph.network(nw) 54 | # ans1 <- as.matrix(ans1$graph[[1]]) 55 | 56 | expect_equivalent(as.matrix(nw), as.matrix(ans1$graph[[1]])) 57 | }) 58 | -------------------------------------------------------------------------------- /tests/testthat/test-imports.R: -------------------------------------------------------------------------------- 1 | context("Silly tests for imports.R") 2 | 3 | test_that("release_questions", { 4 | expect_equal(length(netdiffuseR:::release_questions()), 4L) 5 | }) 6 | -------------------------------------------------------------------------------- /tests/testthat/test-infect_suscept.R: -------------------------------------------------------------------------------- 1 | context("Infection and susceptibility") 2 | 3 | ################################################################################ 4 | # Susceptibility tests 5 | ################################################################################ 6 | 7 | test_that("Numeric tests of Susceptibility", { 8 | # Preparing data ------------------------------------------------------------- 9 | graph <- array(0,dim=c(5,5,4), dimnames = list(1:5,1:5,1:4)) 10 | graph[5,1:4,] <- 1 11 | times <- c(1, 4, 1, 2, 3) 12 | 13 | graphl <- lapply(1:4, function(x) methods::as(graph[,,x], "dgCMatrix")) 14 | names(graphl) <- 1:4 15 | 16 | gl <- list(`Array`=graph, `List`=graphl) 17 | 18 | for(i in names(gl)) { 19 | # K=1 ------------------------------------------------------------------------ 20 | suscep <- netdiffuseR::susceptibility(gl[[i]], times, normalize = FALSE)[5,1] 21 | expect_equal(suscep, 1/3, scale=1, tol=getOption("diffnet.tol"), info=i) 22 | 23 | # K=2 ------------------------------------------------------------------------ 24 | suscep <- netdiffuseR::susceptibility(gl[[i]], times, K = 2, normalize=FALSE)[5,1] 25 | expect_equal(suscep, 2/4, scale=1, tol=getOption("diffnet.tol"), info=i) 26 | 27 | # K=1 exponential r=.1-------------------------------------------------------- 28 | suscep <- netdiffuseR::susceptibility(gl[[i]], times, normalize = FALSE, 29 | r=.1, expdiscount = TRUE)[5,1] 30 | expect_equal(suscep, 1/3, scale=1, tol=getOption("diffnet.tol"), info=i) 31 | 32 | # K=2 exponential r=.1-------------------------------------------------------- 33 | bmark <- (1/1 + 2/(1.1))/(3/1 + 2/(1.1)) 34 | suscep <- netdiffuseR::susceptibility(gl[[i]], times, K = 2, normalize=FALSE, 35 | r=.1, expdiscount = TRUE)[5,1] 36 | expect_equal(suscep, bmark, scale=1, tol=getOption("diffnet.tol"), info=i) 37 | } 38 | } 39 | ) 40 | 41 | 42 | 43 | ################################################################################ 44 | # Infection tests 45 | ################################################################################ 46 | test_that("Numeric tests of Susceptibility", { 47 | # Preparing data ------------------------------------------------------------- 48 | graph <- array(0,dim=c(5,5,4), dimnames = list(1:5,1:5,1:4)) 49 | graph[2:5,1,] <- 1 50 | times <- c(1, 4, 2, 3, 3) +1 51 | times[2] <- 1 52 | 53 | graphl <- lapply(1:4, function(x) methods::as(graph[,,x], "dgCMatrix")) 54 | names(graphl) <- 1:4 55 | 56 | gl <- list(`Array`=graph, `List`=graphl) 57 | 58 | for(i in names(gl)) { 59 | # K=1 ------------------------------------------------------------------------ 60 | infect <- netdiffuseR::infection(gl[[i]], times, normalize = FALSE) 61 | expect_equal(infect[1,1], 1/3, scale=1, tol=getOption("diffnet.tol"), info=i) 62 | 63 | # K=2 ------------------------------------------------------------------------ 64 | infect <- netdiffuseR::infection(gl[[i]], times, normalize = FALSE, K=2) 65 | expect_equal(infect[1,1], 1/2, scale=1, tol=getOption("diffnet.tol"), info=i) 66 | 67 | # K=1 exponential r=.1-------------------------------------------------------- 68 | infect <- netdiffuseR::infection(gl[[i]], times, normalize = FALSE, 69 | r=.1, expdiscount = TRUE) 70 | expect_equal(infect[1,1], 1/3, scale=1, tol=getOption("diffnet.tol"), info=i) 71 | 72 | # K=2 exponential r=.1-------------------------------------------------------- 73 | bmark <- (1/1 + 2/(1.1))/(3/1 + 2/(1.1)) 74 | infect <- netdiffuseR::infection(gl[[i]], times, K = 2, normalize=FALSE, 75 | r=.1, expdiscount = TRUE) 76 | expect_equal(infect[1,1], bmark, scale=1, tol=getOption("diffnet.tol"), info=i) 77 | } 78 | } 79 | ) 80 | -------------------------------------------------------------------------------- /tests/testthat/test-mentor.r: -------------------------------------------------------------------------------- 1 | context("Mentor matching") 2 | 3 | # ------------------------------------------------------------------------------ 4 | test_that("Mentor matching", { 5 | set.seed(1) 6 | 7 | g <- igraph::make_graph(~1--2,1--3,1--4,4--5,6) 8 | g <- igraph::as_adj(g) 9 | 10 | ans <- mentor_matching(g, 2) 11 | expect_equal(sort(unique(ans$match)), as.character(c(1,4))) 12 | }) 13 | 14 | 15 | # ------------------------------------------------------------------------------ 16 | test_that("Plot mentor", { 17 | set.seed(1) 18 | 19 | g <- igraph::make_graph(~1--2,1--3,1--4,4--5,6) 20 | g <- igraph::as_adj(g) 21 | ans <- mentor_matching(g, 2) 22 | 23 | expect_silent(plot(ans)) 24 | }) 25 | -------------------------------------------------------------------------------- /tests/testthat/test-misc.R: -------------------------------------------------------------------------------- 1 | context("Misc functions") 2 | 3 | # ------------------------------------------------------------------------------ 4 | test_that("The recode function for data.frame works", { 5 | edgelist <- data.frame( 6 | ego = c(1, 10, 8), 7 | alter = c(10, 2, 1), stringsAsFactors = FALSE 8 | ) 9 | 10 | expected_edgelist <- data.frame( 11 | ego = c(1, 2, 4), 12 | alter = c(2, 3, 1), stringsAsFactors = FALSE 13 | ) 14 | 15 | expect_equivalent(recode(edgelist), expected_edgelist) 16 | }) 17 | 18 | 19 | # ------------------------------------------------------------------------------ 20 | test_that("as_dgCMatrix works", { 21 | set.seed(1231) 22 | x <- rgraph_er(10) 23 | 24 | # From matrix object 25 | ans_mat <- as_dgCMatrix(as.matrix(x)) 26 | 27 | # From a network object 28 | ans_net <- as_dgCMatrix(network::as.network(as.matrix(x))) 29 | 30 | # From igraph object 31 | ans_ig <- as_dgCMatrix(igraph::graph_from_adjacency_matrix(x)) 32 | 33 | expect_equivalent(ans_mat, ans_net) 34 | expect_equivalent(ans_mat, ans_ig) 35 | 36 | expect_is(as_dgCMatrix(medInnovationsDiffNet), "list") 37 | expect_s4_class(as_dgCMatrix(medInnovationsDiffNet)[[1]], "dgCMatrix") 38 | 39 | # From array 40 | myarray <- array(dim=c(10,10,2)) 41 | myarray[,,1] <- as.matrix(x) 42 | myarray[,,2] <- as.matrix(x) 43 | 44 | expect_is(as_dgCMatrix(myarray), "list") 45 | expect_s4_class(as_dgCMatrix(myarray)[[1]], "dgCMatrix") 46 | }) 47 | -------------------------------------------------------------------------------- /tests/testthat/test-moran.r: -------------------------------------------------------------------------------- 1 | context("Morans I") 2 | 3 | test_that("Get the same result as in ape", { 4 | set.seed(123) 5 | graph <- rgraph_ba(t = 199) 6 | w <- approx_geodesic(graph) 7 | x <- rnorm(200) 8 | 9 | # Computing Moran's I 10 | ans0 <- moran(x, w) 11 | 12 | # Comparing with the ape's package version 13 | ans1 <- ape::Moran.I(x, as.matrix(w)) 14 | 15 | expect_equivalent(unclass(ans0), unclass(ans1)) 16 | }) 17 | # 18 | # graphm <- as.matrix(graph) 19 | # microbenchmark::microbenchmark( 20 | # netdiffuseR::moran(x,graph), 21 | # ape::Moran.I(x, graphm), times = 100, 22 | # unit="relative" 23 | # ) 24 | -------------------------------------------------------------------------------- /tests/testthat/test-netdiffuser_extra.R: -------------------------------------------------------------------------------- 1 | context("C++ extra functions") 2 | 3 | # ------------------------------------------------------------------------------ 4 | test_that("sp_trimatl", { 5 | x <- ring_lattice(10,4, undirected = TRUE) 6 | ans <- netdiffuseR:::sp_trimatl(x) 7 | expect_equal(ans + t(ans), x) 8 | }) 9 | 10 | # ------------------------------------------------------------------------------ 11 | test_that("sp_diag", { 12 | x <- methods::as(diag(1,10,10), "dgCMatrix") 13 | ans1 <- netdiffuseR:::sp_diag(x,1:10) 14 | ans2 <- x 15 | Matrix::diag(ans2) <- 1:10 16 | expect_equal(ans1, ans2) 17 | }) 18 | 19 | # ------------------------------------------------------------------------------ 20 | test_that("sp_as_undirected", { 21 | set.seed(123131312) 22 | ans0 <- rgraph_ba(t=9,m=3) 23 | ans1 <- netdiffuseR:::sp_as_undirected(ans0) 24 | ans0 <- ans0 + t(ans0) 25 | Matrix::diag(ans0) <- Matrix::diag(ans0)/2 26 | 27 | expect_equivalent(ans1, ans0) 28 | 29 | }) 30 | -------------------------------------------------------------------------------- /tests/testthat/test-options.R: -------------------------------------------------------------------------------- 1 | context("Testing package .onLoad and options") 2 | test_that("There should be diffnet options", { 3 | netdiffuseR:::.onLoad() 4 | expect_is(getOption("diffnet.self"), "logical") 5 | expect_is(getOption("diffnet.undirected"), "logical") 6 | expect_is(getOption("diffnet.multiple"), "logical") 7 | expect_is(getOption("diffnet.tol"), "numeric") 8 | }) 9 | -------------------------------------------------------------------------------- /tests/testthat/test-plot_diffnet2.R: -------------------------------------------------------------------------------- 1 | context("Set of functions used in: plot_diffnet2") 2 | 3 | # ------------------------------------------------------------------------------ 4 | test_that("round_to_seq", { 5 | set.seed(12313) 6 | 7 | # Respect the lenght 8 | x <- runif(1000, 0,100) 9 | x_r <- round_to_seq(x, nlevels = 30) 10 | expect_equal(30L, length(unique(x_r))) 11 | }) 12 | 13 | # ------------------------------------------------------------------------------ 14 | test_that("methods of plot_diffnet2", { 15 | set.seed(11222) 16 | dn <- rdiffnet(100, 5) 17 | 18 | # Should get the same outputs 19 | set.seed(1);ans_dn <- plot_diffnet2(dn) 20 | set.seed(1);ans_gp <- plot_diffnet2(dn$graph[[nslices(dn)]], dn$toa) 21 | expect_equal(ans_dn, ans_gp) 22 | 23 | }) 24 | 25 | # ------------------------------------------------------------------------------ 26 | test_that("methods of diffMap", { 27 | set.seed(11445) 28 | dn <- rdiffnet(50, 5, seed.nodes = "central") 29 | 30 | # Should get the same outputs 31 | set.seed(1); ans_dn <- diffmap(dn) 32 | set.seed(1); ans_gp <- diffmap(dn$graph[[nslices(dn)]], dn$toa) 33 | expect_equal(ans_dn, ans_gp) 34 | 35 | set.seed(123);ans0 <- plot_diffnet2(dn, add.map = "last", layout = ans_gp$coords) 36 | set.seed(123);ans1 <- diffmap(dn, layout=igraph::norm_coords(ans_gp$coords)) 37 | 38 | # Should be the same as adding the map after 39 | expect_equal(ans0$diffmap, ans1) 40 | expect_output(print(ans1), "of class.+diffmap") 41 | expect_output(print(ans1), "of class.+diffmap") 42 | expect_silent(image(ans1)) 43 | expect_silent(plot(ans1)) 44 | }) 45 | 46 | 47 | -------------------------------------------------------------------------------- /tests/testthat/test-read_write_foreign.R: -------------------------------------------------------------------------------- 1 | context("Read/write foreign formats") 2 | 3 | test_that("Pajek files", { 4 | # Reading sampson data 5 | path <- system.file("extdata", "SAMPSON.NET", package = "netdiffuseR") 6 | SAMPSON <- read_pajek(path) 7 | 8 | g <- edgelist_to_adjmat(SAMPSON$edges[[1]][,1:2], SAMPSON$edges[[1]][,3], 9 | recode.ids = FALSE, multiple = FALSE) 10 | for (i in 2:length(SAMPSON$edges)) 11 | g <- g + edgelist_to_adjmat(SAMPSON$edges[[i]][,1:2], 12 | SAMPSON$edges[[i]][,3], 13 | recode.ids = FALSE, multiple = FALSE) 14 | 15 | ans0 <- dgr(g, valued = TRUE) 16 | path <- system.file("extdata", "SAMPSON_W_DEGREE.vec", package="netdiffuseR") 17 | ans1 <- as.numeric(readLines(path)[-1]) 18 | 19 | # Comparing against what pajek says 20 | expect_equivalent(as.numeric(ans0),ans1) 21 | 22 | 23 | }) 24 | 25 | # ------------------------------------------------------------------------------ 26 | test_that("DL files", { 27 | # Reading sampson data 28 | path <- system.file("extdata", "SAMPSON.DAT", package = "netdiffuseR") 29 | SAMPSON <- read_ml(path) 30 | 31 | ans0 <- dgr(SAMPSON$adjmat, valued = TRUE) 32 | ans0 <- rowSums(ans0) 33 | 34 | path <- system.file("extdata", "SAMPSON_W_DEGREE.vec", package="netdiffuseR") 35 | ans1 <- as.numeric(readLines(path)[-1]) 36 | 37 | # Comparing against what pajek says 38 | expect_equivalent(as.numeric(ans0),ans1) 39 | }) 40 | 41 | # ------------------------------------------------------------------------------ 42 | # test_that("UCINET files", { 43 | # # Reading sampson data 44 | # path <- system.file("extdata", "sampson.##d", package = "netdiffuseR") 45 | # SAMPSON <- read_ucinet(path)ans0 <- dgr(SAMPSON$adjmat, valued = TRUE) 46 | # ans0 <- rowSums(ans0) 47 | # 48 | # path <- system.file("extdata", "SAMPSON_W_DEGREE.vec", package="netdiffuseR") 49 | # ans1 <- as.numeric(readLines(path)[-1]) 50 | # 51 | # # Comparing against what pajek says 52 | # expect_equivalent(as.numeric(ans0),ans1) 53 | # }) 54 | -------------------------------------------------------------------------------- /tests/testthat/test-select_egoalter.R: -------------------------------------------------------------------------------- 1 | context("Select ego/alter") 2 | 3 | test_that("Simple example", { 4 | 5 | # Creating graph 6 | g <- matrix(0, ncol=3, nrow=3) 7 | g[cbind(1,2:3)] <- 1 8 | g[cbind(2:3,1)] <- 1 9 | g[2,3] <- 1 10 | g[3,2] <- 1 11 | 12 | g <- lapply(1:4, function(x) methods::as(g, "dgCMatrix")) 13 | 14 | # Checking error 15 | expect_error(select_egoalter(g), "provided when") 16 | 17 | # Cumultive adoption matrix 18 | cumadopt <- matrix(0,ncol=4, nrow=3) 19 | cumadopt[1,1:3] <- 1 20 | cumadopt[2,2:4] <- 1 21 | cumadopt[3,3:4] <- 1 22 | 23 | 24 | ans <- adopt_changes(g, cumadopt) 25 | # class(ans) <- c("diffnet_adoptChanges", "data.frame") 26 | 27 | # Only over unchanged 28 | ans2 <- summary(ans)$`unchanged (s)` 29 | expect_equivalent(sapply(ans2, sum), rep(6,3)) 30 | 31 | # Matrices calculated manually 32 | per2 <- matrix(0, ncol=4, nrow=4) 33 | per2[rbind(c(1,2),c(1,4),c(2,1), c(2,4), c(4,1), c(4,2))] <- 1 34 | 35 | per3 <- matrix(0, ncol=4, nrow=4) 36 | per3[rbind(c(2,4), c(4,2), c(4,4))] <- 2 37 | 38 | per4 <- matrix(0, ncol=4, nrow=4) 39 | per4[rbind(c(3,4), c(4,3), c(4,4))] <- 2 40 | 41 | 42 | expect_equivalent(ans2, list(per2, per3, per4)) 43 | 44 | 45 | # Should be equivalent 46 | g <- lapply(g, as.matrix) 47 | g_array <- array(unlist(g), dim=c(3,3,4)) 48 | 49 | ans <- adopt_changes(g_array, cumadopt) 50 | ans3 <- summary(ans)$`unchanged (s)` 51 | 52 | expect_equal(ans2, ans3) 53 | 54 | }) 55 | -------------------------------------------------------------------------------- /tests/testthat/test-spatial.R: -------------------------------------------------------------------------------- 1 | context("Spatial functions (beta)") 2 | 3 | test_that("diag expansion", { 4 | set.seed(1231) 5 | dn <- rdiffnet(n = 100, t = 5) 6 | 7 | ans1 <- diag_expand(dn) 8 | ans2 <- diag_expand(dn$graph, self = is_self(dn)) 9 | 10 | # Checking methods 11 | expect_equal(ans1,ans2) 12 | 13 | # Checking attributes 14 | expect_equal(dim(ans1), c(500L,500L)) 15 | expect_equal(nlinks(ans1), sum(unlist(nlinks(dn)))) 16 | 17 | }) 18 | -------------------------------------------------------------------------------- /vignettes/large-simulation.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Vignette Title" 3 | author: "Vignette Author" 4 | date: "`r Sys.Date()`" 5 | output: rmarkdown::html_vignette 6 | vignette: > 7 | %\VignetteIndexEntry{Vignette Title} 8 | %\VignetteEngine{knitr::rmarkdown} 9 | %\VignetteEncoding{UTF-8} 10 | --- 11 | 12 | ```{r setup, include = FALSE} 13 | knitr::opts_chunk$set( 14 | collapse = TRUE, 15 | comment = "#>" 16 | ) 17 | ``` 18 | 19 | # Preliminaries 20 | 21 | We are interested in running a large scale simulation featuring hundreds of thousands (if not millions) of vertices. Before we proceed, you need to consider the following: 22 | 23 | 1. Networks in netdiffuseR are sparse-matrices, thus, as long as the network is sparsely connected, it will fit in a regular computer. 24 | 2. At the same time, converting a sparse-matrix into a dense matrix at this scale **is not a good idea**, as you computer may crash. This would be the case, for example, if you want to calculate the geodesic matrix. 25 | 3. Following the previous point, using `summary(..., skip.moran = FALSE)`--the default behavior--is not a good idea. When dealing with large graphs, set `skip.moran = TRUE` to avoid memory overflow. 26 | 27 | # Case 1: Single simulation 28 | 29 | Suppose we want to simulate a diffusion process with the following parameters: 30 | 31 | - Network type: Small world with parameters $n=200k, k = 10, p = .1$ 32 | 33 | ```{r setp-1, eval=FALSE} 34 | library(netdiffuseR) 35 | ``` 36 | 37 | We no proceed with the simulation 38 | 39 | ```{r sim-1, eval=FALSE} 40 | ans_sw <- rdiffnet(n = 200, t = 10) 41 | ``` 42 | 43 | 44 | 45 | -------------------------------------------------------------------------------- /vignettes/rdiffnets.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: "A simple simulation example" 3 | author: "George G Vega Yon" 4 | date: "February 25, 2019" 5 | output: rmarkdown::html_vignette 6 | header-includes: \usepackage{graphicx} 7 | vignette: > 8 | %\VignetteIndexEntry{A simple rdiffnet example} 9 | %\VignetteEngine{knitr::rmarkdown} 10 | %\usepackage[utf8]{inputenc} 11 | --- 12 | 13 | ```{r setup, include=FALSE} 14 | knitr::opts_chunk$set(echo = TRUE) 15 | ``` 16 | 17 | ## R Markdown 18 | 19 | ## Step 1: Loading the packages 20 | 21 | ```{r loading, message=FALSE, warning=FALSE} 22 | library(netdiffuseR) 23 | library(sna) 24 | ``` 25 | 26 | ## Step 2: Random network (for input) 27 | 28 | ```{r random-net} 29 | set.seed(8826) 30 | 31 | # Simulating a small world (10, 3) with pr = .3 32 | net <- rgraph_ws(50, 3, .3) 33 | 34 | # A bit more of rewiring 35 | net <- rewire_graph(net, p=3, both.ends = TRUE) 36 | ``` 37 | 38 | Taking a look at it using sna 39 | 40 | ```{r viz} 41 | 42 | # Visualizing with 43 | gplot(as.matrix(net)) 44 | ``` 45 | 46 | ```{r diffnet} 47 | # Random diffusion with a fixed threshold of 1, simulating 5 time points 48 | mydiffnet <- rdiffnet( 49 | seed.graph = net, # The network we just created 50 | threshold.dist = 1, # Fixed threshold of 1 51 | t = 5, # 5 time points 52 | rewire = FALSE, # No rewire (defaults TRUE) 53 | exposure.args = list(normalized=FALSE), # Exposure to be computed unnormalized 54 | # so we use counts instead 55 | seed.nodes = "random" # Random set of initial adopters 56 | ) 57 | 58 | # Looking at the diffusion process 59 | plot_diffnet(mydiffnet) 60 | 61 | # Some summary stats 62 | summary(mydiffnet) 63 | ``` 64 | 65 | We can actually go further and run multiple simulations instead so that we can 66 | get a confidence interval in the proportion of adopters 67 | 68 | ```{r diffnet-multiple, warning=FALSE} 69 | set.seed(871) 70 | mydiffnet <- rdiffnet_multiple( 71 | statistic = function(n) cumulative_adopt_count(n)["prop",], 72 | R = 1000, 73 | stop.no.diff = FALSE, # This option allows us to continue 74 | # The simulation process, even if there 75 | # is no adoption. 76 | seed.graph = net, # The network we just created 77 | threshold.dist = 1, # Fixed threshold of 1 78 | t = 5, # 5 time points 79 | rewire = FALSE, # No rewire (defaults TRUE) 80 | exposure.args = list(normalized=FALSE), # Exposure to be computed unnormalized 81 | # so we use counts instead 82 | seed.nodes = "random" # Random set of initial adopters 83 | ) 84 | 85 | # Looking at the diffusion process 86 | boxplot( 87 | t(mydiffnet), 88 | xlab = "Time", 89 | ylab = "Proportion of Adopters", 90 | main = "Simulation of 1,000 diffusion processes" 91 | ) 92 | ``` 93 | 94 | -------------------------------------------------------------------------------- /vignettes/time_discount_suscep_infect.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Time Discounted Infection and Susceptibility" 3 | author: "George G. Vega Yon" 4 | date: "November 11, 2015" 5 | output: rmarkdown::html_vignette 6 | fontsize: 12pt 7 | vignette: > 8 | %\VignetteIndexEntry{Time Discounted Infection and Susceptibility} 9 | %\VignetteEngine{knitr::rmarkdown} 10 | \usepackage[utf8]{inputenc} 11 | --- 12 | 13 | In Myers (2000), susceptibility and infection is defined for a given time period and as a constant throughout the network--so only varies on $t$. In order to include effects from previous/coming time periods, it adds up through the \emph{severity} of the rioting, which in our case would be strength of tie, hence a dichotomous variable, whenever the event occurred a week within $t$, furthermore, he then introduces a discount factor in order to account for decay of the influence of the event. Finally, he obtains 14 | 15 | $$ 16 | V_{(t)} = \sum_{a\in \mathbf{A}(t)} \frac{S_{(a)}m_{T(a), T\leq t-T(a)}}{t- T(a)} 17 | $$ 18 | 19 | where $\mathbf{A}(t)$ is the set of all riots that occurred by time $t$, $S_{(a)}$ is the severity of the riot $a$, $T(a)$ is the time period by when the riot $a$ accurred and $m$ is an indicator function. 20 | 21 | In order to include this notion in our equations, I modify these by also adding whether a link existed between $i$ and $j$ at the corresponding time period. Furthermore, in a more general way, the time windown is now a function of the number of time periods to include, $K$, this way, instead of looking at time periods $t$ and $t+1$ for infection, we look at the time range between $t$ and $t + K$. 22 | 23 | # Infectiousness 24 | 25 | Following the paper's notation, a more generalized formula for infectiousness is 26 | 27 | $$\label{eq:infect-dec} 28 | \left( 29 | \sum_{k=1}^K\sum_{j\neq i} \frac{x_{ji(t+k-1)}z_{j(t+k)}}{k} 30 | \right)\left( 31 | \sum_{k=1}^K\sum_{j\neq i} \frac{x_{ji(t+k-1)}z_{j([t+k;T])}}{k} 32 | \right)^{-1} 33 | $$ 34 | 35 | \noindent Where $\frac{1}{k}$ would be the equivalent of $\frac{1}{t - T(a)}$ in mayers. Alternatively, we can include a discount factor as follows 36 | 37 | $$\label{eq:infect-exp} 38 | \left( 39 | \sum_{k=1}^K\sum_{j\neq i} \frac{x_{ji(t+k-1)}z_{j(t+k)}}{(1+r)^{k-1}} 40 | \right)\left( 41 | \sum_{k=1}^K\sum_{j\neq i} \frac{x_{ji(t+k-1)}z_{j([t+k;T])}}{(1+r)^{k-1}} 42 | \right)^{-1} 43 | $$ 44 | 45 | Observe that when $K=1$, this formula turns out to be the same as the paper. 46 | 47 | 48 | # Susceptibility 49 | 50 | Likewise, a more generalized formula of susceptibility is 51 | 52 | $$\label{eq:suscept-dec} 53 | \left( 54 | \sum_{k=1}^K\sum_{j\neq i} \frac{x_{ij(t-k+1)}z_{j(t-k)}}{k} 55 | \right)\left( 56 | \sum_{k=1}^K\sum_{j\neq i} \frac{x_{ij(t-k+1)}z_{j([1;t-k])}}{k} 57 | \right)^{-1} 58 | $$ 59 | 60 | \noindent Which can also may include an alternative discount factor 61 | 62 | $$\label{eq:suscept-exp} 63 | \left( 64 | \sum_{k=1}^K\sum_{j\neq i} \frac{x_{ij(t-k+1)}z_{j(t-k)}}{(1+r)^{k-1}} 65 | \right)\left( 66 | \sum_{k=1}^K\sum_{j\neq i} \frac{x_{ij(t-k+1)}z_{j([1;t-k])}}{(1+r)^{k-1}} 67 | \right)^{-1} 68 | $$ 69 | 70 | Also equal to the original equation when $K=1$. Furthermore, the resulting statistic will lie between 0 and 1, been the later whenever $i$ acquired the innovation lastly and right after $j$ acquired it, been $j$ its only alter. 71 | 72 | (PENDING: Normalization of the stats) 73 | --------------------------------------------------------------------------------