├── .Rbuildignore ├── .github ├── .gitignore └── workflows │ └── pkgdown.yaml ├── .gitignore ├── DESCRIPTION ├── LICENSE.md ├── NAMESPACE ├── NEWS.md ├── R ├── RcppExports.R ├── download_rates.R ├── estimate_rates.R ├── prepare_initial_population.R ├── read_results.R ├── retrieve_kin.R ├── rsocsim.R └── startsocsim.R ├── README.md ├── _pkgdown.yml ├── development.md ├── docs ├── 404.html ├── authors.html ├── bootstrap-toc.css ├── bootstrap-toc.js ├── docsearch.css ├── docsearch.js ├── index.html ├── link.svg ├── pkgdown.css ├── pkgdown.js ├── pkgdown.yml ├── readme.html ├── reference │ ├── Rplot001.png │ ├── create_simulation_folder.html │ ├── create_sup_file.html │ ├── get_supplement_content.html │ ├── index.html │ ├── rcpp_hello_world.html │ ├── rsoc-package.html │ ├── run1simulationwithfile.html │ ├── run1simulationwithfile_from_binary.html │ ├── run1simulationwithfile_inprocess.html │ └── simulation_time_to_years.html └── sitemap.xml ├── future_documentation.md ├── inst └── extdata │ ├── SWEfert2022 │ ├── SWEmort2022 │ └── init_new.opop ├── man ├── create_simulation_folder.Rd ├── create_sup_file.Rd ├── estimate_fertility_rates.Rd ├── estimate_mortality_rates.Rd ├── read_omar.Rd ├── read_opop.Rd ├── retrieve_kin.Rd ├── rsoc-package.Rd ├── run1simulationwithfile_from_binary.Rd ├── simulation_time_to_years.Rd └── socsim.Rd ├── random_number ├── rsocsim.Rproj ├── socsimOversimplified.pdf ├── socsim_oversimplified.md ├── src ├── RcppExports.cpp ├── src │ ├── census.c │ ├── defs.h │ ├── events.cpp │ ├── io.c │ ├── load.cpp │ ├── random.c │ ├── utils.c │ └── xevents.c └── startSocsimWithFile.cpp └── tests ├── testthat.R └── testthat ├── test_download_and_run.R ├── test_futurecalls.R ├── test_simulations.R ├── testit.R └── testit2.R /.Rbuildignore: -------------------------------------------------------------------------------- 1 | ^.*\.Rproj$ 2 | ^\.Rproj\.user$ 3 | ^\.github$ 4 | ^_pkgdown\.yml$ 5 | ^docs$ 6 | ^pkgdown$ 7 | -------------------------------------------------------------------------------- /.github/.gitignore: -------------------------------------------------------------------------------- 1 | *.html 2 | -------------------------------------------------------------------------------- /.github/workflows/pkgdown.yaml: -------------------------------------------------------------------------------- 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, master] 6 | pull_request: 7 | branches: [main, master] 8 | release: 9 | types: [published] 10 | workflow_dispatch: 11 | 12 | name: pkgdown 13 | 14 | jobs: 15 | pkgdown: 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 | steps: 23 | - uses: actions/checkout@v3 24 | 25 | - uses: r-lib/actions/setup-pandoc@v2 26 | 27 | - uses: r-lib/actions/setup-r@v2 28 | with: 29 | use-public-rspm: true 30 | 31 | - uses: r-lib/actions/setup-r-dependencies@v2 32 | with: 33 | extra-packages: any::pkgdown, local::. 34 | needs: website 35 | 36 | - name: Build site 37 | run: pkgdown::build_site_github_pages(new_process = FALSE, install = FALSE) 38 | shell: Rscript {0} 39 | 40 | - name: Deploy to GitHub pages 🚀 41 | if: github.event_name != 'pull_request' 42 | uses: JamesIves/github-pages-deploy-action@v4.4.1 43 | with: 44 | clean: false 45 | branch: gh-pages 46 | folder: docs 47 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # R/Rstudio user- or machine-specific files 2 | **/*.Rcheck 3 | **/*.RData 4 | **/*.Rhistory 5 | **/*.Rproj 6 | **/*.Rproj.user 7 | **/*.Ruserdata 8 | 9 | # Documentation. Users should (re-)generate this locally. 10 | docs/* 11 | man/* 12 | **/*.Rd 13 | 14 | # Vscode user- or machine-specific files 15 | .vscode/* 16 | .vscode/c_cpp_properties.json 17 | 18 | src/*.o 19 | src/*.so 20 | src/*.dll 21 | src-x64/* 22 | src-i386/* 23 | *.log 24 | .vscode/settings.json 25 | .vscode/c_cpp_properties.json 26 | docs 27 | man 28 | *.Rcheck 29 | *.Rproj.user 30 | *.Rd 31 | man/estimate_fertility_rates.Rd 32 | man/estimate_mortality_rates.Rd 33 | man/get_supervisory_content.Rd 34 | man/read_omar.Rd 35 | man/read_opop.Rd 36 | man/simulation_time_to_years.Rd 37 | man/socsim.Rd 38 | .vscode/* 39 | tmp/tmp/* 40 | .Rproj.user 41 | rsocsim.Rproj 42 | -------------------------------------------------------------------------------- /DESCRIPTION: -------------------------------------------------------------------------------- 1 | Package: rsocsim 2 | Type: Package 3 | Title: SOCSIM with R 4 | Version: 1.7.3 5 | Date: 2023-03-17 6 | Author: Tom Theile and Diego Alburez-Gutierrez 7 | Maintainer: Tom Theile 8 | Authors@R: c( 9 | person("Tom", "Theile", role = c("aut", "cre"), email = "theile@demogr.mpg.de", comment = c(ORCID = "0000-0003-0573-9093")), 10 | person("Diego", "Alburez-Gutierrez", role = c("aut", "cre"), comment = c(ORCID = "0000-0003-0573-9093")), 11 | person("Mallika", "Snyder", role = c("aut", "cre")), 12 | person("Liliana P.", "Calderón-Bernal", role = c("aut", "cre")) 13 | ) 14 | Description: Install and run socsim microsimulations from within R with this R-package. 15 | License: GPL (>= 2) 16 | Imports: Rcpp (>= 1.0.5), 17 | future, 18 | parallel, 19 | magrittr, 20 | dplyr, 21 | utils 22 | LinkingTo: Rcpp 23 | RoxygenNote: 7.3.2 24 | Suggests: 25 | testthat (>= 3.0.0) 26 | Config/testthat/edition: 3 27 | URL: https://github.com/MPIDR/rsocsim, 28 | https://mpidr.github.io/rsocsim/ 29 | Encoding: UTF-8 30 | Roxygen: list(markdown = TRUE) 31 | -------------------------------------------------------------------------------- /NAMESPACE: -------------------------------------------------------------------------------- 1 | # Generated by roxygen2: do not edit by hand 2 | 3 | export(asYr) 4 | export(census_socsim) 5 | export(create_initial_population) 6 | export(create_simulation_folder) 7 | export(create_sup_file) 8 | export(download_rates) 9 | export(estimate_fertility_rates) 10 | export(estimate_mortality_rates) 11 | export(get_supervisory_content) 12 | export(get_women_reproductive_age_socsim) 13 | export(jul) 14 | export(read_omar) 15 | export(read_opop) 16 | export(retrieve_kin) 17 | export(run1simulationwithfile_from_binary) 18 | export(simulation_time_to_years) 19 | export(socsim) 20 | export(yearly_birth_by_age_socsim) 21 | exportPattern("^[[:alpha:]]+") 22 | import(dplyr) 23 | importFrom(Rcpp,evalCpp) 24 | importFrom(magrittr,"%>%") 25 | useDynLib(rsocsim) 26 | -------------------------------------------------------------------------------- /NEWS.md: -------------------------------------------------------------------------------- 1 | # rsocsim 1.7.0 2 | * added function create_initial_simulation 3 | * the code is based on https://github.com/MPIDR/rsocsim_workshop_paa?tab=readme-ov-file#23-create-initial-population-and-marriage-files 4 | * merged bugfixes that caused crashes in socsim since December 2024 5 | 6 | # rsocsim 1.6.0 7 | * added function download_rates, which downloads UN rates and saves them into rsocsim format 8 | * See https://github.com/MPIDR/rsocsim/issues/28 9 | 10 | # rsocsim 1.5.9 11 | * removed keyword register in load.cpp (See https://github.com/MPIDR/rsocsim/issues/11; it causes errors on Mac) 12 | 13 | # rsocsim 1.5.8 14 | * renamed getKin() to retrieve_kin() 15 | * bugfixes 16 | 17 | # rsocsim 1.5.7 18 | * bugfixes 19 | 20 | # rsocsim 1.5.6 21 | * read_opop and read_omar 22 | * works on linux and windows, also with future and clustercall. Mac not tested, linux sometimes flaky 23 | 24 | # rsocsim 1.5.5 25 | * compiles and runs on Linux again 26 | * reorganized contributed code from Liliana and Mallika 27 | * todo: tests for contributed code. how to use these functions? 28 | * todo: install and run on Mac 29 | 30 | # rsocsim 1.5.4 31 | * Max age 200 years 32 | * new command for sup files: marriage_after_childbirth 1 33 | * allows simulations without marriage rates 34 | * mothers will marry immediately before childbirth if not married already 35 | 36 | # rsocsim 1.5.3 37 | * compiles on Github now 38 | * use pkgdown to generate documentation-website 39 | -------------------------------------------------------------------------------- /R/RcppExports.R: -------------------------------------------------------------------------------- 1 | # Generated by using Rcpp::compileAttributes() -> do not edit by hand 2 | # Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 3 | 4 | startSocsimWithFile <- function(supfile, seed, compatibility_mode, result_suffix) { 5 | .Call('_rsocsim_startSocsimWithFile', PACKAGE = 'rsocsim', supfile, seed, compatibility_mode, result_suffix) 6 | } 7 | 8 | -------------------------------------------------------------------------------- /R/download_rates.R: -------------------------------------------------------------------------------- 1 | #' download and convert rate files from HMD, HFD, UN 2 | #' @description Given a iso2code countrycode and a range of years (between 1950 3 | #' and 2100) this function will download mortality and fertility rates and 4 | #' saves them in a 5 | #' @param folder folder where the rates will be saved 6 | #' @param countrycode 2-character country code https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 7 | #' @param yearStart Start year. For "UN" the first possible year is 1950 8 | #' @param yearEnd End year. For "UN" the first possible year is 2100 9 | #' @param source "UN", at the moment only UN Population Prospects is supported 10 | #' @param apiUrl url of the API. "https://user.demogr.mpg.de/theile/socsimratesAPI/v1/" by default 11 | #' @details 12 | #' See https://github.com/tomthe/retrieveVitalRates_for_rsocsim_API for the 13 | #' code that converts the source data into socsim format. 14 | #' 15 | #' @return todo 16 | #'@examples 17 | #' \dontrun{ 18 | #' # todo 19 | #' } 20 | #' @export 21 | download_rates <- function(folder, countrycode, yearStart = 1950, yearEnd = 2100, 22 | source = "UN", 23 | apiUrl = "https://user.demogr.mpg.de/theile/socsimratesAPI/v1/") { 24 | 25 | # Validate input parameters 26 | if (!dir.exists(folder)) { 27 | stop("The specified folder does not exist.") 28 | } 29 | 30 | if (!is.character(countrycode) || nchar(countrycode) != 2) { 31 | stop("countrycode should be a 2-character string.") 32 | } 33 | 34 | if (!is.numeric(yearStart) || !is.numeric(yearEnd) || yearStart > yearEnd) { 35 | stop("yearStart and yearEnd should be numeric values with yearStart <= yearEnd") 36 | } 37 | 38 | # Construct API URLs for fertility and mortality data 39 | fertUrl <- paste0(apiUrl, source, "/", countrycode, "/socsim_fert_", countrycode, "_rates.zip") 40 | mortUrl <- paste0(apiUrl, source, "/", countrycode, "/socsim_mort_", countrycode, "_rates.zip") 41 | 42 | # Create a temporary directory for downloading zip files 43 | tempDir <- tempdir() 44 | 45 | # Download fertility and mortality zip files 46 | fertZipPath <- file.path(tempDir, paste0("socsim_fert_", countrycode, "_rates.zip")) 47 | mortZipPath <- file.path(tempDir, paste0("socsim_mort_", countrycode, "_rates.zip")) 48 | 49 | tryCatch({ 50 | message(paste0("Downloading fertility data from ", fertUrl, " to ", fertZipPath)) 51 | utils::download.file(fertUrl, destfile = fertZipPath, mode = "wb", quiet = TRUE) 52 | message(paste0("Downloading mortality data from ", mortUrl, " to ", mortZipPath)) 53 | utils::download.file(mortUrl, destfile = mortZipPath, mode = "wb", quiet = TRUE) 54 | }, error = function(e) { 55 | stop(paste("Error downloading data from API:", e$message)) 56 | }) 57 | 58 | message("Processing files...") 59 | 60 | # Create rates subfolder if it doesn't exist 61 | ratesFolder <- file.path(folder, "rates") 62 | if (!dir.exists(ratesFolder)) { 63 | dir.create(ratesFolder) 64 | } 65 | 66 | # Process zip file and extract relevant files based on year range 67 | processZip <- function(zipPath, type) { 68 | tryCatch({ 69 | # Extract file list from zip 70 | zipContent <- utils::unzip(zipPath, list = TRUE) 71 | files <- zipContent$Name 72 | 73 | # Initialize vector for extracted files 74 | extractedFiles <- character(0) 75 | 76 | for (file in files) { 77 | # Extract year from filename assuming the format "socsim___.txt" 78 | parts <- strsplit(file, "_")[[1]] 79 | year <- as.numeric(sub(".txt", "", parts[4])) 80 | yearMatches <- if (!is.na(year)) year else numeric(0) 81 | 82 | # Skip if no year found in filename 83 | if (length(yearMatches) == 0) { 84 | next 85 | } 86 | 87 | # Convert matched strings to numbers 88 | years <- as.numeric(yearMatches) 89 | 90 | # Determine the file's year range 91 | fileYearStart <- min(years) 92 | fileYearEnd <- max(years) 93 | 94 | # Check if file's year range overlaps with requested range 95 | if (fileYearEnd >= yearStart && fileYearStart <= yearEnd) { 96 | # Extract the file into the rates folder 97 | utils::unzip(zipPath, files = file, exdir = ratesFolder, overwrite = TRUE) 98 | extractedFiles <- c(extractedFiles, file) 99 | } 100 | } 101 | 102 | return(extractedFiles) 103 | }, error = function(e) { 104 | message("Error processing ", type, " zip file: ", e$message) 105 | return(character(0)) 106 | }) 107 | } 108 | 109 | # Process both zip files 110 | extractedFertFiles <- processZip(fertZipPath, "fertility") 111 | extractedMortFiles <- processZip(mortZipPath, "mortality") 112 | 113 | # Create info file 114 | infoFilePath <- file.path(folder, paste0(countrycode, "_rates_info.sup")) 115 | 116 | # Create supervisory file content 117 | supContent <- paste0( 118 | "***************************************************************************\n", 119 | "* Supervisory file for SOCSIM microsimulation for ", countrycode, " ", yearStart, "-", yearEnd, "\n", 120 | "* Created on ", format(Sys.time(), "%d.%m.%Y"), "\n", 121 | "***************************************************************************\n", 122 | "* This simulation uses as input age-specific data retrieved from ", source, "\n", 123 | "* converted into SOCSIM format.\n", 124 | "***************************************************************************\n", 125 | "segments ", yearEnd - yearStart + 1, "\n", 126 | "input_file presim\n", 127 | "execute \"touch presim.omar\"\n", 128 | "\nbint 12\nhetfert 1\nmarriage_queues 1\nmarriage_eval distribution\nmarriage_after_childbirth 1\nrandom_father 1\n", 129 | "\n***********************************************************************\n", 130 | "* Pre-simulation to get a stable population at ", yearStart - 1, "\n", 131 | "* Using rates for ", yearStart, "\n", 132 | "* Change duration to 1200 for a stable population\n", 133 | "***********************************************************************\n", 134 | "\nduration 96", 135 | "\ninclude rates/socsim_fert_", countrycode, "_", yearStart, ".txt", 136 | "\ninclude rates/socsim_mort_", countrycode, "_", yearStart, ".txt", 137 | "\nrun\n" 138 | ) 139 | 140 | # Add simulation segments for each year 141 | for (year in yearStart:yearEnd) { 142 | supContent <- paste0( 143 | supContent, 144 | "\n* Simulation for year ", year, "\n", 145 | "duration 12", 146 | "\ninclude rates/socsim_fert_", countrycode, "_", year, ".txt", 147 | "\ninclude rates/socsim_mort_", countrycode, "_", year, ".txt", 148 | "\nrun\n" 149 | ) 150 | } 151 | 152 | writeLines(supContent, infoFilePath) 153 | 154 | # Clean up temporary files 155 | unlink(fertZipPath) 156 | unlink(mortZipPath) 157 | 158 | message("Process complete. Files extracted to ", folder) 159 | 160 | return(list( 161 | fertility = extractedFertFiles, 162 | mortality = extractedMortFiles, 163 | infoFile = infoFilePath 164 | )) 165 | } 166 | 167 | 168 | -------------------------------------------------------------------------------- /R/prepare_initial_population.R: -------------------------------------------------------------------------------- 1 | #' Create Initial Population for Simulation 2 | #' 3 | #' This function generates an initial population data frame and an empty marriage data frame, 4 | #' then writes them to files in the specified folder. The output filenames are generated by appending 5 | #' ".opop" and ".omar" to the given base name. 6 | #' 7 | #' @param folder A character string specifying the folder where the files will be saved. 8 | #' @param size_opop An integer defining the size of the initial population. Default is 20000. 9 | #' @param output_base A character string for the base name of the output files. Default is "presim". 10 | #' 11 | #' @return None. The function writes two files: one for the initial population and one for empty marriage data. 12 | #' 13 | #' @examples 14 | #' \dontrun{ 15 | #' create_initial_population(folder = "C:/simulations", size_opop = 10000, output_base = "simdata") 16 | #' } 17 | #' 18 | #' @export 19 | create_initial_population <- function(folder, size_opop = 20000, output_base = "presim") { 20 | 21 | # Construct full file paths for the output files 22 | output_file_opop <- file.path(folder, paste0(output_base, ".opop")) 23 | output_file_omar <- file.path(folder, paste0(output_base, ".omar")) 24 | 25 | # Create data.frame with 14 columns and nrows = size_opop 26 | presim_opop <- setNames( 27 | data.frame(matrix(data = 0, ncol = 14, nrow = size_opop)), 28 | c("pid", "fem", "group", "nev", "dob", "mom", "pop", 29 | "nesibm", "nesibp", "lborn", "marid", "mstat", "dod", "fmult") 30 | ) 31 | 32 | # Add pid 1:size_opop 33 | presim_opop$pid <- 1:size_opop 34 | 35 | # Add sex randomly 36 | presim_opop$fem <- sample(0:1, nrow(presim_opop), replace = TRUE) 37 | 38 | # Add group 1 for all individuals 39 | presim_opop$group <- 1 40 | 41 | # Add random dates of birth (max age around 50) 42 | presim_opop$dob <- sample(600:1200, nrow(presim_opop), replace = TRUE) 43 | 44 | # Write initial population for pre-simulation (without fertility multiplier) 45 | utils::write.table(presim_opop, output_file_opop, row.names = FALSE, col.names = FALSE) 46 | 47 | # Create an empty data frame for marriage data 48 | presim_omar <- data.frame() 49 | 50 | # Write empty marriage data for pre-simulation 51 | utils::write.table(presim_omar, output_file_omar, row.names = FALSE, col.names = FALSE) 52 | } -------------------------------------------------------------------------------- /R/read_results.R: -------------------------------------------------------------------------------- 1 | 2 | #' Read output marriage file into a data frame 3 | #' 4 | #' \tabular{rll}{ 5 | #' 1 \tab mid \tab Marriage id number (unique sequential integer) \cr 6 | #' 2 \tab wpid \tab Wife’s person id \cr 7 | #' 3 \tab hpid \tab Husband’s person id \cr 8 | #' 4 \tab dstart \tab Date marriage began \cr 9 | #' 5 \tab dend \tab Date marriage ended or zero if still in force at end of simulation \cr 10 | #' 6 \tab rend \tab Reason marriage ended 2 = divorce; 3 = death of one partner \cr 11 | #' 7 \tab wprior \tab Marriage id of wife’s next most recent prior marriage \cr 12 | #' 8 \tab hprior \tab Marriage id of husband’s next most recent prior marriage \cr 13 | #' } 14 | #' 15 | #' you can either provide the complete `path` to the file or the `folder`, supfilename, seed and suffix with which you 16 | #' started the simulation 17 | #' 18 | #' @param folder simulation base folder ("~/socsim/simulation_235/") 19 | #' @param supfile name of supervisory-file ("socsim.sup") 20 | #' @param seed random number seed (42) 21 | #' @param suffix optional suffix for the results-directory (default="") 22 | #' @param fn complete path to the file. If not provided, it will be created from the other arguments 23 | #' 24 | #' @return Data frame with the information of the output population file 25 | #' 26 | #' @md 27 | #' 28 | #' @export 29 | read_omar <- function(folder=NULL, supfile="socsim.sup",seed=42,suffix="",fn=NULL){ 30 | 31 | # create fn 32 | if (is.null(fn)){ 33 | fn <- paste0(folder,"/sim_results_", supfile, "_",seed,"_",suffix, "/result.omar") 34 | } else { 35 | fn <- fn 36 | } 37 | print(paste0("read marriage file: ",fn)) 38 | omar<-read.table(file = fn, header = F, as.is = T) 39 | names(omar)<-c("mid","wpid","hpid","dstart","dend", "rend","wprior","hprior") 40 | return(omar) 41 | } 42 | 43 | 44 | #' Read output population file into a data frame 45 | #' 46 | #' after the end of the simulation, socsim writes every person of the simulation into 47 | #' a file called result.opop | 48 | #' 49 | #' \tabular{rll}{ 50 | #' 1 \tab pid \tab Person id unique identifier assigned as integer in birth order \cr 51 | #' 2 \tab fem \tab 1 if female 0 if male \cr 52 | #' 3 \tab group \tab Group identifier 1..60 current group membership of individual \cr 53 | #' 4 \tab nev \tab Next scheduled event \cr 54 | #' 5 \tab dob \tab Date of birth integer month number \cr 55 | #' 6 \tab mom \tab Person id of mother \cr 56 | #' 7 \tab pop \tab Person id of father \cr 57 | #' 8 \tab nesibm \tab Person id of next eldest sibling through mother \cr 58 | #' 9 \tab nesibp \tab Person id of next eldest sibling through father \cr 59 | #' 10 \tab lborn \tab Person id of last born child \cr 60 | #' 11 \tab marid \tab Id of marriage in .omar file \cr 61 | #' 12 \tab mstat \tab Marital status at end of simulation integer 1=single;2=divorced; 3=widowed; 4=married \cr 62 | #' 13 \tab dod \tab Date of death or 0 if alive at end of simulation \cr 63 | #' 14 \tab fmult \tab Fertility multiplier \cr 64 | #' } 65 | #' 66 | #' This table explains the columns of the opop file and the columns of the output data frame. 67 | #' You can either provide the complete `path` to the file or the `folder`, supfilename, seed and suffix with which you 68 | #' started the simulation 69 | #' 70 | #' @param folder simulation base folder ("~/socsim/simulation_235/") 71 | #' @param supfile name of supervisory-file ("socsim.sup") 72 | #' @param seed random number seed (42) 73 | #' @param suffix optional suffix for the results-directory (default="") 74 | #' @param fn complete path to the file. If not provided, it will be created from the other arguments 75 | #' 76 | #' @return Data frame with the information of the output population file 77 | #' 78 | #' @md 79 | #' 80 | #' @export 81 | read_opop <- function(folder=NULL, supfile="socsim.sup",seed=42,suffix="",fn=NULL){ 82 | 83 | # create fn 84 | if (is.null(fn)){ 85 | fn <- paste0(folder,"/sim_results_", supfile, "_",seed,"_",suffix, "/result.opop") 86 | } else { 87 | fn <- fn 88 | } 89 | 90 | print(paste0("read population file: ",fn)) 91 | opop <- read.table(file=fn,header=F,as.is=T) 92 | ## assign names to columns 93 | names(opop)<-c("pid","fem","group", 94 | "nev","dob","mom","pop","nesibm","nesibp", 95 | "lborn","marid","mstat","dod","fmult") 96 | return(opop) 97 | } 98 | -------------------------------------------------------------------------------- /R/rsocsim.R: -------------------------------------------------------------------------------- 1 | #' @useDynLib rsocsim 2 | #' @importFrom Rcpp evalCpp 3 | #' @exportPattern "^[[:alpha:]]+" 4 | NULL 5 | 6 | # This file is necessary so that Roxigen2 and devtools::document() generate the correct NAMESPACE file. 7 | # See https://stackoverflow.com/questions/33395264/trouble-building-r-package-wtih-devtools-when-it-uses-rcpparmadillo 8 | 9 | if (getRversion() >= "2.15.1") { 10 | utils::globalVariables(c("dod", "dob", "dod2", "census", "fem", "sex", 11 | "age_at_census", "agegr_at_census", "n", 12 | "pid", "mom", "birth_year", "mother_birth", 13 | "birth_year_factor", "mother_age", "mother_agegr_factor")) 14 | } -------------------------------------------------------------------------------- /R/startsocsim.R: -------------------------------------------------------------------------------- 1 | #' Run a single Socsim simulation with a given supervisory file and directory 2 | #' 3 | #' @param folder A string. This is the base directory of the simulation. Every 4 | #' .sup and rate file should be named relative to this directory. 5 | #' @param supfile A string. The name of the .sup file to start the simulation, 6 | #' relative to the directory. 7 | #' @param seed A string. The seed for the RNG, so expects an integer. Defaults 8 | #' to "42". 9 | #' @param process_method A string. Whether and how SOCSIM should be started in 10 | #' its own process or in the running R process. Defaults to "inprocess". Use 11 | #' one of: 12 | #' * "future" - the safest option. A new process will be started via the 13 | #' "future" package 14 | #' * "inprocess" - SOCSIM runs in the R-process. Beware if you run several 15 | #' different simulations, they may affect later simulations. 16 | #' * "clustercall" - if the future package is not available, try this method 17 | #' instead. 18 | #' @param compatibility_mode A string. 19 | #' @param suffix A string. 20 | #' @return Returns the name of the directory to which the results will be 21 | #' written. 22 | #' @export 23 | socsim <- function(folder, supfile, seed = "42", process_method = "inprocess", 24 | compatibility_mode = "1", suffix = "") { 25 | seed = as.character(seed) 26 | compatibility_mode = as.character(compatibility_mode) 27 | print("Start running one simulation with a .sup file.") 28 | print(paste("Base directory of the simulation:", folder)) 29 | print(paste("RNG seed:", seed)) 30 | previous_wd = getwd() 31 | result = NULL 32 | # If 'supfile' contains more than a basename, startSocsimWithFile() will 33 | # crash. This is only a workaround. 34 | remove_supfile <- FALSE 35 | if (!identical(basename(supfile), supfile)) { 36 | if (identical(dirname(supfile), "folder")) { 37 | supfile <- basename(supfile) 38 | } else { 39 | warning("The argument 'supfile' contained more than a basename. We copy the .sup file to the 'folder' directory (to avoid startSocsimWithFile() from crashing) and will remove it after the simulation finishes.") 40 | file.copy(from = file.path(folder, supfile), to = folder, overwrite = TRUE) 41 | remove_supfile <- TRUE 42 | } 43 | } 44 | tryCatch(expr = { 45 | setwd(folder) 46 | result = run_sim_w_file(supfile = supfile, 47 | seed = seed, 48 | compatibility_mode = compatibility_mode, 49 | suffix = suffix, 50 | method = process_method) 51 | }, 52 | error = function(w){ 53 | warning("Error during execution of simulation!") 54 | warning(w) 55 | }, 56 | finally = { 57 | print(paste("Restore previous working dir:", previous_wd)) 58 | setwd(previous_wd) 59 | } 60 | ) 61 | return(result) 62 | 63 | } 64 | 65 | #' Run a single Socsim simulation. 66 | #' 67 | #' @details 68 | #' See [socsim()] for documentation of the arguments. 69 | #' 70 | #' @inheritParams socsim 71 | run_sim_w_file <- function(supfile, seed = "42", compatibility_mode = "1", 72 | suffix = "", method = "inprocess") { 73 | if (method == "inprocess") { 74 | print("Starting socsim simulation now. No output will be shown!") 75 | startSocsimWithFile(supfile = supfile, 76 | seed = seed, 77 | compatibility_mode = compatibility_mode, 78 | result_suffix = suffix) 79 | return(1) 80 | } else if (method == "future") { 81 | print("Using future::future to run simulation in a separate process.") 82 | future::plan(future::multisession, workers=2) 83 | print("Starting socsim simulation now. No output will be shown!") 84 | f1 <- future::future({ 85 | startSocsimWithFile(supfile, seed, compatibility_mode, result_suffix = suffix) 86 | }, seed = TRUE) 87 | print("Started the simulation.") 88 | # start a loop and check whether the simulation in the future is finished. 89 | # if it is not yet finished, read the output file and print the last line 90 | # to the console 91 | outfn = paste0("sim_results_", supfile, "_", seed, "_", suffix, "/logfile.log") 92 | print(paste("Wait for simulation to finish. Log file:",outfn)) 93 | lastline = "" 94 | while (!future::resolved(f1)) { 95 | Sys.sleep(1) 96 | lastline = print_last_line_of_logfile(outfn, lastline) 97 | if (lastline=="err0"){ 98 | break; 99 | } 100 | } 101 | print("Finished running the simulation.") 102 | v1 <- future::value(f1) # TODO: v1 isn't used anywhere? 103 | return(1) 104 | } else if (method == "clustercall") { 105 | print("Using parallel::clusterCall to run simulation in a separate process.") 106 | outfn <- paste0("sim_results_", supfile, "_", seed, "_", suffix, "/logfile.log") 107 | cl <- parallel::makeCluster(spec = 1, type = "PSOCK", outfile = outfn) 108 | parallel::clusterExport(cl, "startSocsimWithFile") 109 | parallel::clusterCall(cl, 110 | startSocsimWithFile, 111 | supfile = supfile, 112 | seed = seed, 113 | compatibility_mode = compatibility_mode, 114 | result_suffix = suffix) 115 | print("Started the simulation.") 116 | print_last_line_of_logfile(outfn) 117 | parallel::stopCluster(cl) 118 | print("Finished running the simulation.") 119 | return(1) 120 | } else { 121 | stop("No valid process_method argument given.") 122 | } 123 | } 124 | 125 | print_last_line_of_logfile = function(logfilename, lastline = "") { 126 | tryCatch({ 127 | con = file(logfilename, "r") 128 | while ( TRUE ) { 129 | line = readLines(con, n = 1) 130 | if ( length(line) == 0 ) { 131 | if(lastline != line2){ 132 | print(line2); 133 | } 134 | break 135 | } 136 | line2 <- line 137 | } 138 | close(con) 139 | return(line2) 140 | }, error = function(e) { 141 | warning("Error while reading file") 142 | warning(logfilename) 143 | warning(e) 144 | return("err0") 145 | }) 146 | } 147 | 148 | 149 | #' Run a single socsim-simulation with a socsim binary 150 | #' 151 | #' @param folder base-directory of the simulation. 152 | #' @param supfile the .sup file to start the simulation, relative to the 153 | #' folder 154 | #' @param seed RNG seed as string, Default="42" 155 | #' @param socsim_path path+filename of a socsim-executable. Download one from https://github.com/tomthe/socsim/releases/download/0.3/socsim.exe 156 | #' @param compatibility_mode compatibility mode as string, Default="1" 157 | #' 158 | #' @return The results will be written into the specified folder 159 | #' @export 160 | run1simulationwithfile_from_binary <- function(folder, supfile,seed="42",compatibility_mode="1",socsim_path=NULL) { 161 | if (is.null(socsim_path) || !dir.exists(normalizePath(socsim_path))) { 162 | print("No socsim_path specified. So I will download the Windows-binary from github to a temporary directory!") 163 | print("This will probably not work due to antivirus-software.") 164 | print("please download an executable socsim from https://github.com/tomthe/socsim/releases/download/0.3/socsim.exe") 165 | print("then save the whole path and specify it as socsim_path for this function!") 166 | url = "https://github.com/tomthe/socsim/releases/download/0.3/socsim.exe" 167 | socsim_path = file.path(tempdir(), "socsim.exe") 168 | download.file(url,socsim_path,method="auto") 169 | } 170 | seed = toString(seed) 171 | print("Start run1simulationwithfile") 172 | print(folder) 173 | print(supfile) 174 | print(paste0("socsim_path: ", socsim_path)) 175 | print(seed) 176 | previous_wd = getwd() 177 | setwd(paste0(folder)) 178 | 179 | print(paste0("command: ",socsim_path,args=paste0(" ",supfile," ", seed," ", compatibility_mode))) 180 | 181 | print(system2(socsim_path,args=c(supfile," ", seed, " ",compatibility_mode))) 182 | print(system(paste(socsim_path, supfile, seed,compatibility_mode))) 183 | a = (system(paste(socsim_path, paste0(dirname(folder), "\\", supfile), seed, compatibility_mode))) 184 | print(paste(socsim_path, paste0(dirname(folder), "\\", supfile), seed,compatibility_mode)) 185 | print(a) 186 | print(previous_wd) 187 | setwd(previous_wd) 188 | return(1) 189 | } 190 | 191 | #' Create a directory structure for the simulation 192 | #' 193 | #' Create a two-level directory structure. If the first-level argument is NULL, 194 | #' we look for and, if needed, created the directory 'socsim' in the user's 195 | #' home directory. If the second-level argument is NULL, we create a directory 196 | #' named 'socsim_sim_{some random component}' in the first-level directory. 197 | #' 198 | #' @param basedir A string. Optional. First-level directory where the 199 | #' simulation-specific directory will be created. Defaults to '$HOME/socsim'. 200 | #' @param simdir A string. Optional. Simulation-specific directory which will 201 | #' be created within 'basedir'. Defaults to 'socsim_sim_' plus a random 202 | #' component created with [tempfile()]. 203 | #' @return A string. The full path to the simulation-specific directory. 204 | #' @export 205 | create_simulation_folder <- function(basedir = NULL, simdir = NULL) { 206 | # If no 'basedir' is given, we default to '$HOME/socsim'. 207 | if (is.null(basedir)) { basedir <- file.path(path.expand("~"), "socsim") } 208 | # If 'basedir' does not exist, create it. 209 | if (!dir.exists(basedir)) { dir.create(basedir) } 210 | if (is.null(simdir)) { 211 | # If no 'simdir' is given, create a random name that starts with 212 | # 'socsim_sim_'. 213 | subdir = tempfile(pattern = "socsim_sim_", tmpdir = basedir) 214 | } else { 215 | subdir = file.path(basedir, simdir) 216 | } 217 | if (!dir.exists(subdir)) { dir.create(subdir) } 218 | return(subdir) 219 | } 220 | 221 | #' Create a basic .sup file for a simulation 222 | #' 223 | #' The simulation is only a simple one. The file will be saved into the 224 | #' directory 'simdir'. 225 | #' 226 | #' @param simdir A string. The directory where the .sup file will be saved. 227 | #' @param simname A string. The name of the simulation. 228 | #' @return A string. The filename of the supervisory file which is needed to 229 | #' start the simulation. 230 | #' @export 231 | create_sup_file <- function(simdir, simname) { 232 | sup_content <- " 233 | *Supervisory file for a stable population 234 | * 20220120 235 | marriage_queues 1 236 | bint 10 237 | segments 1 238 | marriage_eval distribution 239 | marriage_after_childbirth 1 240 | input_file init_new 241 | * 242 | duration 1200 243 | include SWEfert2022 244 | include SWEmort2022 245 | run 246 | " 247 | sup_fn <- "socsim.sup" 248 | cat(sup_content, file = file.path(simdir, sup_fn)) 249 | fn_SWEfert2022_source <- system.file("extdata", "SWEfert2022", 250 | package = "rsocsim", mustWork = TRUE) 251 | fn_SWEfert2022_dest <- file.path(simdir, "SWEfert2022") 252 | fn_SWEmort2022_source <- system.file("extdata", "SWEmort2022", 253 | package = "rsocsim", mustWork = TRUE) 254 | fn_SWEmort2022_dest <- file.path(simdir, "SWEmort2022") 255 | fn_init_source <- system.file("extdata", "init_new.opop", 256 | package = "rsocsim", mustWork = TRUE) 257 | fn_init_dest <- file.path(simdir, "init_new.opop") 258 | file.copy(fn_SWEfert2022_source, fn_SWEfert2022_dest) 259 | file.copy(fn_SWEmort2022_source, fn_SWEmort2022_dest) 260 | file.copy(fn_init_source, fn_init_dest) 261 | return(sup_fn) 262 | } 263 | 264 | #' Read the content of the supervisory file 265 | #' 266 | #' @param simdir A string. Base directory of the simulation. 267 | #' @param simname A string. File name of the .sup file. 268 | #' @return A list of strings. The content of the supervisory file. 269 | #' @export 270 | get_supervisory_content <- function(simdir, sup_fn) { 271 | if (is.null(sup_fn)) { 272 | sup_fn <- "socsim.sup" 273 | } 274 | sup_content <- readLines(file.path(simdir, sup_fn)) 275 | return(sup_content) 276 | } 277 | 278 | #' Calculate for how many years the simulation ran 279 | #' 280 | #' @param simulation_time An integer. The number of periods (months) the 281 | #' simulation ran. 282 | #' @param pre_simulation_time An integer. The number of periods (months) the 283 | #' simulation ran before getting to a stable population. This is subtracted 284 | #' from 'simulation_time' in order to arrive at the "real" simulation time 285 | #' @param start_year An integer. The year the simulation started. 286 | #' @return An number. The number of years for which the simulation ran. May 287 | #' have a fractional part. 288 | #' @export 289 | simulation_time_to_years <- function(simulation_time, pre_simulation_time, start_year) { 290 | stopifnot(all(is.integer(simulation_time), is.integer(pre_simulation_time), is.integer(start_year))) 291 | return(start_year + (simulation_time - pre_simulation_time)/12) 292 | } 293 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # rsocsim - Socsim R package 2 | 3 | 2023-MPIDR_rsocsim-web-144 4 | 5 | Socsim ('Social Simulator') is an open source stochastic microsimulation platform used to produce synthetic populations with plausible kinship structures using demographic rates as input. 6 | We stand on the shoulders of giants: Socsim was originally developed for Unix at UC Berkeley [1-2], where it has been mantained for decades. The current release of `rsocsim` aims to be OS-agnostic and, for the most part, back-compatible with the original Socsim distribution (https://lab.demog.berkeley.edu/socsim/). 7 | 8 | `rsocsim` is still under development. You might find some bugs or unexpected behavior, the API might change without warnings in the next weeks. 9 | If you encounter an error or bug, we are happy to hear from you in the issues. 10 | 11 | ## Installation 12 | 13 | ### From a binary package 14 | 15 | Download the correct binary package from the [release section on Github](https://github.com/MPIDR/rsocsim/releases): 16 | Currently, you can use [rsocsim_1.5.9.tgz](https://github.com/MPIDR/rsocsim/releases/download/v1.5.9/rsocsim_1.5.9.tgz) for Mac and [rsocsim_1.7.3.zip](https://github.com/MPIDR/rsocsim/releases/download/1.7.3/rsocsim_1.7.3.zip) 17 | for Windows. 18 | 19 | Then execute the following line in R and choose the downloaded file: 20 | ``` 21 | install.packages(file.choose(),repos=NULL,type="binary") 22 | ``` 23 | 24 | ### From Source (requires a compiler) 25 | 26 | To get the latest version, you need to have a Rcpp compatible compiler installed 27 | and a way to install packages from Github. 28 | 29 | Install a Rcpp compatible compiler: 30 | 31 | - on Windows: [RTools](https://cran.r-project.org/bin/windows/Rtools/index.html); 32 | - on Mac: `xcode-select --install`; 33 | - on Linux: `sudo apt-get install r-base-dev`. 34 | 35 | For more help, see [Rcpp for everyone](https://teuder.github.io/rcpp4everyone_en/020_install.html). 36 | 37 | In order to install packages from Github, you can use the {remotes} or 38 | {devtools} packages. {remotes} ([CRAN link](https://cran.r-project.org/web/packages/remotes/index.html)) 39 | only provides the capability to install packages from different code 40 | repositories. {devtools} ([CRAN link](https://cran.r-project.org/web/packages/devtools/index.html)) 41 | includes many more capabilities needed in package development (e.g. 42 | (re-)generating documentation or running tests). {devtools} includes {remotes}. 43 | 44 | 45 | Install {remotes} or {devtools}: 46 | ````R 47 | install.packages("remotes") 48 | ```` 49 | 50 | Install rsocsim from Github: 51 | ````R 52 | # The command is the same in {devtools} and {remotes}. 53 | remotes::install_github("MPIDR/rsocsim@v1.5.9") 54 | ```` 55 | 56 | ## Use rsocsim 57 | 58 | 59 | ### Getting started 60 | 61 | ````R 62 | library("rsocsim") 63 | 64 | # create a new folder for all the files related to a simulation. 65 | # this will be in your home- or user-directory: 66 | folder = rsocsim::create_simulation_folder() 67 | 68 | # create a new supervisory-file. 69 | # supervisory-files tell socsim what to simulate. 70 | # create_sup_file will create a very basic supervisory file. 71 | # It also copies some rate-files that will be needed into the 72 | # simulation folder: 73 | supfile = rsocsim::create_sup_file(folder) 74 | 75 | # Choose a random-number seed: 76 | seed = 300 77 | 78 | # Start the simulation: 79 | rsocsim::socsim(folder,supfile,seed) 80 | 81 | ```` 82 | 83 | The results will be saved into a subfolder of the simulation-`folder´. 84 | For more sophisticated simulations you will need to edit the supervisory 85 | file and provide rate files for fertility, mortality and marriage rates. 86 | 87 | If you run more than one simulation, previous simulations may corrupt 88 | later simulations. Use the option `process_method = "future"` to prevent this: 89 | ``` 90 | rsocsim::socsim(folder,supfile,seed,process_method = "future") 91 | ``` 92 | 93 | ### Tutorial 94 | 95 | We created a practical workshop "Demographic microsimulations in R using SOCSIM: Modelling population and kinship dynamics" which you can access here: 96 | https://github.com/alburezg/rsocsim_workshop_paa 97 | 98 | ## Background and applications 99 | 100 | The following description of SOCSIM was adapted from the Supplementary Materials of [4]. 101 | SOCSIM is an open source and extensible demographic microsimulation program [1,3]. 102 | It is written in the C programming language and relies heavily on arrays of linked lists to keep track of kinship relationships and to store information about simulated individuals. 103 | The simulator takes as input initial population files and monthly age-specific fertility and mortality demographic rates. 104 | The individual is the unit of analysis of the simulator. 105 | Each person is subject to a set of rates, expressed as monthly probabilities of events, given certain demographic characteristics, like age and sex. 106 | Every month, each individual faces the risk of experiencing a number of events, including childbirth, death, and marriage. 107 | The selection of the event and the waiting time until the event occurs are determined stochastically using a competing risk model. 108 | Some other constraints are included in the simulation program in order to draw events only for individuals that are eligible for the events (e.g. to allow for a minimum interval of time between births from the same mother, to avoid social taboos such as incest, etc.). 109 | Each event for which the individual is at risk is modeled as a piece-wise exponential distribution. 110 | The waiting time until each event occurs is randomly generated according to the associated demographic rates. 111 | The individual’s next event is the one with the shortest waiting time. 112 | At the end of the simulation, population files that contain a list of everyone who has ever lived in the population are created. 113 | In these files, each individual is an observation in a rectangular data file with records of demographic characteristics for the individual, and identification numbers for key kinship relations. 114 | SOCSIM models “closed” populations. 115 | Individuals may enter and exit the simulation only by (simulated) birth and death. 116 | 117 | 118 | SOCSIM has been used extensively in social science research to study, among other things, dynamics of kin availability [5-7], generational overlap [4,8], and kin loss [9-11]. 119 | 120 | ## Develop the package 121 | 122 | You will need RTools, devtools and rcpp. 123 | Clone this repository, change something, hit "Build-->clean and rebuild" 124 | (If that fails because the package is in use, you can restart the R-session (CTRL-SHIFT-F10)). 125 | 126 | 127 | renew documentation and some stuff with: 128 | ``` 129 | devtools.document() 130 | ``` 131 | 132 | build source and binary package: 133 | ``` 134 | devtools::build(binary=FALSE) 135 | devtools::build(binary=TRUE) 136 | ``` 137 | ### Style guide 138 | 139 | The goal of this section is to improve the readability of the code and reduce complaints from modern compilers (parts of the code are 40ish years old). We (try to) follow Allman style, but as a guideline not a hard requirement. Basically, this means: 140 | 141 | - one level of indentation = 4 spaces; 142 | - spaces not tabs; 143 | - braces after a function declaration or a control flow statement go on a new line; 144 | - first-level braces at the beginning of a line appear in the first column; 145 | - closing braces appear in the same column as their counterpart. 146 | - spaces...: 147 | - ... around binary operators; 148 | - ... after commas; 149 | - ... before opening parentheses and after closing parentheses. 150 | 151 | If you use vim, the default C formatting should be fine (':h C-indenting'). 152 | 153 | We reformatted the .cpp files because indentation was all over the place, but we left the .c files largely alone such as not to anger the compiler gods. 154 | 155 | ### Future plans 156 | 157 | * Testing and verification 158 | * including convenient R-functions for generating input and reading/processing output 159 | * possible options: 160 | * include those functions into this package 161 | * create another package that loads this package 162 | 163 | 164 | ## References 165 | 166 | 1. Hammel, E., Hutchinson, D., Wachter, K., Lundy, R., and Deuel, R. (1976). The SOCSIM Demographic-Sociological Microsimulation Program: Operating Manual. University of California Berkeley. Institute of International Studies. 167 | 168 | 2. Wachter, K.W. (1997). Kinship resources for the elderly. Philosophical Transactions of the Royal Society of London. Series B: Biological Sciences 352(1363):1811–1817. doi:10.1098/rstb.1997.0166. 169 | 170 | 3. Mason, Carl. (2016). Socsim Oversimplified. Accesed on 24 Feb 2023 from: https://lab.demog.berkeley.edu/socsim/CurrentDocs/socsimOversimplified.pdf 171 | 172 | 4. Alburez‐Gutierrez, D., Mason, C., and Zagheni, E. (2021). The “Sandwich Generation” Revisited: Global Demographic Drivers of Care Time Demands. Population and Development Review 47(4):997–1023. doi:10.1111/padr.12436. 173 | 174 | 5. Hammel, E.A. (2005). Demographic dynamics and kinship in anthropological populations. Proceedings of the National Academy of Sciences 102(6):2248–2253. doi:10.1073/pnas.0409762102. 175 | 176 | 6. Verdery, A.M. and Margolis, R. (2017). Projections of white and black older adults without living kin in the United States, 2015 to 2060. Proceedings of the National Academy of Sciences 114(42):11109–11114. doi:10.1073/pnas.1710341114. 177 | 178 | 7. Murphy, M. (2011). Long-Term Effects of the Demographic Transition on Family and Kinship Networks in Britain. Population and Development Review 37:55–80. doi:10.1111/j.1728-4457.2011.00378.x. 179 | 180 | 8. Margolis, R. and Verdery, A.M. (2019). A Cohort Perspective on the Demography of Grandparenthood: Past, Present, and Future Changes in Race and Sex Disparities in the United States. Demography 56(4):1495–1518. doi:10.1007/s13524-019-00795-1. 181 | 182 | 9. Zagheni, E. (2011). The Impact of the HIV/AIDS Epidemic on Kinship Resources for Orphans in Zimbabwe. Population and Development Review 37(4):761–783. doi:10.1111/j.1728-4457.2011.00456.x. 183 | 184 | 10. Verdery, A.M., Smith-Greenaway, E., Margolis, R., and Daw, J. (2020). Tracking the reach of COVID-19 kin loss with a bereavement multiplier applied to the United States. Proceedings of the National Academy of Sciences 117(30):17695. doi:10.1073/pnas.2007476117. 185 | 186 | 11. Snyder, M., Alburez-Gutierrez, D., Williams, I., and Zagheni, E. (2022). Estimates from 31 countries show the significant impact of COVID-19 excess mortality on the incidence of family bereavement. Proceedings of the National Academy of Sciences 119(26):e2202686119. doi:10.1073/pnas.2202686119. 187 | -------------------------------------------------------------------------------- /_pkgdown.yml: -------------------------------------------------------------------------------- 1 | url: https://mpidr.github.io/rsocsim/ 2 | template: 3 | bootstrap: 5 4 | 5 | -------------------------------------------------------------------------------- /development.md: -------------------------------------------------------------------------------- 1 | ## Development 2 | 3 | Github Actions is configured so that it automatically builds the documentation and website when the version number in the DESCRIPTION file is increased. 4 | 5 | But you can also use devtools to build the documentation and website. And to build the package (The package will not be build by Github Actions). 6 | 7 | `devtools::document()` - generate documentation from source-code comments 8 | `devtools::build()` - compile and build package 9 | `devtools::build(binary = TRUE)` - compile binary 10 | 11 | `devtools::check()` - run tests --> can it be published on CRAN? Runs several tests. 12 | 13 | 14 | `usethis::use_github_action("pkgdown")` 15 | 16 | `usethis::use_pkgdown_github_pages()` 17 | 18 | `devtools::document()` 19 | 20 | `pkgdown::build_site()` 21 | 22 | 23 | #### Testing without devtools 24 | Rscript -e "testthat::test_dir('tests/testthat')" -------------------------------------------------------------------------------- /docs/404.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | Page not found (404) • rsocsim 9 | 10 | 11 | 12 | 13 | 14 | 18 | 19 | 20 | Skip to contents 21 | 22 | 23 |
60 |
61 |
65 | 66 | Content not found. Please use links in the navbar. 67 | 68 |
69 |
70 | 71 | 72 |
76 | 77 | 81 | 82 |
83 |
84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | -------------------------------------------------------------------------------- /docs/authors.html: -------------------------------------------------------------------------------- 1 | 2 | Authors and Citation • rsocsim 6 | Skip to contents 7 | 8 | 9 |
41 |
42 |
45 | 46 |
47 |

Authors

48 | 49 |
  • 50 |

    Tom Theile. Author, maintainer. 51 |

    52 |
  • 53 |
  • 54 |

    Diego Alburez-Gutierrez. Author, maintainer. 55 |

    56 |
  • 57 |
  • 58 |

    Mallika Snyder. Author, maintainer. 59 |

    60 |
  • 61 |
  • 62 |

    Liliana P. Calderón-Bernal. Author, maintainer. 63 |

    64 |
  • 65 |
66 | 67 |
68 |

Citation

69 |

Source: DESCRIPTION

70 | 71 |

Theile T, Alburez-Gutierrez D, Snyder M, Calderón-Bernal L (2023). 72 | rsocsim: SOCSIM with R. 73 | https://github.com/MPIDR/rsocsim, 74 | https://mpidr.github.io/rsocsim/. 75 |

76 |
@Manual{,
 77 |   title = {rsocsim: SOCSIM with R},
 78 |   author = {Tom Theile and Diego Alburez-Gutierrez and Mallika Snyder and Liliana P. Calderón-Bernal},
 79 |   year = {2023},
 80 |   note = {https://github.com/MPIDR/rsocsim,
 81 | https://mpidr.github.io/rsocsim/},
 82 | }
83 |
84 |
86 | 87 | 88 |
91 | 92 | 95 | 96 |
97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | -------------------------------------------------------------------------------- /docs/bootstrap-toc.css: -------------------------------------------------------------------------------- 1 | /*! 2 | * Bootstrap Table of Contents v0.4.1 (http://afeld.github.io/bootstrap-toc/) 3 | * Copyright 2015 Aidan Feldman 4 | * Licensed under MIT (https://github.com/afeld/bootstrap-toc/blob/gh-pages/LICENSE.md) */ 5 | 6 | /* modified from https://github.com/twbs/bootstrap/blob/94b4076dd2efba9af71f0b18d4ee4b163aa9e0dd/docs/assets/css/src/docs.css#L548-L601 */ 7 | 8 | /* All levels of nav */ 9 | nav[data-toggle='toc'] .nav > li > a { 10 | display: block; 11 | padding: 4px 20px; 12 | font-size: 13px; 13 | font-weight: 500; 14 | color: #767676; 15 | } 16 | nav[data-toggle='toc'] .nav > li > a:hover, 17 | nav[data-toggle='toc'] .nav > li > a:focus { 18 | padding-left: 19px; 19 | color: #563d7c; 20 | text-decoration: none; 21 | background-color: transparent; 22 | border-left: 1px solid #563d7c; 23 | } 24 | nav[data-toggle='toc'] .nav > .active > a, 25 | nav[data-toggle='toc'] .nav > .active:hover > a, 26 | nav[data-toggle='toc'] .nav > .active:focus > a { 27 | padding-left: 18px; 28 | font-weight: bold; 29 | color: #563d7c; 30 | background-color: transparent; 31 | border-left: 2px solid #563d7c; 32 | } 33 | 34 | /* Nav: second level (shown on .active) */ 35 | nav[data-toggle='toc'] .nav .nav { 36 | display: none; /* Hide by default, but at >768px, show it */ 37 | padding-bottom: 10px; 38 | } 39 | nav[data-toggle='toc'] .nav .nav > li > a { 40 | padding-top: 1px; 41 | padding-bottom: 1px; 42 | padding-left: 30px; 43 | font-size: 12px; 44 | font-weight: normal; 45 | } 46 | nav[data-toggle='toc'] .nav .nav > li > a:hover, 47 | nav[data-toggle='toc'] .nav .nav > li > a:focus { 48 | padding-left: 29px; 49 | } 50 | nav[data-toggle='toc'] .nav .nav > .active > a, 51 | nav[data-toggle='toc'] .nav .nav > .active:hover > a, 52 | nav[data-toggle='toc'] .nav .nav > .active:focus > a { 53 | padding-left: 28px; 54 | font-weight: 500; 55 | } 56 | 57 | /* from https://github.com/twbs/bootstrap/blob/e38f066d8c203c3e032da0ff23cd2d6098ee2dd6/docs/assets/css/src/docs.css#L631-L634 */ 58 | nav[data-toggle='toc'] .nav > .active > ul { 59 | display: block; 60 | } 61 | -------------------------------------------------------------------------------- /docs/bootstrap-toc.js: -------------------------------------------------------------------------------- 1 | /*! 2 | * Bootstrap Table of Contents v0.4.1 (http://afeld.github.io/bootstrap-toc/) 3 | * Copyright 2015 Aidan Feldman 4 | * Licensed under MIT (https://github.com/afeld/bootstrap-toc/blob/gh-pages/LICENSE.md) */ 5 | (function() { 6 | 'use strict'; 7 | 8 | window.Toc = { 9 | helpers: { 10 | // return all matching elements in the set, or their descendants 11 | findOrFilter: function($el, selector) { 12 | // http://danielnouri.org/notes/2011/03/14/a-jquery-find-that-also-finds-the-root-element/ 13 | // http://stackoverflow.com/a/12731439/358804 14 | var $descendants = $el.find(selector); 15 | return $el.filter(selector).add($descendants).filter(':not([data-toc-skip])'); 16 | }, 17 | 18 | generateUniqueIdBase: function(el) { 19 | var text = $(el).text(); 20 | var anchor = text.trim().toLowerCase().replace(/[^A-Za-z0-9]+/g, '-'); 21 | return anchor || el.tagName.toLowerCase(); 22 | }, 23 | 24 | generateUniqueId: function(el) { 25 | var anchorBase = this.generateUniqueIdBase(el); 26 | for (var i = 0; ; i++) { 27 | var anchor = anchorBase; 28 | if (i > 0) { 29 | // add suffix 30 | anchor += '-' + i; 31 | } 32 | // check if ID already exists 33 | if (!document.getElementById(anchor)) { 34 | return anchor; 35 | } 36 | } 37 | }, 38 | 39 | generateAnchor: function(el) { 40 | if (el.id) { 41 | return el.id; 42 | } else { 43 | var anchor = this.generateUniqueId(el); 44 | el.id = anchor; 45 | return anchor; 46 | } 47 | }, 48 | 49 | createNavList: function() { 50 | return $(''); 51 | }, 52 | 53 | createChildNavList: function($parent) { 54 | var $childList = this.createNavList(); 55 | $parent.append($childList); 56 | return $childList; 57 | }, 58 | 59 | generateNavEl: function(anchor, text) { 60 | var $a = $(''); 61 | $a.attr('href', '#' + anchor); 62 | $a.text(text); 63 | var $li = $('
  • '); 64 | $li.append($a); 65 | return $li; 66 | }, 67 | 68 | generateNavItem: function(headingEl) { 69 | var anchor = this.generateAnchor(headingEl); 70 | var $heading = $(headingEl); 71 | var text = $heading.data('toc-text') || $heading.text(); 72 | return this.generateNavEl(anchor, text); 73 | }, 74 | 75 | // Find the first heading level (`

    `, then `

    `, etc.) that has more than one element. Defaults to 1 (for `

    `). 76 | getTopLevel: function($scope) { 77 | for (var i = 1; i <= 6; i++) { 78 | var $headings = this.findOrFilter($scope, 'h' + i); 79 | if ($headings.length > 1) { 80 | return i; 81 | } 82 | } 83 | 84 | return 1; 85 | }, 86 | 87 | // returns the elements for the top level, and the next below it 88 | getHeadings: function($scope, topLevel) { 89 | var topSelector = 'h' + topLevel; 90 | 91 | var secondaryLevel = topLevel + 1; 92 | var secondarySelector = 'h' + secondaryLevel; 93 | 94 | return this.findOrFilter($scope, topSelector + ',' + secondarySelector); 95 | }, 96 | 97 | getNavLevel: function(el) { 98 | return parseInt(el.tagName.charAt(1), 10); 99 | }, 100 | 101 | populateNav: function($topContext, topLevel, $headings) { 102 | var $context = $topContext; 103 | var $prevNav; 104 | 105 | var helpers = this; 106 | $headings.each(function(i, el) { 107 | var $newNav = helpers.generateNavItem(el); 108 | var navLevel = helpers.getNavLevel(el); 109 | 110 | // determine the proper $context 111 | if (navLevel === topLevel) { 112 | // use top level 113 | $context = $topContext; 114 | } else if ($prevNav && $context === $topContext) { 115 | // create a new level of the tree and switch to it 116 | $context = helpers.createChildNavList($prevNav); 117 | } // else use the current $context 118 | 119 | $context.append($newNav); 120 | 121 | $prevNav = $newNav; 122 | }); 123 | }, 124 | 125 | parseOps: function(arg) { 126 | var opts; 127 | if (arg.jquery) { 128 | opts = { 129 | $nav: arg 130 | }; 131 | } else { 132 | opts = arg; 133 | } 134 | opts.$scope = opts.$scope || $(document.body); 135 | return opts; 136 | } 137 | }, 138 | 139 | // accepts a jQuery object, or an options object 140 | init: function(opts) { 141 | opts = this.helpers.parseOps(opts); 142 | 143 | // ensure that the data attribute is in place for styling 144 | opts.$nav.attr('data-toggle', 'toc'); 145 | 146 | var $topContext = this.helpers.createChildNavList(opts.$nav); 147 | var topLevel = this.helpers.getTopLevel(opts.$scope); 148 | var $headings = this.helpers.getHeadings(opts.$scope, topLevel); 149 | this.helpers.populateNav($topContext, topLevel, $headings); 150 | } 151 | }; 152 | 153 | $(function() { 154 | $('nav[data-toggle="toc"]').each(function(i, el) { 155 | var $nav = $(el); 156 | Toc.init($nav); 157 | }); 158 | }); 159 | })(); 160 | -------------------------------------------------------------------------------- /docs/docsearch.css: -------------------------------------------------------------------------------- 1 | /* Docsearch -------------------------------------------------------------- */ 2 | /* 3 | Source: https://github.com/algolia/docsearch/ 4 | License: MIT 5 | */ 6 | 7 | .algolia-autocomplete { 8 | display: block; 9 | -webkit-box-flex: 1; 10 | -ms-flex: 1; 11 | flex: 1 12 | } 13 | 14 | .algolia-autocomplete .ds-dropdown-menu { 15 | width: 100%; 16 | min-width: none; 17 | max-width: none; 18 | padding: .75rem 0; 19 | background-color: #fff; 20 | background-clip: padding-box; 21 | border: 1px solid rgba(0, 0, 0, .1); 22 | box-shadow: 0 .5rem 1rem rgba(0, 0, 0, .175); 23 | } 24 | 25 | @media (min-width:768px) { 26 | .algolia-autocomplete .ds-dropdown-menu { 27 | width: 175% 28 | } 29 | } 30 | 31 | .algolia-autocomplete .ds-dropdown-menu::before { 32 | display: none 33 | } 34 | 35 | .algolia-autocomplete .ds-dropdown-menu [class^=ds-dataset-] { 36 | padding: 0; 37 | background-color: rgb(255,255,255); 38 | border: 0; 39 | max-height: 80vh; 40 | } 41 | 42 | .algolia-autocomplete .ds-dropdown-menu .ds-suggestions { 43 | margin-top: 0 44 | } 45 | 46 | .algolia-autocomplete .algolia-docsearch-suggestion { 47 | padding: 0; 48 | overflow: visible 49 | } 50 | 51 | .algolia-autocomplete .algolia-docsearch-suggestion--category-header { 52 | padding: .125rem 1rem; 53 | margin-top: 0; 54 | font-size: 1.3em; 55 | font-weight: 500; 56 | color: #00008B; 57 | border-bottom: 0 58 | } 59 | 60 | .algolia-autocomplete .algolia-docsearch-suggestion--wrapper { 61 | float: none; 62 | padding-top: 0 63 | } 64 | 65 | .algolia-autocomplete .algolia-docsearch-suggestion--subcategory-column { 66 | float: none; 67 | width: auto; 68 | padding: 0; 69 | text-align: left 70 | } 71 | 72 | .algolia-autocomplete .algolia-docsearch-suggestion--content { 73 | float: none; 74 | width: auto; 75 | padding: 0 76 | } 77 | 78 | .algolia-autocomplete .algolia-docsearch-suggestion--content::before { 79 | display: none 80 | } 81 | 82 | .algolia-autocomplete .ds-suggestion:not(:first-child) .algolia-docsearch-suggestion--category-header { 83 | padding-top: .75rem; 84 | margin-top: .75rem; 85 | border-top: 1px solid rgba(0, 0, 0, .1) 86 | } 87 | 88 | .algolia-autocomplete .ds-suggestion .algolia-docsearch-suggestion--subcategory-column { 89 | display: block; 90 | padding: .1rem 1rem; 91 | margin-bottom: 0.1; 92 | font-size: 1.0em; 93 | font-weight: 400 94 | /* display: none */ 95 | } 96 | 97 | .algolia-autocomplete .algolia-docsearch-suggestion--title { 98 | display: block; 99 | padding: .25rem 1rem; 100 | margin-bottom: 0; 101 | font-size: 0.9em; 102 | font-weight: 400 103 | } 104 | 105 | .algolia-autocomplete .algolia-docsearch-suggestion--text { 106 | padding: 0 1rem .5rem; 107 | margin-top: -.25rem; 108 | font-size: 0.8em; 109 | font-weight: 400; 110 | line-height: 1.25 111 | } 112 | 113 | .algolia-autocomplete .algolia-docsearch-footer { 114 | width: 110px; 115 | height: 20px; 116 | z-index: 3; 117 | margin-top: 10.66667px; 118 | float: right; 119 | font-size: 0; 120 | line-height: 0; 121 | } 122 | 123 | .algolia-autocomplete .algolia-docsearch-footer--logo { 124 | background-image: url("data:image/svg+xml;utf8,"); 125 | background-repeat: no-repeat; 126 | background-position: 50%; 127 | background-size: 100%; 128 | overflow: hidden; 129 | text-indent: -9000px; 130 | width: 100%; 131 | height: 100%; 132 | display: block; 133 | transform: translate(-8px); 134 | } 135 | 136 | .algolia-autocomplete .algolia-docsearch-suggestion--highlight { 137 | color: #FF8C00; 138 | background: rgba(232, 189, 54, 0.1) 139 | } 140 | 141 | 142 | .algolia-autocomplete .algolia-docsearch-suggestion--text .algolia-docsearch-suggestion--highlight { 143 | box-shadow: inset 0 -2px 0 0 rgba(105, 105, 105, .5) 144 | } 145 | 146 | .algolia-autocomplete .ds-suggestion.ds-cursor .algolia-docsearch-suggestion--content { 147 | background-color: rgba(192, 192, 192, .15) 148 | } 149 | -------------------------------------------------------------------------------- /docs/docsearch.js: -------------------------------------------------------------------------------- 1 | $(function() { 2 | 3 | // register a handler to move the focus to the search bar 4 | // upon pressing shift + "/" (i.e. "?") 5 | $(document).on('keydown', function(e) { 6 | if (e.shiftKey && e.keyCode == 191) { 7 | e.preventDefault(); 8 | $("#search-input").focus(); 9 | } 10 | }); 11 | 12 | $(document).ready(function() { 13 | // do keyword highlighting 14 | /* modified from https://jsfiddle.net/julmot/bL6bb5oo/ */ 15 | var mark = function() { 16 | 17 | var referrer = document.URL ; 18 | var paramKey = "q" ; 19 | 20 | if (referrer.indexOf("?") !== -1) { 21 | var qs = referrer.substr(referrer.indexOf('?') + 1); 22 | var qs_noanchor = qs.split('#')[0]; 23 | var qsa = qs_noanchor.split('&'); 24 | var keyword = ""; 25 | 26 | for (var i = 0; i < qsa.length; i++) { 27 | var currentParam = qsa[i].split('='); 28 | 29 | if (currentParam.length !== 2) { 30 | continue; 31 | } 32 | 33 | if (currentParam[0] == paramKey) { 34 | keyword = decodeURIComponent(currentParam[1].replace(/\+/g, "%20")); 35 | } 36 | } 37 | 38 | if (keyword !== "") { 39 | $(".contents").unmark({ 40 | done: function() { 41 | $(".contents").mark(keyword); 42 | } 43 | }); 44 | } 45 | } 46 | }; 47 | 48 | mark(); 49 | }); 50 | }); 51 | 52 | /* Search term highlighting ------------------------------*/ 53 | 54 | function matchedWords(hit) { 55 | var words = []; 56 | 57 | var hierarchy = hit._highlightResult.hierarchy; 58 | // loop to fetch from lvl0, lvl1, etc. 59 | for (var idx in hierarchy) { 60 | words = words.concat(hierarchy[idx].matchedWords); 61 | } 62 | 63 | var content = hit._highlightResult.content; 64 | if (content) { 65 | words = words.concat(content.matchedWords); 66 | } 67 | 68 | // return unique words 69 | var words_uniq = [...new Set(words)]; 70 | return words_uniq; 71 | } 72 | 73 | function updateHitURL(hit) { 74 | 75 | var words = matchedWords(hit); 76 | var url = ""; 77 | 78 | if (hit.anchor) { 79 | url = hit.url_without_anchor + '?q=' + escape(words.join(" ")) + '#' + hit.anchor; 80 | } else { 81 | url = hit.url + '?q=' + escape(words.join(" ")); 82 | } 83 | 84 | return url; 85 | } 86 | -------------------------------------------------------------------------------- /docs/link.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | 8 | 12 | 13 | -------------------------------------------------------------------------------- /docs/pkgdown.css: -------------------------------------------------------------------------------- 1 | /* Sticky footer */ 2 | 3 | /** 4 | * Basic idea: https://philipwalton.github.io/solved-by-flexbox/demos/sticky-footer/ 5 | * Details: https://github.com/philipwalton/solved-by-flexbox/blob/master/assets/css/components/site.css 6 | * 7 | * .Site -> body > .container 8 | * .Site-content -> body > .container .row 9 | * .footer -> footer 10 | * 11 | * Key idea seems to be to ensure that .container and __all its parents__ 12 | * have height set to 100% 13 | * 14 | */ 15 | 16 | html, body { 17 | height: 100%; 18 | } 19 | 20 | body { 21 | position: relative; 22 | } 23 | 24 | body > .container { 25 | display: flex; 26 | height: 100%; 27 | flex-direction: column; 28 | } 29 | 30 | body > .container .row { 31 | flex: 1 0 auto; 32 | } 33 | 34 | footer { 35 | margin-top: 45px; 36 | padding: 35px 0 36px; 37 | border-top: 1px solid #e5e5e5; 38 | color: #666; 39 | display: flex; 40 | flex-shrink: 0; 41 | } 42 | footer p { 43 | margin-bottom: 0; 44 | } 45 | footer div { 46 | flex: 1; 47 | } 48 | footer .pkgdown { 49 | text-align: right; 50 | } 51 | footer p { 52 | margin-bottom: 0; 53 | } 54 | 55 | img.icon { 56 | float: right; 57 | } 58 | 59 | /* Ensure in-page images don't run outside their container */ 60 | .contents img { 61 | max-width: 100%; 62 | height: auto; 63 | } 64 | 65 | /* Fix bug in bootstrap (only seen in firefox) */ 66 | summary { 67 | display: list-item; 68 | } 69 | 70 | /* Typographic tweaking ---------------------------------*/ 71 | 72 | .contents .page-header { 73 | margin-top: calc(-60px + 1em); 74 | } 75 | 76 | dd { 77 | margin-left: 3em; 78 | } 79 | 80 | /* Section anchors ---------------------------------*/ 81 | 82 | a.anchor { 83 | display: none; 84 | margin-left: 5px; 85 | width: 20px; 86 | height: 20px; 87 | 88 | background-image: url(./link.svg); 89 | background-repeat: no-repeat; 90 | background-size: 20px 20px; 91 | background-position: center center; 92 | } 93 | 94 | h1:hover .anchor, 95 | h2:hover .anchor, 96 | h3:hover .anchor, 97 | h4:hover .anchor, 98 | h5:hover .anchor, 99 | h6:hover .anchor { 100 | display: inline-block; 101 | } 102 | 103 | /* Fixes for fixed navbar --------------------------*/ 104 | 105 | .contents h1, .contents h2, .contents h3, .contents h4 { 106 | padding-top: 60px; 107 | margin-top: -40px; 108 | } 109 | 110 | /* Navbar submenu --------------------------*/ 111 | 112 | .dropdown-submenu { 113 | position: relative; 114 | } 115 | 116 | .dropdown-submenu>.dropdown-menu { 117 | top: 0; 118 | left: 100%; 119 | margin-top: -6px; 120 | margin-left: -1px; 121 | border-radius: 0 6px 6px 6px; 122 | } 123 | 124 | .dropdown-submenu:hover>.dropdown-menu { 125 | display: block; 126 | } 127 | 128 | .dropdown-submenu>a:after { 129 | display: block; 130 | content: " "; 131 | float: right; 132 | width: 0; 133 | height: 0; 134 | border-color: transparent; 135 | border-style: solid; 136 | border-width: 5px 0 5px 5px; 137 | border-left-color: #cccccc; 138 | margin-top: 5px; 139 | margin-right: -10px; 140 | } 141 | 142 | .dropdown-submenu:hover>a:after { 143 | border-left-color: #ffffff; 144 | } 145 | 146 | .dropdown-submenu.pull-left { 147 | float: none; 148 | } 149 | 150 | .dropdown-submenu.pull-left>.dropdown-menu { 151 | left: -100%; 152 | margin-left: 10px; 153 | border-radius: 6px 0 6px 6px; 154 | } 155 | 156 | /* Sidebar --------------------------*/ 157 | 158 | #pkgdown-sidebar { 159 | margin-top: 30px; 160 | position: -webkit-sticky; 161 | position: sticky; 162 | top: 70px; 163 | } 164 | 165 | #pkgdown-sidebar h2 { 166 | font-size: 1.5em; 167 | margin-top: 1em; 168 | } 169 | 170 | #pkgdown-sidebar h2:first-child { 171 | margin-top: 0; 172 | } 173 | 174 | #pkgdown-sidebar .list-unstyled li { 175 | margin-bottom: 0.5em; 176 | } 177 | 178 | /* bootstrap-toc tweaks ------------------------------------------------------*/ 179 | 180 | /* All levels of nav */ 181 | 182 | nav[data-toggle='toc'] .nav > li > a { 183 | padding: 4px 20px 4px 6px; 184 | font-size: 1.5rem; 185 | font-weight: 400; 186 | color: inherit; 187 | } 188 | 189 | nav[data-toggle='toc'] .nav > li > a:hover, 190 | nav[data-toggle='toc'] .nav > li > a:focus { 191 | padding-left: 5px; 192 | color: inherit; 193 | border-left: 1px solid #878787; 194 | } 195 | 196 | nav[data-toggle='toc'] .nav > .active > a, 197 | nav[data-toggle='toc'] .nav > .active:hover > a, 198 | nav[data-toggle='toc'] .nav > .active:focus > a { 199 | padding-left: 5px; 200 | font-size: 1.5rem; 201 | font-weight: 400; 202 | color: inherit; 203 | border-left: 2px solid #878787; 204 | } 205 | 206 | /* Nav: second level (shown on .active) */ 207 | 208 | nav[data-toggle='toc'] .nav .nav { 209 | display: none; /* Hide by default, but at >768px, show it */ 210 | padding-bottom: 10px; 211 | } 212 | 213 | nav[data-toggle='toc'] .nav .nav > li > a { 214 | padding-left: 16px; 215 | font-size: 1.35rem; 216 | } 217 | 218 | nav[data-toggle='toc'] .nav .nav > li > a:hover, 219 | nav[data-toggle='toc'] .nav .nav > li > a:focus { 220 | padding-left: 15px; 221 | } 222 | 223 | nav[data-toggle='toc'] .nav .nav > .active > a, 224 | nav[data-toggle='toc'] .nav .nav > .active:hover > a, 225 | nav[data-toggle='toc'] .nav .nav > .active:focus > a { 226 | padding-left: 15px; 227 | font-weight: 500; 228 | font-size: 1.35rem; 229 | } 230 | 231 | /* orcid ------------------------------------------------------------------- */ 232 | 233 | .orcid { 234 | font-size: 16px; 235 | color: #A6CE39; 236 | /* margins are required by official ORCID trademark and display guidelines */ 237 | margin-left:4px; 238 | margin-right:4px; 239 | vertical-align: middle; 240 | } 241 | 242 | /* Reference index & topics ----------------------------------------------- */ 243 | 244 | .ref-index th {font-weight: normal;} 245 | 246 | .ref-index td {vertical-align: top; min-width: 100px} 247 | .ref-index .icon {width: 40px;} 248 | .ref-index .alias {width: 40%;} 249 | .ref-index-icons .alias {width: calc(40% - 40px);} 250 | .ref-index .title {width: 60%;} 251 | 252 | .ref-arguments th {text-align: right; padding-right: 10px;} 253 | .ref-arguments th, .ref-arguments td {vertical-align: top; min-width: 100px} 254 | .ref-arguments .name {width: 20%;} 255 | .ref-arguments .desc {width: 80%;} 256 | 257 | /* Nice scrolling for wide elements --------------------------------------- */ 258 | 259 | table { 260 | display: block; 261 | overflow: auto; 262 | } 263 | 264 | /* Syntax highlighting ---------------------------------------------------- */ 265 | 266 | pre, code, pre code { 267 | background-color: #f8f8f8; 268 | color: #333; 269 | } 270 | pre, pre code { 271 | white-space: pre-wrap; 272 | word-break: break-all; 273 | overflow-wrap: break-word; 274 | } 275 | 276 | pre { 277 | border: 1px solid #eee; 278 | } 279 | 280 | pre .img, pre .r-plt { 281 | margin: 5px 0; 282 | } 283 | 284 | pre .img img, pre .r-plt img { 285 | background-color: #fff; 286 | } 287 | 288 | code a, pre a { 289 | color: #375f84; 290 | } 291 | 292 | a.sourceLine:hover { 293 | text-decoration: none; 294 | } 295 | 296 | .fl {color: #1514b5;} 297 | .fu {color: #000000;} /* function */ 298 | .ch,.st {color: #036a07;} /* string */ 299 | .kw {color: #264D66;} /* keyword */ 300 | .co {color: #888888;} /* comment */ 301 | 302 | .error {font-weight: bolder;} 303 | .warning {font-weight: bolder;} 304 | 305 | /* Clipboard --------------------------*/ 306 | 307 | .hasCopyButton { 308 | position: relative; 309 | } 310 | 311 | .btn-copy-ex { 312 | position: absolute; 313 | right: 0; 314 | top: 0; 315 | visibility: hidden; 316 | } 317 | 318 | .hasCopyButton:hover button.btn-copy-ex { 319 | visibility: visible; 320 | } 321 | 322 | /* headroom.js ------------------------ */ 323 | 324 | .headroom { 325 | will-change: transform; 326 | transition: transform 200ms linear; 327 | } 328 | .headroom--pinned { 329 | transform: translateY(0%); 330 | } 331 | .headroom--unpinned { 332 | transform: translateY(-100%); 333 | } 334 | 335 | /* mark.js ----------------------------*/ 336 | 337 | mark { 338 | background-color: rgba(255, 255, 51, 0.5); 339 | border-bottom: 2px solid rgba(255, 153, 51, 0.3); 340 | padding: 1px; 341 | } 342 | 343 | /* vertical spacing after htmlwidgets */ 344 | .html-widget { 345 | margin-bottom: 10px; 346 | } 347 | 348 | /* fontawesome ------------------------ */ 349 | 350 | .fab { 351 | font-family: "Font Awesome 5 Brands" !important; 352 | } 353 | 354 | /* don't display links in code chunks when printing */ 355 | /* source: https://stackoverflow.com/a/10781533 */ 356 | @media print { 357 | code a:link:after, code a:visited:after { 358 | content: ""; 359 | } 360 | } 361 | 362 | /* Section anchors --------------------------------- 363 | Added in pandoc 2.11: https://github.com/jgm/pandoc-templates/commit/9904bf71 364 | */ 365 | 366 | div.csl-bib-body { } 367 | div.csl-entry { 368 | clear: both; 369 | } 370 | .hanging-indent div.csl-entry { 371 | margin-left:2em; 372 | text-indent:-2em; 373 | } 374 | div.csl-left-margin { 375 | min-width:2em; 376 | float:left; 377 | } 378 | div.csl-right-inline { 379 | margin-left:2em; 380 | padding-left:1em; 381 | } 382 | div.csl-indent { 383 | margin-left: 2em; 384 | } 385 | -------------------------------------------------------------------------------- /docs/pkgdown.js: -------------------------------------------------------------------------------- 1 | /* http://gregfranko.com/blog/jquery-best-practices/ */ 2 | (function($) { 3 | $(function() { 4 | 5 | $('nav.navbar').headroom(); 6 | 7 | Toc.init({ 8 | $nav: $("#toc"), 9 | $scope: $("main h2, main h3, main h4, main h5, main h6") 10 | }); 11 | 12 | if ($('#toc').length) { 13 | $('body').scrollspy({ 14 | target: '#toc', 15 | offset: $("nav.navbar").outerHeight() + 1 16 | }); 17 | } 18 | 19 | // Activate popovers 20 | $('[data-bs-toggle="popover"]').popover({ 21 | container: 'body', 22 | html: true, 23 | trigger: 'focus', 24 | placement: "top", 25 | sanitize: false, 26 | }); 27 | 28 | $('[data-bs-toggle="tooltip"]').tooltip(); 29 | 30 | /* Clipboard --------------------------*/ 31 | 32 | function changeTooltipMessage(element, msg) { 33 | var tooltipOriginalTitle=element.getAttribute('data-bs-original-title'); 34 | element.setAttribute('data-bs-original-title', msg); 35 | $(element).tooltip('show'); 36 | element.setAttribute('data-bs-original-title', tooltipOriginalTitle); 37 | } 38 | 39 | if(ClipboardJS.isSupported()) { 40 | $(document).ready(function() { 41 | var copyButton = ""; 42 | 43 | $("div.sourceCode").addClass("hasCopyButton"); 44 | 45 | // Insert copy buttons: 46 | $(copyButton).prependTo(".hasCopyButton"); 47 | 48 | // Initialize tooltips: 49 | $('.btn-copy-ex').tooltip({container: 'body'}); 50 | 51 | // Initialize clipboard: 52 | var clipboard = new ClipboardJS('[data-clipboard-copy]', { 53 | text: function(trigger) { 54 | return trigger.parentNode.textContent.replace(/\n#>[^\n]*/g, ""); 55 | } 56 | }); 57 | 58 | clipboard.on('success', function(e) { 59 | changeTooltipMessage(e.trigger, 'Copied!'); 60 | e.clearSelection(); 61 | }); 62 | 63 | clipboard.on('error', function(e) { 64 | changeTooltipMessage(e.trigger,'Press Ctrl+C or Command+C to copy'); 65 | }); 66 | 67 | }); 68 | } 69 | 70 | /* Search marking --------------------------*/ 71 | var url = new URL(window.location.href); 72 | var toMark = url.searchParams.get("q"); 73 | var mark = new Mark("main#main"); 74 | if (toMark) { 75 | mark.mark(toMark, { 76 | accuracy: { 77 | value: "complementary", 78 | limiters: [",", ".", ":", "/"], 79 | } 80 | }); 81 | } 82 | 83 | /* Search --------------------------*/ 84 | /* Adapted from https://github.com/rstudio/bookdown/blob/2d692ba4b61f1e466c92e78fd712b0ab08c11d31/inst/resources/bs4_book/bs4_book.js#L25 */ 85 | // Initialise search index on focus 86 | var fuse; 87 | $("#search-input").focus(async function(e) { 88 | if (fuse) { 89 | return; 90 | } 91 | 92 | $(e.target).addClass("loading"); 93 | var response = await fetch($("#search-input").data("search-index")); 94 | var data = await response.json(); 95 | 96 | var options = { 97 | keys: ["what", "text", "code"], 98 | ignoreLocation: true, 99 | threshold: 0.1, 100 | includeMatches: true, 101 | includeScore: true, 102 | }; 103 | fuse = new Fuse(data, options); 104 | 105 | $(e.target).removeClass("loading"); 106 | }); 107 | 108 | // Use algolia autocomplete 109 | var options = { 110 | autoselect: true, 111 | debug: true, 112 | hint: false, 113 | minLength: 2, 114 | }; 115 | var q; 116 | async function searchFuse(query, callback) { 117 | await fuse; 118 | 119 | var items; 120 | if (!fuse) { 121 | items = []; 122 | } else { 123 | q = query; 124 | var results = fuse.search(query, { limit: 20 }); 125 | items = results 126 | .filter((x) => x.score <= 0.75) 127 | .map((x) => x.item); 128 | if (items.length === 0) { 129 | items = [{dir:"Sorry 😿",previous_headings:"",title:"No results found.",what:"No results found.",path:window.location.href}]; 130 | } 131 | } 132 | callback(items); 133 | } 134 | $("#search-input").autocomplete(options, [ 135 | { 136 | name: "content", 137 | source: searchFuse, 138 | templates: { 139 | suggestion: (s) => { 140 | if (s.title == s.what) { 141 | return `${s.dir} >
    ${s.title}
    `; 142 | } else if (s.previous_headings == "") { 143 | return `${s.dir} >
    ${s.title}
    > ${s.what}`; 144 | } else { 145 | return `${s.dir} >
    ${s.title}
    > ${s.previous_headings} > ${s.what}`; 146 | } 147 | }, 148 | }, 149 | }, 150 | ]).on('autocomplete:selected', function(event, s) { 151 | window.location.href = s.path + "?q=" + q + "#" + s.id; 152 | }); 153 | }); 154 | })(window.jQuery || window.$) 155 | 156 | document.addEventListener('keydown', function(event) { 157 | // Check if the pressed key is '/' 158 | if (event.key === '/') { 159 | event.preventDefault(); // Prevent any default action associated with the '/' key 160 | document.getElementById('search-input').focus(); // Set focus to the search input 161 | } 162 | }); 163 | -------------------------------------------------------------------------------- /docs/pkgdown.yml: -------------------------------------------------------------------------------- 1 | pandoc: '3.2' 2 | pkgdown: 2.1.3 3 | pkgdown_sha: ~ 4 | articles: {} 5 | last_built: 2025-07-02T13:25Z 6 | urls: 7 | reference: https://mpidr.github.io/rsocsim/reference 8 | article: https://mpidr.github.io/rsocsim/articles 9 | -------------------------------------------------------------------------------- /docs/reference/Rplot001.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MPIDR/rsocsim/28ff018137b6543ee637c9770a388ae8ee7d30ef/docs/reference/Rplot001.png -------------------------------------------------------------------------------- /docs/reference/create_simulation_folder.html: -------------------------------------------------------------------------------- 1 | 2 | Create a directory structure for the simulation — create_simulation_folder • rsocsim 9 | Skip to contents 10 | 11 | 12 |
    34 |
    35 |
    41 | 42 |
    43 |

    Create a two-level directory structure. If the first-level argument is NULL, 44 | we look for and, if needed, created the directory 'socsim' in the user's 45 | home directory. If the second-level argument is NULL, we create a directory 46 | named 'socsim_sim_some random component' in the first-level directory.

    47 |
    48 | 49 |
    50 |

    Usage

    51 |
    create_simulation_folder(basedir = NULL, simdir = NULL)
    52 |
    53 | 54 |
    55 |

    Arguments

    56 | 57 | 58 |
    basedir
    59 |

    A string. Optional. First-level directory where the 60 | simulation-specific directory will be created. Defaults to '$HOME/socsim'.

    61 | 62 | 63 |
    simdir
    64 |

    A string. Optional. Simulation-specific directory which will 65 | be created within 'basedir'. Defaults to 'socsim_sim_' plus a random 66 | component created with tempfile().

    67 | 68 |
    69 |
    70 |

    Value

    71 |

    A string. The full path to the simulation-specific directory.

    72 |
    73 | 74 |
    76 | 77 | 78 |
    81 | 82 | 85 | 86 |
    87 | 88 | 89 | 90 | 91 | 92 | 93 | 94 | -------------------------------------------------------------------------------- /docs/reference/create_sup_file.html: -------------------------------------------------------------------------------- 1 | 2 | Create a basic .sup file for a simulation — create_sup_file • rsocsim 5 | Skip to contents 6 | 7 | 8 |
    30 |
    31 |
    37 | 38 |
    39 |

    The simulation is only a simple one. The file will be saved into the 40 | directory 'simdir'.

    41 |
    42 | 43 |
    44 |

    Usage

    45 |
    create_sup_file(simdir, simname)
    46 |
    47 | 48 |
    49 |

    Arguments

    50 | 51 | 52 |
    simdir
    53 |

    A string. The directory where the .sup file will be saved.

    54 | 55 | 56 |
    simname
    57 |

    A string. The name of the simulation.

    58 | 59 |
    60 |
    61 |

    Value

    62 |

    A string. The filename of the supervisory file which is needed to 63 | start the simulation.

    64 |
    65 | 66 |
    68 | 69 | 70 |
    73 | 74 | 77 | 78 |
    79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | -------------------------------------------------------------------------------- /docs/reference/get_supplement_content.html: -------------------------------------------------------------------------------- 1 | 2 | read the content of the supplement file — get_supplement_content • rsocsim 6 | Skip to contents 7 | 8 | 9 |
    41 |
    42 |
    47 | 48 |
    49 |

    read the content of the supplement file

    50 |
    51 | 52 |
    53 |

    Usage

    54 |
    get_supplement_content(simfolder, sup_fn)
    55 |
    56 | 57 |
    58 |

    Arguments

    59 |
    simfolder
    60 |

    base folder of the simulation

    61 | 62 | 63 |
    simname
    64 |

    name of the .sup-file

    65 | 66 |
    67 |
    68 |

    Value

    69 | 70 | 71 |

    the content of the supplement file as a string (TODO: Now it 72 | returns a list of lines instead of a single string)

    73 |
    74 | 75 |
    77 | 78 | 79 |
    82 | 83 | 86 | 87 |
    88 | 89 | 90 | 91 | 92 | 93 | 94 | 95 | -------------------------------------------------------------------------------- /docs/reference/index.html: -------------------------------------------------------------------------------- 1 | 2 | Package index • rsocsim 3 | Skip to contents 4 | 5 | 6 |
    28 |
    29 |
    33 | 34 |
    35 |

    All functions

    36 | 37 | 38 | 39 | 40 |
    41 | 42 | 43 | 44 | 45 |
    46 | 47 | asYr() 48 | 49 |
    50 |
    Convert SOCSIM months to calendar years.
    51 |
    52 | 53 | census_socsim() 54 | 55 |
    56 |
    Census SOCSIM: Population counts by sex and age.
    57 |
    58 | 59 | create_initial_population() 60 | 61 |
    62 |
    Create Initial Population for Simulation
    63 |
    64 | 65 | create_simulation_folder() 66 | 67 |
    68 |
    Create a directory structure for the simulation
    69 |
    70 | 71 | create_sup_file() 72 | 73 |
    74 |
    Create a basic .sup file for a simulation
    75 |
    76 | 77 | download_rates() 78 | 79 |
    80 |
    download and convert rate files from HMD, HFD, UN
    81 |
    82 | 83 | estimate_fertility_rates() 84 | 85 |
    86 |
    Estimate yearly age-specific fertility rates (ASFR) from a SOCSIM-generated population file
    87 |
    88 | 89 | estimate_mortality_rates() 90 | 91 |
    92 |
    Estimate yearly age-specific mortality rates (ASMR) from a SOCSIM-generated population file
    93 |
    94 | 95 | get_supervisory_content() 96 | 97 |
    98 |
    Read the content of the supervisory file
    99 |
    100 | 101 | get_women_reproductive_age_socsim() 102 | 103 |
    104 |
    Get women of reproductive age from SOCSIM population data.
    105 |
    106 | 107 | jul() 108 | 109 |
    110 |
    Get simulation month corresponding to July of a given year.
    111 |
    112 | 113 | read_omar() 114 | 115 |
    116 |
    Read output marriage file into a data frame
    117 |
    118 | 119 | read_opop() 120 | 121 |
    122 |
    Read output population file into a data frame
    123 |
    124 | 125 | retrieve_kin() 126 | 127 |
    128 |
    Identify members of a kin network for an individual or individuals of interest.
    129 |
    130 | 131 | rsocsim-package rsocsim 132 | 133 |
    134 |
    SOCSIM Package for R. Run Social microsimulations directly from R.
    135 |
    136 | 137 | run1simulationwithfile_from_binary() 138 | 139 |
    140 |
    Run a single socsim-simulation with a socsim binary
    141 |
    142 | 143 | run_sim_w_file() 144 | 145 |
    146 |
    Run a single Socsim simulation.
    147 |
    148 | 149 | simulation_time_to_years() 150 | 151 |
    152 |
    Calculate for how many years the simulation ran
    153 |
    154 | 155 | socsim() 156 | 157 |
    158 |
    Run a single Socsim simulation with a given supervisory file and directory
    159 |
    160 | 161 | yearly_birth_by_age_socsim() 162 | 163 |
    164 |
    Estimate yearly number of births by mother’s age group in SOCSIM data.
    165 |
    166 |
    167 | 168 | 169 |
    172 | 173 | 176 | 177 |
    178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | -------------------------------------------------------------------------------- /docs/reference/rcpp_hello_world.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | Simple function using Rcpp — rcpp_hello_world • rsoc 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 56 | 57 | 58 | 59 | 60 | 61 | 62 |
    63 |
    64 | 98 | 99 | 100 | 101 |
    102 | 103 |
    104 |
    105 | 110 | 111 |
    112 |

    Simple function using Rcpp

    113 |
    114 | 115 |
    rcpp_hello_world()
    116 | 117 | 118 | 119 |

    Examples

    120 |
    if (FALSE) {
    121 | rcpp_hello_world()
    122 | }
    123 | 
    124 |
    125 | 130 |
    131 | 132 | 133 |
    134 | 137 | 138 |
    139 |

    Site built with pkgdown 1.6.1.

    140 |
    141 | 142 |
    143 |
    144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | -------------------------------------------------------------------------------- /docs/reference/rsoc-package.html: -------------------------------------------------------------------------------- 1 | 2 | SOCSIM Package for R. Run Social microsimulations directly from R. — rsocsim-package • rsocsim 5 | Skip to contents 6 | 7 | 8 |
    30 |
    31 |
    37 | 38 |
    39 |

    This package makes it easy to install socsim, run simulations, and 40 | read the results.

    41 |
    42 | 43 | 44 |
    45 |

    Details

    46 | 47 | 48 | 49 |
    50 |
    51 |

    Author

    52 |

    Maintainer: Tom Theile <theile@mpidr.de> and Diego Alburez-Gutierrez <alburezgutierrez@demogr.mpg.de>

    53 |
    54 |
    55 |

    References

    56 |

    This optional section can contain literature or other references for 57 | background information.

    58 |
    59 |
    60 |

    See also

    61 |
    62 |
    63 |
    64 | 65 |
    66 |

    Examples

    67 |
      if (FALSE) { # \dontrun{
    68 |      ## Optional simple examples of the most important functions
    69 |      ## These can be in \dontrun{} and \donttest{} blocks.   
    70 |   } # }
    71 | 
    72 |
    73 |
    75 | 76 | 77 |
    80 | 81 | 84 | 85 |
    86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | -------------------------------------------------------------------------------- /docs/reference/run1simulationwithfile.html: -------------------------------------------------------------------------------- 1 | 2 | Run a single socsim-simulation with a given supplement-file and folder. 3 | The results will be saved into that folder — run1simulationwithfile • rsoc 9 | 10 | 11 |
    12 |
    40 | 41 | 42 | 43 |
    44 |
    45 | 51 | 52 |
    53 |

    Run a single socsim-simulation with a given supplement-file and folder. 54 | The results will be saved into that folder

    55 |
    56 | 57 |
    58 |
    run1simulationwithfile(
     59 |   folder,
     60 |   supfile,
     61 |   seed = "42",
     62 |   process_method = "inprocess"
     63 | )
    64 |
    65 | 66 |
    67 |

    Arguments

    68 |
    folder
    69 |

    base-directory of the simulation.

    70 |
    supfile
    71 |

    the .sup file to start the simulation, relative to the 72 | folder

    73 |
    seed
    74 |

    RNG seed as string, Default="42"

    75 |
    process_method
    76 |

    specify whether and how SOCSIM should be started in its 77 | own process or in the running R process. Use one of 78 | "inprocess" - SOCSIM runs in the R-process. Beware if you run several different 79 | simulations - they may affect later simulations 80 | "future" - the safest option. A new process will be start via the "future" 81 | package 82 | "clustercall" - if the future package is not available, try this method instead

    83 |
    rootfolder
    84 |

    rootfolder...

    85 |
    86 |
    87 |

    Value

    88 |

    The results will be written into the specified folder

    89 |
    90 | 91 |
    92 | 95 |
    96 | 97 | 98 |
    102 | 103 |
    104 |

    Site built with pkgdown 105 | 2.0.2.

    106 |
    107 | 108 |
    109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | -------------------------------------------------------------------------------- /docs/reference/run1simulationwithfile_from_binary.html: -------------------------------------------------------------------------------- 1 | 2 | Run a single socsim-simulation with a socsim binary — run1simulationwithfile_from_binary • rsocsim 3 | Skip to contents 4 | 5 | 6 |
    28 |
    29 |
    35 | 36 |
    37 |

    Run a single socsim-simulation with a socsim binary

    38 |
    39 | 40 |
    41 |

    Usage

    42 |
    run1simulationwithfile_from_binary(
     43 |   folder,
     44 |   supfile,
     45 |   seed = "42",
     46 |   compatibility_mode = "1",
     47 |   socsim_path = NULL
     48 | )
    49 |
    50 | 51 |
    52 |

    Arguments

    53 | 54 | 55 |
    folder
    56 |

    base-directory of the simulation.

    57 | 58 | 59 |
    supfile
    60 |

    the .sup file to start the simulation, relative to the 61 | folder

    62 | 63 | 64 |
    seed
    65 |

    RNG seed as string, Default="42"

    66 | 67 | 68 |
    compatibility_mode
    69 |

    compatibility mode as string, Default="1"

    70 | 71 | 72 |
    socsim_path
    73 |

    path+filename of a socsim-executable. Download one from https://github.com/tomthe/socsim/releases/download/0.3/socsim.exe

    74 | 75 |
    76 |
    77 |

    Value

    78 |

    The results will be written into the specified folder

    79 |
    80 | 81 |
    83 | 84 | 85 |
    88 | 89 | 92 | 93 |
    94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | -------------------------------------------------------------------------------- /docs/reference/run1simulationwithfile_inprocess.html: -------------------------------------------------------------------------------- 1 | 2 | Run a socsim-simulation in the r-process — run1simulationwithfile_inprocess • rsocsim 6 | Skip to contents 7 | 8 | 9 |
    41 |
    42 |
    47 | 48 |
    49 |

    Run a socsim-simulation in the r-process

    50 |
    51 | 52 |
    53 |

    Usage

    54 |
    run1simulationwithfile_inprocess(
     55 |   folder,
     56 |   supfile,
     57 |   seed,
     58 |   compatibility_mode = "1",
     59 |   suffix = ""
     60 | )
    61 |
    62 | 63 |
    64 |

    Arguments

    65 |
    supfile
    66 |

    the .sup file to start the simulation

    67 | 68 | 69 |
    seed
    70 |

    RNG seed

    71 | 72 | 73 |
    rootfolder
    74 |

    rootfolder name of the simulation

    75 | 76 |
    77 |
    78 |

    Value

    79 | 80 | 81 |

    The results will be written into the specified folder

    82 |
    83 | 84 |
    86 | 87 | 88 |
    91 | 92 | 95 | 96 |
    97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | -------------------------------------------------------------------------------- /docs/reference/simulation_time_to_years.html: -------------------------------------------------------------------------------- 1 | 2 | Calculate for how many years the simulation ran — simulation_time_to_years • rsocsim 3 | Skip to contents 4 | 5 | 6 |
    28 |
    29 |
    35 | 36 |
    37 |

    Calculate for how many years the simulation ran

    38 |
    39 | 40 |
    41 |

    Usage

    42 |
    simulation_time_to_years(simulation_time, pre_simulation_time, start_year)
    43 |
    44 | 45 |
    46 |

    Arguments

    47 | 48 | 49 |
    simulation_time
    50 |

    An integer. The number of periods (months) the 51 | simulation ran.

    52 | 53 | 54 |
    pre_simulation_time
    55 |

    An integer. The number of periods (months) the 56 | simulation ran before getting to a stable population. This is subtracted 57 | from 'simulation_time' in order to arrive at the "real" simulation time

    58 | 59 | 60 |
    start_year
    61 |

    An integer. The year the simulation started.

    62 | 63 |
    64 |
    65 |

    Value

    66 |

    An number. The number of years for which the simulation ran. May 67 | have a fractional part.

    68 |
    69 | 70 |
    72 | 73 | 74 |
    77 | 78 | 81 | 82 |
    83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | -------------------------------------------------------------------------------- /docs/sitemap.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | https://mpidr.github.io/rsocsim/404.html 5 | 6 | 7 | https://mpidr.github.io/rsocsim/authors.html 8 | 9 | 10 | https://mpidr.github.io/rsocsim/development.html 11 | 12 | 13 | https://mpidr.github.io/rsocsim/index.html 14 | 15 | 16 | https://mpidr.github.io/rsocsim/LICENSE.html 17 | 18 | 19 | https://mpidr.github.io/rsocsim/news/index.html 20 | 21 | 22 | https://mpidr.github.io/rsocsim/readme.html 23 | 24 | 25 | https://mpidr.github.io/rsocsim/reference/create_simulation_folder.html 26 | 27 | 28 | https://mpidr.github.io/rsocsim/reference/create_sup_file.html 29 | 30 | 31 | https://mpidr.github.io/rsocsim/reference/estimate_fertility_rates.html 32 | 33 | 34 | https://mpidr.github.io/rsocsim/reference/estimate_mortality_rates.html 35 | 36 | 37 | https://mpidr.github.io/rsocsim/reference/get_supervisory_content.html 38 | 39 | 40 | https://mpidr.github.io/rsocsim/reference/get_supplement_content.html 41 | 42 | 43 | https://mpidr.github.io/rsocsim/reference/index.html 44 | 45 | 46 | https://mpidr.github.io/rsocsim/reference/rcpp_hello_world.html 47 | 48 | 49 | https://mpidr.github.io/rsocsim/reference/read_omar.html 50 | 51 | 52 | https://mpidr.github.io/rsocsim/reference/read_opop.html 53 | 54 | 55 | https://mpidr.github.io/rsocsim/reference/retrieve_kin.html 56 | 57 | 58 | https://mpidr.github.io/rsocsim/reference/rsoc-package.html 59 | 60 | 61 | https://mpidr.github.io/rsocsim/reference/run1simulationwithfile.html 62 | 63 | 64 | https://mpidr.github.io/rsocsim/reference/run1simulationwithfile_from_binary.html 65 | 66 | 67 | https://mpidr.github.io/rsocsim/reference/run1simulationwithfile_inprocess.html 68 | 69 | 70 | https://mpidr.github.io/rsocsim/reference/simulation_time_to_years.html 71 | 72 | 73 | https://mpidr.github.io/rsocsim/reference/socsim.html 74 | 75 | 76 | https://mpidr.github.io/rsocsim/socsim_oversimplified.html 77 | 78 | 79 | -------------------------------------------------------------------------------- /future_documentation.md: -------------------------------------------------------------------------------- 1 | # Socsim less simplified 2 | 3 | ## Stuff to add to Socsim Oversimplified 4 | 5 | ### New functionality of c socsim 6 | 7 | #### Write intermediate output files: 8 | 9 | Add this line to your sup-file: 10 | `write_output 1` 11 | 12 | 13 | ### New functionality of R code 14 | 15 | * download_rates 16 | * create_initial_population -------------------------------------------------------------------------------- /inst/extdata/SWEfert2022: -------------------------------------------------------------------------------- 1 | *Period fertility rates for SWE in 2022 2 | * Mon Dec 20 14:21:54 2010 3 | birth 1 F married 0 4 | 1 0 0 5 | 2 0 0 6 | 3 0 0 7 | 4 0 0 8 | 5 0 0 9 | 6 0 0 10 | 7 0 0 11 | 8 0 0 12 | 9 0 0 13 | 10 0 0 14 | 11 0 0 15 | 12 0 0 16 | 13 0 0 17 | 14 0 0 18 | 15 0 0.0000121580833333333 19 | 16 0 0.0000677991666666667 20 | 17 0 0.000210484083333333 21 | 18 0 0.000414651166666667 22 | 19 0 0.000866806583333333 23 | 20 0 0.00156010816666667 24 | 21 0 0.00253334408333333 25 | 22 0 0.00328222925 26 | 23 0 0.00417582333333333 27 | 24 0 0.00516225558333333 28 | 25 0 0.00626294441666667 29 | 26 0 0.00742211816666667 30 | 27 0 0.00865184341666667 31 | 28 0 0.00993853308333333 32 | 29 0 0.0109669800833333 33 | 30 0 0.011959903 34 | 31 0 0.012040219 35 | 32 0 0.011839596 36 | 33 0 0.010978106 37 | 34 0 0.00991917491666667 38 | 35 0 0.00874326725 39 | 36 0 0.00717917116666667 40 | 37 0 0.005868357 41 | 38 0 0.0046696 42 | 39 0 0.00355931941666667 43 | 40 0 0.00259080875 44 | 41 0 0.00171299258333333 45 | 42 0 0.00114608391666667 46 | 43 0 0.00064995475 47 | 44 0 0.00031994625 48 | 45 0 0.00014344 49 | 46 0 0.000079271 50 | 47 0 0.0000276439166666667 51 | 48 0 0.00001276525 52 | 49 0 0.00000719166666666667 53 | 50 0 0 54 | 51 0 0 55 | 52 0 0 56 | 53 0 0 57 | 54 0 0 58 | 55 0 0 59 | 56 0 0 60 | 57 0 0 61 | 58 0 0 62 | 59 0 0 63 | 60 0 0 64 | 61 0 0 65 | 62 0 0 66 | 63 0 0 67 | 64 0 0 68 | 65 0 0 69 | 66 0 0 70 | 67 0 0 71 | 68 0 0 72 | 69 0 0 73 | 70 0 0 74 | 71 0 0 75 | 72 0 0 76 | 73 0 0 77 | 74 0 0 78 | 75 0 0 79 | 76 0 0 80 | 77 0 0 81 | 78 0 0 82 | 79 0 0 83 | 80 0 0 84 | 81 0 0 85 | 82 0 0 86 | 83 0 0 87 | 84 0 0 88 | 85 0 0 89 | 86 0 0 90 | 87 0 0 91 | 88 0 0 92 | 89 0 0 93 | 90 0 0 94 | 91 0 0 95 | 92 0 0 96 | 93 0 0 97 | 94 0 0 98 | 95 0 0 99 | 96 0 0 100 | 97 0 0 101 | 98 0 0 102 | 99 0 0 103 | 100 0 0 104 | 105 | birth 1 F single 0 106 | 1 0 0 107 | 2 0 0 108 | 3 0 0 109 | 4 0 0 110 | 5 0 0 111 | 6 0 0 112 | 7 0 0 113 | 8 0 0 114 | 9 0 0 115 | 10 0 0 116 | 11 0 0 117 | 12 0 0 118 | 13 0 0 119 | 14 0 0 120 | 15 0 0.0000121580833333333 121 | 16 0 0.0000677991666666667 122 | 17 0 0.000210484083333333 123 | 18 0 0.000414651166666667 124 | 19 0 0.000866806583333333 125 | 20 0 0.00156010816666667 126 | 21 0 0.00253334408333333 127 | 22 0 0.00328222925 128 | 23 0 0.00417582333333333 129 | 24 0 0.00516225558333333 130 | 25 0 0.00626294441666667 131 | 26 0 0.00742211816666667 132 | 27 0 0.00865184341666667 133 | 28 0 0.00993853308333333 134 | 29 0 0.0109669800833333 135 | 30 0 0.011959903 136 | 31 0 0.012040219 137 | 32 0 0.011839596 138 | 33 0 0.010978106 139 | 34 0 0.00991917491666667 140 | 35 0 0.00874326725 141 | 36 0 0.00717917116666667 142 | 37 0 0.005868357 143 | 38 0 0.0046696 144 | 39 0 0.00355931941666667 145 | 40 0 0.00259080875 146 | 41 0 0.00171299258333333 147 | 42 0 0.00114608391666667 148 | 43 0 0.00064995475 149 | 44 0 0.00031994625 150 | 45 0 0.00014344 151 | 46 0 0.000079271 152 | 47 0 0.0000276439166666667 153 | 48 0 0.00001276525 154 | 49 0 0.00000719166666666667 155 | 50 0 0 156 | 51 0 0 157 | 52 0 0 158 | 53 0 0 159 | 54 0 0 160 | 55 0 0 161 | 56 0 0 162 | 57 0 0 163 | 58 0 0 164 | 59 0 0 165 | 60 0 0 166 | 61 0 0 167 | 62 0 0 168 | 63 0 0 169 | 64 0 0 170 | 65 0 0 171 | 66 0 0 172 | 67 0 0 173 | 68 0 0 174 | 69 0 0 175 | 70 0 0 176 | 71 0 0 177 | 72 0 0 178 | 73 0 0 179 | 74 0 0 180 | 75 0 0 181 | 76 0 0 182 | 77 0 0 183 | 78 0 0 184 | 79 0 0 185 | 80 0 0 186 | 81 0 0 187 | 82 0 0 188 | 83 0 0 189 | 84 0 0 190 | 85 0 0 191 | 86 0 0 192 | 87 0 0 193 | 88 0 0 194 | 89 0 0 195 | 90 0 0 196 | 91 0 0 197 | 92 0 0 198 | 93 0 0 199 | 94 0 0 200 | 95 0 0 201 | 96 0 0 202 | 97 0 0 203 | 98 0 0 204 | 99 0 0 205 | 100 0 0 206 | -------------------------------------------------------------------------------- /man/create_simulation_folder.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/startsocsim.R 3 | \name{create_simulation_folder} 4 | \alias{create_simulation_folder} 5 | \title{Create a directory structure for the simulation} 6 | \usage{ 7 | create_simulation_folder(basedir = NULL, simdir = NULL) 8 | } 9 | \arguments{ 10 | \item{basedir}{A string. Optional. First-level directory where the 11 | simulation-specific directory will be created. Defaults to '$HOME/socsim'.} 12 | 13 | \item{simdir}{A string. Optional. Simulation-specific directory which will 14 | be created within 'basedir'. Defaults to 'socsim_sim_' plus a random 15 | component created with \code{\link[=tempfile]{tempfile()}}.} 16 | } 17 | \value{ 18 | A string. The full path to the simulation-specific directory. 19 | } 20 | \description{ 21 | Create a two-level directory structure. If the first-level argument is NULL, 22 | we look for and, if needed, created the directory 'socsim' in the user's 23 | home directory. If the second-level argument is NULL, we create a directory 24 | named 'socsim_sim_{some random component}' in the first-level directory. 25 | } 26 | -------------------------------------------------------------------------------- /man/create_sup_file.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/startsocsim.R 3 | \name{create_sup_file} 4 | \alias{create_sup_file} 5 | \title{Create a basic .sup file for a simulation} 6 | \usage{ 7 | create_sup_file(simdir, simname) 8 | } 9 | \arguments{ 10 | \item{simdir}{A string. The directory where the .sup file will be saved.} 11 | 12 | \item{simname}{A string. The name of the simulation.} 13 | } 14 | \value{ 15 | A string. The filename of the supervisory file which is needed to 16 | start the simulation. 17 | } 18 | \description{ 19 | The simulation is only a simple one. The file will be saved into the 20 | directory 'simdir'. 21 | } 22 | -------------------------------------------------------------------------------- /man/estimate_fertility_rates.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/estimate_rates.R 3 | \name{estimate_fertility_rates} 4 | \alias{estimate_fertility_rates} 5 | \title{Estimate yearly age-specific fertility rates (ASFR) from a SOCSIM-generated 6 | population file} 7 | \usage{ 8 | estimate_fertility_rates( 9 | opop, 10 | final_sim_year, 11 | year_min, 12 | year_max, 13 | year_group = 5, 14 | age_min_fert = 15, 15 | age_max_fert = 50, 16 | age_group = 5 17 | ) 18 | } 19 | \arguments{ 20 | \item{opop}{An R object from SOCSIM microsimulation output (population file).} 21 | 22 | \item{final_sim_year}{numeric. Final simulated year in 'real world' time ( 23 | used to convert 'SOCSIM time' to 'real world' time.)} 24 | 25 | \item{year_min}{numeric. Lower-bound year for which rate should be estimated.} 26 | 27 | \item{year_max}{numeric. Upper-bound year for which rate should be estimated.} 28 | 29 | \item{year_group}{numeric. Size of year groups to estimate rate (year_group=1 30 | will produce single-year estimates)} 31 | 32 | \item{age_min_fert}{numeric. Lower-bound age of female reproductive period} 33 | 34 | \item{age_max_fert}{numeric. Upper-bound age of female reproductive period} 35 | 36 | \item{age_group}{numeric. Size of age groups to estimate rate (age_group=1 37 | will produce single-age estimates)} 38 | } 39 | \value{ 40 | A data.frame with age-specific fertility rates by year and age. 41 | } 42 | \description{ 43 | Given a population file ('opop') generated by rsocsim, the 44 | function estimates age-specific fertility rates. 45 | } 46 | \details{ 47 | The \code{final_sim_year} can be obtained from the .sup file and must 48 | refer to to a real-world year. 49 | 50 | Grouped year and age ranges (i.e., if \code{year_group > 1} or \code{age_group > 1}) 51 | are created as [year;year+year_group). 52 | } 53 | \examples{ 54 | \dontrun{ 55 | # Read opop file into global environment 56 | opop <- read_opop(path = "my_path") 57 | # Retrieve age-specific fertility rates 58 | asfr <- get_asfr_socsim(opop = opop, 59 | final_sim_year = 2021, 60 | year_min = 1750, 61 | year_max = 2020, 62 | year_group = 5, 63 | age_min_fert = 10, 64 | age_max_fert = 55, 65 | age_group = 5) 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /man/estimate_mortality_rates.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/estimate_rates.R 3 | \name{estimate_mortality_rates} 4 | \alias{estimate_mortality_rates} 5 | \title{Estimate yearly age-specific mortality rates (ASMR) from a SOCSIM-generated 6 | population file} 7 | \usage{ 8 | estimate_mortality_rates( 9 | opop, 10 | final_sim_year, 11 | year_min, 12 | year_max, 13 | year_group, 14 | age_max_mort, 15 | age_group 16 | ) 17 | } 18 | \arguments{ 19 | \item{opop}{An R object from SOCSIM microsimulation output (population file).} 20 | 21 | \item{final_sim_year}{numeric. Final simulated year in 'real world' time ( 22 | used to convert 'SOCSIM time' to 'real world' time.)} 23 | 24 | \item{year_min}{numeric. Lower-bound year for which rate should be estimated.} 25 | 26 | \item{year_max}{numeric. Upper-bound year for which rate should be estimated.} 27 | 28 | \item{year_group}{numeric. Size of year groups to estimate rate (year_group=1 29 | will produce single-year estimates)} 30 | 31 | \item{age_max_mort}{numeric. Maximum age for estimating mortality.} 32 | 33 | \item{age_group}{numeric. Size of age groups to estimate rate (age_group=1 34 | will produce single-age estimates)} 35 | } 36 | \value{ 37 | A data.frame with yearly age-specific mortality rates by year and age. 38 | } 39 | \description{ 40 | Given a population file ('opop') generated by rsocsim, the 41 | function estimates (yearly) age-specific mortality rates. 42 | } 43 | \details{ 44 | The \code{final_sim_year} can be obtained from the .sup file and must 45 | refer to to a real-world year. 46 | 47 | Grouped year and age ranges (i.e., if \code{year_group > 1} or \code{age_group > 1}) 48 | are created as [year;year+year_group). Mortality rates always start from 0 49 | [0,0+age_group). 50 | } 51 | \examples{ 52 | \dontrun{ 53 | # Read opop file into global environment 54 | opop <- read_opop(path = "my_path") 55 | # Retrieve age-specific mortality rates 56 | asmr <- get_asmr_socsim(opop = opop, 57 | final_sim_year = 2021, 58 | year_min = 1750, 59 | year_max = 2020, 60 | year_group = 5, 61 | age_max_mort = 110, 62 | age_group = 5) 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /man/read_omar.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/read_results.R 3 | \name{read_omar} 4 | \alias{read_omar} 5 | \title{Read output marriage file into a data frame} 6 | \usage{ 7 | read_omar( 8 | folder = NULL, 9 | supfile = "socsim.sup", 10 | seed = 42, 11 | suffix = "", 12 | fn = NULL 13 | ) 14 | } 15 | \arguments{ 16 | \item{folder}{simulation base folder ("~/socsim/simulation_235/")} 17 | 18 | \item{supfile}{name of supervisory-file ("socsim.sup")} 19 | 20 | \item{seed}{random number seed (42)} 21 | 22 | \item{suffix}{optional suffix for the results-directory (default="")} 23 | 24 | \item{fn}{complete path to the file. If not provided, it will be created from the other arguments} 25 | } 26 | \value{ 27 | Data frame with the information of the output population file 28 | } 29 | \description{ 30 | \tabular{rll}{ 31 | 1 \tab mid \tab Marriage id number (unique sequential integer) \cr 32 | 2 \tab wpid \tab Wife’s person id \cr 33 | 3 \tab hpid \tab Husband’s person id \cr 34 | 4 \tab dstart \tab Date marriage began \cr 35 | 5 \tab dend \tab Date marriage ended or zero if still in force at end of simulation \cr 36 | 6 \tab rend \tab Reason marriage ended 2 = divorce; 3 = death of one partner \cr 37 | 7 \tab wprior \tab Marriage id of wife’s next most recent prior marriage \cr 38 | 8 \tab hprior \tab Marriage id of husband’s next most recent prior marriage \cr 39 | } 40 | } 41 | \details{ 42 | you can either provide the complete \code{path} to the file or the \code{folder}, supfilename, seed and suffix with which you 43 | started the simulation 44 | } 45 | -------------------------------------------------------------------------------- /man/read_opop.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/read_results.R 3 | \name{read_opop} 4 | \alias{read_opop} 5 | \title{Read output population file into a data frame} 6 | \usage{ 7 | read_opop( 8 | folder = NULL, 9 | supfile = "socsim.sup", 10 | seed = 42, 11 | suffix = "", 12 | fn = NULL 13 | ) 14 | } 15 | \arguments{ 16 | \item{folder}{simulation base folder ("~/socsim/simulation_235/")} 17 | 18 | \item{supfile}{name of supervisory-file ("socsim.sup")} 19 | 20 | \item{seed}{random number seed (42)} 21 | 22 | \item{suffix}{optional suffix for the results-directory (default="")} 23 | 24 | \item{fn}{complete path to the file. If not provided, it will be created from the other arguments} 25 | } 26 | \value{ 27 | Data frame with the information of the output population file 28 | } 29 | \description{ 30 | after the end of the simulation, socsim writes every person of the simulation into 31 | a file called result.opop | 32 | } 33 | \details{ 34 | \tabular{rll}{ 35 | 1 \tab pid \tab Person id unique identifier assigned as integer in birth order \cr 36 | 2 \tab fem \tab 1 if female 0 if male \cr 37 | 3 \tab group \tab Group identifier 1..60 current group membership of individual \cr 38 | 4 \tab nev \tab Next scheduled event \cr 39 | 5 \tab dob \tab Date of birth integer month number \cr 40 | 6 \tab mom \tab Person id of mother \cr 41 | 7 \tab pop \tab Person id of father \cr 42 | 8 \tab nesibm \tab Person id of next eldest sibling through mother \cr 43 | 9 \tab nesibp \tab Person id of next eldest sibling through father \cr 44 | 10 \tab lborn \tab Person id of last born child \cr 45 | 11 \tab marid \tab Id of marriage in .omar file \cr 46 | 12 \tab mstat \tab Marital status at end of simulation integer 1=single;2=divorced; 3=widowed; 4=married \cr 47 | 13 \tab dod \tab Date of death or 0 if alive at end of simulation \cr 48 | 14 \tab fmult \tab Fertility multiplier \cr 49 | } 50 | 51 | This table explains the columns of the opop file and the columns of the output data frame. 52 | You can either provide the complete \code{path} to the file or the \code{folder}, supfilename, seed and suffix with which you 53 | started the simulation 54 | } 55 | -------------------------------------------------------------------------------- /man/retrieve_kin.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/retrieve_kin.R 3 | \name{retrieve_kin} 4 | \alias{retrieve_kin} 5 | \title{Identify members of a kin network for an individual or individuals of 6 | interest.} 7 | \usage{ 8 | retrieve_kin( 9 | opop = opop, 10 | omar = omar, 11 | KidsOf = KidsOf, 12 | pid, 13 | extra_kintypes, 14 | kin_by_sex 15 | ) 16 | } 17 | \arguments{ 18 | \item{opop}{An R object from SOCSIM microsimulation output (population file). Create this object with the function read_opop().} 19 | 20 | \item{omar}{An R object from SOCSIM microsimulation output (marriage file). Create this object with the function read_omar().} 21 | 22 | \item{KidsOf}{A list object containing the children of each person in the 23 | population. This object is created by the function getKidsOf().} 24 | 25 | \item{pid}{A character vector of person IDs, indicating persons of interest 26 | for whom these kin networks should be identified.} 27 | 28 | \item{extra_kintypes}{A vector of character values indicating which 29 | additional types of kin should be obtained. For reasons of computational 30 | efficiency, the function will by default only identify an individual's 31 | great-grandparents ("ggparents" in function output), 32 | grandparents ("gparents"), parents, 33 | siblings, spouse, children, and grandchildren ("gchildren"). 34 | However, by selecting one or more of the following 35 | kin types, the kin network generated will also include these individuals: 36 | \itemize{ 37 | \item "gunclesaunts": Great-uncles and great-aunts 38 | \item "unclesaunts": Uncles and aunts 39 | \item "firstcousins": First cousins (Children of uncles and aunts) 40 | \item "niblings": Nieces and nephews (Children of siblings) 41 | \item "inlaws": Parents-in-law (parents of spouse) and brothers and sisters 42 | in law (siblings of spouse and spouse of siblings) 43 | }} 44 | 45 | \item{kin_by_sex}{A logical value indicating whether output should include 46 | kin relations additionally disaggregated by the sex of the relative. Setting 47 | this value to TRUE will result in additional objects being generated 48 | to identify individuals' relatives by sex.} 49 | } 50 | \value{ 51 | An R object containing a list of lists with person IDs 52 | of kin, organized by relationship. These person ID values will be named 53 | based on the person of interest with whom they are associated. 54 | For example, for a list named "parents", the values will be person IDs of 55 | the parents of individuals of interest. These values will be named according 56 | to their children's IDs (given that their children are, in this case, 57 | the persons of interest provided to the function input). 58 | With kin_by_sex set to TRUE and extra_kintypes set to c(c("gunclesaunts", 59 | "unclesaunts", "firstcousins", "niblings", "inlaws")), 60 | the full list of kin relations identified are: 61 | \itemize{ 62 | \item "ggparents": great-grandparents 63 | \item "ggmothers": great-grandmothers 64 | \item "ggfathers": great-grandfathers 65 | \item "gparents": grandparents 66 | \item "gmothers": grandmothers 67 | \item "gfathers": grandfathers 68 | \item "gunclesaunts": great-uncles and great-aunts 69 | \item "guncles": great-uncles 70 | \item "gaunts": great-aunts 71 | \item "parents": parents 72 | \item "mother": mother 73 | \item "father": father 74 | \item "unclesaunts": uncles and aunts (siblings of parents) 75 | \item "uncles": uncles 76 | \item "aunts": aunts 77 | \item "siblings": siblings 78 | \item "sisters": sisters 79 | \item "brothers": brothers 80 | \item "firstcousins": first cousins 81 | \item "firstcousinsfemale": female first cousins 82 | \item "firstcousinsmale": male first cousins 83 | \item "children": children 84 | \item "daughters": daughters 85 | \item "sons": sons 86 | \item "gchildren": grandchildren 87 | \item "gdaughters": granddaughters 88 | \item "gsons": grandsons 89 | \item "niblings": nephews and nieces 90 | \item "nieces": nieces 91 | \item "nephews": nephews 92 | \item "spouse": spouse (based on final marriage, in the case of 93 | multiple marriages) 94 | \item "parentsinlaw": parents-in-law 95 | \item "motherinlaw": mother-in-law 96 | \item "fatherinlaw": father-in-law 97 | \item "siblingsinlaw": brothers and sisters in law 98 | \item "sistersinlaw": sisters-in-law 99 | \item "brothersinlaw": brothers-in-law 100 | } 101 | } 102 | \description{ 103 | Identify members of a kin network for an individual or individuals of 104 | interest. 105 | } 106 | \examples{ 107 | \dontrun{ 108 | #Individuals of interest 109 | pid <- c("10111", "10211", "10311") 110 | #Obtain partial kinship network, with omar and opop already in R environment 111 | kin_network <- getKin(opop = opop, omar = omar, pid = pid, 112 | extra_kintypes = c("unclesaunts", "niblings"), kin_by_sex = TRUE) 113 | } 114 | 115 | } 116 | -------------------------------------------------------------------------------- /man/rsoc-package.Rd: -------------------------------------------------------------------------------- 1 | \name{rsocsim-package} 2 | \alias{rsocsim-package} 3 | \alias{rsocsim} 4 | \docType{package} 5 | \title{ 6 | SOCSIM Package for R. Run Social microsimulations directly from R. 7 | } 8 | \description{ 9 | This package makes it easy to install socsim, run simulations, and 10 | read the results. 11 | } 12 | \details{ 13 | 14 | } 15 | \author{ 16 | Maintainer: Tom Theile and Diego Alburez-Gutierrez 17 | } 18 | \references{ 19 | This optional section can contain literature or other references for 20 | background information. 21 | } 22 | \keyword{ package } 23 | \seealso{ 24 | } 25 | \examples{ 26 | \dontrun{ 27 | ## Optional simple examples of the most important functions 28 | ## These can be in \dontrun{} and \donttest{} blocks. 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /man/run1simulationwithfile_from_binary.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/startsocsim.R 3 | \name{run1simulationwithfile_from_binary} 4 | \alias{run1simulationwithfile_from_binary} 5 | \title{Run a single socsim-simulation with a socsim binary} 6 | \usage{ 7 | run1simulationwithfile_from_binary( 8 | folder, 9 | supfile, 10 | seed = "42", 11 | compatibility_mode = "1", 12 | socsim_path = NULL 13 | ) 14 | } 15 | \arguments{ 16 | \item{folder}{base-directory of the simulation.} 17 | 18 | \item{supfile}{the .sup file to start the simulation, relative to the 19 | folder} 20 | 21 | \item{seed}{RNG seed as string, Default="42"} 22 | 23 | \item{compatibility_mode}{compatibility mode as string, Default="1"} 24 | 25 | \item{socsim_path}{path+filename of a socsim-executable. Download one from https://github.com/tomthe/socsim/releases/download/0.3/socsim.exe} 26 | } 27 | \value{ 28 | The results will be written into the specified folder 29 | } 30 | \description{ 31 | Run a single socsim-simulation with a socsim binary 32 | } 33 | -------------------------------------------------------------------------------- /man/simulation_time_to_years.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/startsocsim.R 3 | \name{simulation_time_to_years} 4 | \alias{simulation_time_to_years} 5 | \title{Calculate for how many years the simulation ran} 6 | \usage{ 7 | simulation_time_to_years(simulation_time, pre_simulation_time, start_year) 8 | } 9 | \arguments{ 10 | \item{simulation_time}{An integer. The number of periods (months) the 11 | simulation ran.} 12 | 13 | \item{pre_simulation_time}{An integer. The number of periods (months) the 14 | simulation ran before getting to a stable population. This is subtracted 15 | from 'simulation_time' in order to arrive at the "real" simulation time} 16 | 17 | \item{start_year}{An integer. The year the simulation started.} 18 | } 19 | \value{ 20 | An number. The number of years for which the simulation ran. May 21 | have a fractional part. 22 | } 23 | \description{ 24 | Calculate for how many years the simulation ran 25 | } 26 | -------------------------------------------------------------------------------- /man/socsim.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/startsocsim.R 3 | \name{socsim} 4 | \alias{socsim} 5 | \title{Run a single Socsim simulation with a given supervisory file and directory} 6 | \usage{ 7 | socsim( 8 | folder, 9 | supfile, 10 | seed = "42", 11 | process_method = "inprocess", 12 | compatibility_mode = "1", 13 | suffix = "" 14 | ) 15 | } 16 | \arguments{ 17 | \item{folder}{A string. This is the base directory of the simulation. Every 18 | .sup and rate file should be named relative to this directory.} 19 | 20 | \item{supfile}{A string. The name of the .sup file to start the simulation, 21 | relative to the directory.} 22 | 23 | \item{seed}{A string. The seed for the RNG, so expects an integer. Defaults 24 | to "42".} 25 | 26 | \item{process_method}{A string. Whether and how SOCSIM should be started in 27 | its own process or in the running R process. Defaults to "inprocess". Use 28 | one of: 29 | \itemize{ 30 | \item "future" - the safest option. A new process will be started via the 31 | "future" package 32 | \item "inprocess" - SOCSIM runs in the R-process. Beware if you run several 33 | different simulations, they may affect later simulations. 34 | \item "clustercall" - if the future package is not available, try this method 35 | instead. 36 | }} 37 | 38 | \item{compatibility_mode}{A string.} 39 | 40 | \item{suffix}{A string.} 41 | } 42 | \value{ 43 | Returns the name of the directory to which the results will be 44 | written. 45 | } 46 | \description{ 47 | Run a single Socsim simulation with a given supervisory file and directory 48 | } 49 | -------------------------------------------------------------------------------- /random_number: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MPIDR/rsocsim/28ff018137b6543ee637c9770a388ae8ee7d30ef/random_number -------------------------------------------------------------------------------- /rsocsim.Rproj: -------------------------------------------------------------------------------- 1 | Version: 1.0 2 | ProjectId: e6f03911-b123-4447-a550-b5db584bc26e 3 | 4 | RestoreWorkspace: Default 5 | SaveWorkspace: Default 6 | AlwaysSaveHistory: Default 7 | 8 | EnableCodeIndexing: Yes 9 | UseSpacesForTab: Yes 10 | NumSpacesForTab: 2 11 | Encoding: UTF-8 12 | 13 | RnwWeave: Sweave 14 | LaTeX: pdfLaTeX 15 | 16 | BuildType: Package 17 | PackageUseDevtools: Yes 18 | PackageInstallArgs: --no-multiarch --with-keep.source 19 | PackageCheckArgs: --as-cran 20 | -------------------------------------------------------------------------------- /socsimOversimplified.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/MPIDR/rsocsim/28ff018137b6543ee637c9770a388ae8ee7d30ef/socsimOversimplified.pdf -------------------------------------------------------------------------------- /src/RcppExports.cpp: -------------------------------------------------------------------------------- 1 | // Generated by using Rcpp::compileAttributes() -> do not edit by hand 2 | // Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 3 | 4 | #include 5 | 6 | using namespace Rcpp; 7 | 8 | #ifdef RCPP_USE_GLOBAL_ROSTREAM 9 | Rcpp::Rostream& Rcpp::Rcout = Rcpp::Rcpp_cout_get(); 10 | Rcpp::Rostream& Rcpp::Rcerr = Rcpp::Rcpp_cerr_get(); 11 | #endif 12 | 13 | // startSocsimWithFile 14 | int startSocsimWithFile(String supfile, String seed, String compatibility_mode, String result_suffix); 15 | RcppExport SEXP _rsocsim_startSocsimWithFile(SEXP supfileSEXP, SEXP seedSEXP, SEXP compatibility_modeSEXP, SEXP result_suffixSEXP) { 16 | BEGIN_RCPP 17 | Rcpp::RObject rcpp_result_gen; 18 | Rcpp::RNGScope rcpp_rngScope_gen; 19 | Rcpp::traits::input_parameter< String >::type supfile(supfileSEXP); 20 | Rcpp::traits::input_parameter< String >::type seed(seedSEXP); 21 | Rcpp::traits::input_parameter< String >::type compatibility_mode(compatibility_modeSEXP); 22 | Rcpp::traits::input_parameter< String >::type result_suffix(result_suffixSEXP); 23 | rcpp_result_gen = Rcpp::wrap(startSocsimWithFile(supfile, seed, compatibility_mode, result_suffix)); 24 | return rcpp_result_gen; 25 | END_RCPP 26 | } 27 | 28 | static const R_CallMethodDef CallEntries[] = { 29 | {"_rsocsim_startSocsimWithFile", (DL_FUNC) &_rsocsim_startSocsimWithFile, 4}, 30 | {NULL, NULL, 0} 31 | }; 32 | 33 | RcppExport void R_init_rsocsim(DllInfo *dll) { 34 | R_registerRoutines(dll, NULL, CallEntries, NULL, NULL); 35 | R_useDynamicSymbols(dll, FALSE); 36 | } 37 | -------------------------------------------------------------------------------- /src/src/census.c: -------------------------------------------------------------------------------- 1 | /* %W% %G% */ 2 | //#include "defs.h" 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | double census1960_sm[] = { 9020, 8350, 7600, 5658, 2448, 946, 593, 455, 360, 10 | 342, 326, 302, 239, 205, 159, 99, 44, 21,}; 11 | 12 | double census1960_mm[] = { 0, 0, 0, 231, 2208, 3786, 4625, 5011, 4752, 4507, 13 | 4006, 3477, 2861, 2431, 1812, 1125, 545, 283,}; 14 | 15 | double census1960_sf[] = { 8600, 7960, 7250, 4843, 1326, 470, 349, 337, 320, 16 | 327, 347, 334, 272, 253, 205, 140, 83, 50,}; 17 | 18 | double census1960_mf[] = { 0, 0, 0, 928, 3490, 4364, 5023, 5396, 4959, 4667, 19 | 4107, 3646, 3140, 2772, 2140, 1404, 742, 435,}; 20 | 21 | double census1960_tm[] = { 9020, 8350, 7600, 5889, 4656, 4732, 5218, 5466, 22 | 5112, 4849, 4332, 3779, 3100, 2636, 1971, 1224, 589, 304, }; 23 | 24 | double census1960_tf[] = { 8600, 7960, 7250, 5771, 4816, 4834, 5372, 5733, 25 | 5279, 4994, 4454, 3980, 3412, 3025, 2345, 1544, 825, 485, }; 26 | 27 | int single1960[] = {37167, 33466, }; 28 | int notsingle1960[] = {41660, 47213, }; 29 | int total1960[] = {78827, 80679, }; 30 | 31 | double single_scale[2], notsingle_scale[2], total_scale[2]; 32 | 33 | 34 | void marriage_tally(FILE *fd) 35 | { 36 | struct person *p; 37 | int single_matrix[20][2][MAXGROUPS]; 38 | int notsingle_matrix[20][2][MAXGROUPS]; 39 | int total_matrix[20][2][MAXGROUPS]; 40 | int i, g; 41 | 42 | fprintf (fd,"MALES on marriage queue %d \n", marriage_queue->num); 43 | fprintf (fd,"FEMALES on marriage queue %d \n", (marriage_queue + 1)->num); 44 | 45 | for (g = 1; g <= numgroups; g++) { 46 | for (i = 0; i < 20; i++) { 47 | single_matrix[i][MALE][g] = 0; 48 | single_matrix[i][FEMALE][g] = 0; 49 | notsingle_matrix[i][MALE][g] = 0; 50 | notsingle_matrix[i][FEMALE][g] = 0; 51 | total_matrix[i][MALE][g] = 0; 52 | total_matrix[i][FEMALE][g] = 0; 53 | } 54 | } 55 | 56 | p = person0; 57 | 58 | while (p != NULL) { 59 | if (p->deathdate == 0) { 60 | i = (int) ((current_month - p->birthdate)/60); 61 | 62 | printf("agegrp %d mstat %d group %d smat %d \n",i, 63 | p->mstatus,p->group, 64 | single_matrix[i][p->sex][p->group]); 65 | if (p->mstatus == SINGLE) { 66 | single_matrix[i][p->sex][p->group]++; 67 | } else { 68 | notsingle_matrix[i][p->sex][p->group]++; 69 | } 70 | total_matrix[i][p->sex][p->group]++; 71 | } 72 | p = p->down; 73 | } 74 | 75 | for (g = 1; g <= 1; g++) { 76 | 77 | /* odd seg fault here */ 78 | fprintf(fd,"GROUP %d MALE SINGLE ", g); 79 | 80 | for (i = 0; i < 20; i++) 81 | fprintf(fd,"%d ", single_matrix[i][MALE][g]); 82 | fprintf(fd,"\n"); 83 | fprintf(fd,"GROUP %d MALE NOTSINGLE ", g); 84 | for (i = 0; i < 20; i++) 85 | fprintf(fd,"%d ", notsingle_matrix[i][MALE][g]); 86 | fprintf(fd,"\n"); 87 | fprintf(fd,"GROUP %d FEMALE SINGLE ", g); 88 | for (i = 0; i < 20; i++) 89 | fprintf(fd,"%d ", single_matrix[i][FEMALE][g]); 90 | fprintf(fd,"\n"); 91 | fprintf(fd,"GROUP %d FEMALE NOTSINGLE ", g); 92 | for (i = 0; i < 20; i++) 93 | fprintf(fd,"%d ", notsingle_matrix[i][FEMALE][g]); 94 | fprintf(fd,"\n"); 95 | } 96 | /* 97 | */ 98 | for (g = 1; g <= 1; g++) { 99 | int sum_sm = 0; 100 | int sum_sf = 0; 101 | int sum_mm = 0; 102 | int sum_mf = 0; 103 | int sum_tm = 0; 104 | int sum_tf = 0; 105 | int x; 106 | 107 | fprintf(fd,"GROUP %d MALE SINGLE ", g); 108 | for (i = 0; i < 17; i++) { 109 | fprintf(fd,"%d ", single_matrix[i][MALE][g]); 110 | sum_sm += single_matrix[i][MALE][g]; 111 | } 112 | x = single_matrix[17][MALE][g] + single_matrix[18][MALE][g]+ 113 | single_matrix[19][MALE][g]; 114 | fprintf(fd,"%d\n", x); 115 | sum_sm += x; 116 | single_scale[MALE] = (double) single1960[MALE]/sum_sm; 117 | fprintf(fd,"sum_sm %d scale factor %lf\n", sum_sm, single_scale[MALE]); 118 | fprintf(fd,"DIFF "); 119 | for (i = 0; i < 17; i++) { 120 | fprintf(fd,"%lf ", census1960_sm[i] - 121 | single_scale[MALE] * single_matrix[i][MALE][g]); 122 | } 123 | fprintf(fd,"%lf\n", census1960_sm[17] - single_scale[MALE] * x); 124 | 125 | fprintf(fd,"GROUP %d MALE NOTSINGLE ", g); 126 | for (i = 0; i < 17; i++) { 127 | fprintf(fd,"%d ", notsingle_matrix[i][MALE][g]); 128 | sum_mm += notsingle_matrix[i][MALE][g]; 129 | } 130 | x = notsingle_matrix[17][MALE][g] + notsingle_matrix[18][MALE][g] 131 | + notsingle_matrix[19][MALE][g]; 132 | fprintf(fd,"%d\n", x); 133 | sum_mm += x; 134 | notsingle_scale[MALE] = (double) notsingle1960[MALE]/sum_mm; 135 | fprintf(fd,"sum_mm %d scale factor %lf\n", sum_mm, notsingle_scale[MALE]); 136 | fprintf(fd,"DIFF "); 137 | for (i = 0; i < 17; i++) { 138 | fprintf(fd,"%lf ", census1960_mm[i] - 139 | notsingle_scale[MALE] * notsingle_matrix[i][MALE][g]); 140 | } 141 | fprintf(fd,"%lf\n", census1960_mm[17] - notsingle_scale[MALE] * x); 142 | 143 | fprintf(fd,"GROUP %d MALE TOTAL ", g); 144 | for (i = 0; i < 17; i++) { 145 | fprintf(fd,"%d ", total_matrix[i][MALE][g]); 146 | sum_tm += total_matrix[i][MALE][g]; 147 | } 148 | x = total_matrix[17][MALE][g] + total_matrix[18][MALE][g] 149 | + total_matrix[19][MALE][g]; 150 | fprintf(fd,"%d\n", x); 151 | sum_tm += x; 152 | total_scale[MALE] = (double) total1960[MALE]/sum_tm; 153 | fprintf(fd,"sum_tm %d scale factor %lf\n", sum_tm, total_scale[MALE]); 154 | fprintf(fd,"TOTAL DIFF "); 155 | for (i = 0; i < 17; i++) { 156 | fprintf(fd,"%lf ", census1960_tm[i] - 157 | total_scale[MALE] * total_matrix[i][MALE][g]); 158 | } 159 | fprintf(fd,"%lf\n", census1960_tm[17] - total_scale[MALE] * x); 160 | 161 | fprintf(fd,"GROUP %d FEMALE SINGLE ", g); 162 | for (i = 0; i < 17; i++) { 163 | fprintf(fd,"%d ", single_matrix[i][FEMALE][g]); 164 | sum_sf += single_matrix[i][FEMALE][g]; 165 | } 166 | x = single_matrix[17][FEMALE][g] + single_matrix[18][FEMALE][g] 167 | + single_matrix[19][FEMALE][g]; 168 | fprintf(fd,"%d\n", x); 169 | sum_sf += x; 170 | single_scale[FEMALE] = (double) single1960[FEMALE]/sum_sf; 171 | fprintf(fd,"sum_sf %d scale factor %lf\n", sum_sf, 172 | single_scale[FEMALE]); 173 | fprintf(fd,"DIFF "); 174 | for (i = 0; i < 17; i++) { 175 | fprintf(fd,"%lf ", census1960_sf[i] - 176 | single_scale[FEMALE] * single_matrix[i][FEMALE][g]); 177 | } 178 | fprintf(fd,"%lf\n", census1960_sf[17] - single_scale[FEMALE] * x); 179 | 180 | fprintf(fd,"GROUP %d FEMALE NOTSINGLE ", g); 181 | for (i = 0; i < 17; i++) { 182 | fprintf(fd,"%d ", notsingle_matrix[i][FEMALE][g]); 183 | sum_mf += notsingle_matrix[i][FEMALE][g]; 184 | } 185 | x = notsingle_matrix[17][FEMALE][g] + 186 | notsingle_matrix[18][FEMALE][g] + 187 | notsingle_matrix[19][FEMALE][g]; 188 | fprintf(fd,"%d\n", x); 189 | sum_mf += x; 190 | notsingle_scale[FEMALE] = (double) notsingle1960[FEMALE]/sum_mf; 191 | fprintf(fd,"sum_mf %d scale factor %lf\n", 192 | sum_mf, notsingle_scale[FEMALE]); 193 | fprintf(fd,"DIFF "); 194 | for (i = 0; i < 17; i++) { 195 | fprintf(fd,"%lf ", census1960_mf[i] - 196 | notsingle_scale[FEMALE] * notsingle_matrix[i][FEMALE][g]); 197 | } 198 | fprintf(fd,"%lf\n", census1960_mf[17] - notsingle_scale[FEMALE] * x); 199 | 200 | fprintf(fd,"GROUP %d FEMALE TOTAL ", g); 201 | for (i = 0; i < 17; i++) { 202 | fprintf(fd,"%d ", total_matrix[i][FEMALE][g]); 203 | sum_tf += total_matrix[i][FEMALE][g]; 204 | } 205 | x = total_matrix[17][FEMALE][g] + total_matrix[18][FEMALE][g] 206 | + total_matrix[19][FEMALE][g]; 207 | fprintf(fd,"%d\n", x); 208 | sum_tf += x; 209 | total_scale[FEMALE] = (double) total1960[FEMALE]/sum_tf; 210 | fprintf(fd,"sum_tf %d scale factor %lf\n", 211 | sum_tf, total_scale[FEMALE]); 212 | fprintf(fd,"TOTAL DIFF "); 213 | for (i = 0; i < 17; i++) { 214 | fprintf(fd,"%lf ", census1960_tf[i] - 215 | total_scale[FEMALE] * total_matrix[i][FEMALE][g]); 216 | } 217 | fprintf(fd,"%lf\n", census1960_tf[17] - total_scale[FEMALE] * x); 218 | } 219 | } 220 | 221 | /**********************************************************************/ 222 | void evaluate_marmkt(FILE *fd) 223 | { 224 | /* this makes sense only when MSCOREPROB is in effect. It will print the 225 | values in marriage_agetarget against those realized. */ 226 | 227 | 228 | int g,i,rxs,expected_marriages;// observed_marriages; 229 | double xs_mars=0,observedP=0,expectedP,oeratio=0,pctwrong=0,score=0; 230 | struct person *groom; 231 | struct person *bride; 232 | 233 | bride = NEW(struct person); 234 | groom = NEW(struct person); 235 | groom->birthdate=2000; /*months*/ 236 | groom->sex=MALE; bride->sex=FEMALE; 237 | 238 | 239 | 240 | fprintf(fd,"ageDiff\ttargetProp \tobservedProp\tE(mars)\tO(mars)\texcess\tO/E\tscore\n"); 241 | for(g=1;g<=numgroups;g++){ 242 | for(i=0;i<(2*MAXUYEARS); i++){ 243 | bride->group=g; 244 | 245 | bride->birthdate= groom->birthdate +(i-MAXUYEARS)*12 ; 246 | score= score3(bride,groom); 247 | observedP=((double)(marriage_ageobs[g][i]))/((double)(marriage_tots[g])); 248 | expectedP=(marriage_agetarget[g][i]>0)?marriage_agetarget[g][i]:0; 249 | expected_marriages=(marriage_agetarget[g][i]*marriage_tots[g]); 250 | expected_marriages=(expected_marriages <0)?0:expected_marriages; 251 | //observed_marriages=marriage_ageobs[g][i]; 252 | xs_mars= marriage_ageobs[g][i]-expected_marriages; 253 | 254 | rxs=round(xs_mars); 255 | 256 | if(marriage_ageobs[g][i]<=0){ 257 | oeratio= 0; 258 | }else{ 259 | oeratio=(expected_marriages<=0)? 260 | 1: 261 | (double)marriage_ageobs[g][i]/expected_marriages; 262 | } 263 | 264 | 265 | fprintf(fd,"%d\t%e\t%e\t%d\t%d\t%d\t%f\t%f\n", 266 | (i-MAXUYEARS), 267 | expectedP, 268 | observedP, 269 | expected_marriages, 270 | marriage_ageobs[g][i], 271 | rxs, 272 | oeratio, 273 | score 274 | ); 275 | pctwrong+=ABS(expectedP-observedP); 276 | 277 | /* 278 | fprintf(fd,"%d == %g == %g == %g == %g == %d\n", 279 | (i-MAXUYEARS), 280 | marriage_agetarget[g][i], 281 | ((double)marriage_ageobs[g][i]/ (double)marriage_tots[g]), 282 | marriage_ageobs[g][i], 283 | xs_mars, 284 | marriage_tots[g]); 285 | */ 286 | } 287 | /*pctwrong=(nwrong/marriage_tots[g])/2; */ 288 | fprintf(fd,"Absolute sum of fract expected-observed in group %d:%f\n", 289 | g,pctwrong); 290 | } 291 | 292 | 293 | 294 | } 295 | -------------------------------------------------------------------------------- /src/src/random.c: -------------------------------------------------------------------------------- 1 | /* %W% %G% */ 2 | #include 3 | #include 4 | //#include "defs.h" 5 | #include 6 | // #include 7 | 8 | /* 9 | Thu Sep 20 14:10:43 PDT 2012 10 | NO these must be const long int 11 | #define MODULUS 65536 12 | #define MULTIPLIER 25173 13 | #define INCREMENT 13849 14 | */ 15 | 16 | /*const long int MODULUS= 65536; // m */ 17 | /*const long int MULTIPLIER = 25173; // a */ 18 | /*const long int INCREMENT = 13849; // c */ 19 | 20 | const long long MODULUS= 2147483648 ; /* m */ 21 | const long long MULTIPLIER = 1103515245; /* a */ 22 | const long int INCREMENT = 12345; /*c */ 23 | 24 | double cycle(double,int); 25 | //long int ceed=12345678; 26 | 27 | 28 | int irandom() 29 | { 30 | #if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) //check if this is Windows, because win has no random(), only rand() 31 | //ceed = rand(); // rand() is not very good randomness. 32 | ceed = ((MULTIPLIER * ceed) + INCREMENT) % MODULUS; //implement our own https://en.wikipedia.org/wiki/Linear_congruential_generator ... leads to errors 33 | #else 34 | //Linux has random() which gives proper random-numbers: 35 | ceed = random(); 36 | #endif 37 | printf("\nrand_max: %d",RAND_MAX); 38 | 39 | return (int) ceed; 40 | } 41 | /***********************************************************************/ 42 | double 43 | rrandom() 44 | { 45 | 46 | double u; 47 | /*********************************************************************** 48 | * This just calls the builtin random() function. Initialization is 49 | * done in event.c. In case you don't care for your compiler's 50 | * random() you cann call real_rrandom() instead real_rrandom 51 | * implements what wikipedia says is gcc's cheapest/simplest random 52 | * number generator. 53 | ************************************************************************/ 54 | #if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) //check if this is Windows, because win has no random(), only rand() 55 | u = real_rrandom(); 56 | //u=rand()/(double) (RAND_MAX+1);//rand()/(double) RAND_MAX; // real_rrandom(); 57 | //the +1 is important, otherwise u will sometimes (every about 32600 times) be exactly 1.0! 58 | #else 59 | //Linux has random() which gives proper random-numbers: 60 | u= random()/(double) RAND_MAX; /** using system function !!!! **/ 61 | #endif 62 | /* u=real_rrandom(); */ 63 | 64 | /*fprintf(fd_allrandom,"%36.30f\n",u);*/ 65 | return(u); 66 | } 67 | 68 | 69 | /************************************************************************/ 70 | 71 | double 72 | real_rrandom() 73 | { 74 | /* Thu Sep 20 14:07:32 PDT 2012 This is NOT used by default. The 75 | code is here in case we encounter a compiler that does not do 76 | random() well. 77 | */ 78 | 79 | 80 | double t; 81 | t = (double) MODULUS; 82 | 83 | ceed = ((MULTIPLIER * ceed) + INCREMENT) % MODULUS; 84 | ; 85 | /* 86 | printf("rand: %e\n", ((double) ceed)/t); 87 | */ 88 | 89 | return ((double) ceed)/t; 90 | 91 | } 92 | 93 | double 94 | normal() 95 | { 96 | double theta, r, w; 97 | 98 | theta = rrandom() * 2 * PI; 99 | w = rrandom(); 100 | while (w == 0) 101 | w = rrandom(); 102 | r = sqrt(-2. * log(w)); 103 | return r * sin(theta); 104 | } 105 | 106 | double 107 | fertmult() 108 | { 109 | double u; 110 | 111 | u = rrandom(); 112 | 113 | return ((-1.764 + 1.995 * u) * u + 2.178) * u; 114 | /* 115 | return 1; 116 | */ 117 | } 118 | 119 | double flog(double x) 120 | { 121 | return cycle(x,1) - cycle(x, 2)/2 122 | + cycle(x, 3)/3 - cycle(x,4)/4 123 | + cycle(x,5)/5; 124 | /* 125 | - cycle(x,6)/6 126 | + cycle(x,7)/7 - cycle(x,8)/8 127 | + cycle(x,9)/9 - cycle(x,10)/10 128 | + cycle(x,11)/11 - cycle(x,12)/12 129 | + cycle(x,13)/13 - cycle(x,14)/14 130 | + cycle(x,15)/15 - cycle(x,16)/16; 131 | */ 132 | } 133 | 134 | double cycle(double x,int p) 135 | { 136 | double y; 137 | int i; 138 | 139 | y = 1; 140 | for (i = 1; i <= p; i++) { 141 | y*=x; 142 | } 143 | return y; 144 | } 145 | 146 | /** good RNG from https://www.pcg-random.org/download.html needs the #include at the top: 147 | // *Really* minimal PCG32 code / (c) 2014 M.E. O'Neill / pcg-random.org 148 | // Licensed under Apache License 2.0 (NO WARRANTY, etc. see website) 149 | 150 | typedef struct { uint64_t state; uint64_t inc; } pcg32_random_t; 151 | 152 | uint32_t pcg32_random_r(pcg32_random_t* rng) 153 | { 154 | uint64_t oldstate = rng->state; 155 | // Advance internal state 156 | rng->state = oldstate * 6364136223846793005ULL + (rng->inc|1); 157 | // Calculate output function (XSH RR), uses old state for max ILP 158 | uint32_t xorshifted = ((oldstate >> 18u) ^ oldstate) >> 27u; 159 | uint32_t rot = oldstate >> 59u; 160 | return (xorshifted >> rot) | (xorshifted << ((-rot) & 31)); 161 | } 162 | **/ -------------------------------------------------------------------------------- /src/startSocsimWithFile.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace Rcpp; 3 | 4 | #include "./src/events.cpp" 5 | //#include "src\random.c" 6 | 7 | // [[Rcpp::export]] 8 | int startSocsimWithFile(String supfile, String seed, String compatibility_mode, String result_suffix){ 9 | Rcpp::Rcout << "Start socsim" << std::endl; 10 | char *args[] = { 11 | (char*)"zerothArgument", 12 | (char*) supfile.get_cstring(), 13 | (char*) seed.get_cstring(), 14 | (char*) compatibility_mode.get_cstring(), 15 | (char*) result_suffix.get_cstring(), 16 | NULL 17 | }; 18 | main1(2, args); 19 | Rcpp::Rcout << "Socsim Done." << std::endl; 20 | 21 | return 0; 22 | 23 | } 24 | 25 | 26 | // You can include R code blocks in C++ files processed with sourceCpp 27 | // (useful for testing and development). The R code will be automatically 28 | // run after the compilation. 29 | // 30 | 31 | // /*** R 32 | // timesTwo(42) 33 | // */ 34 | -------------------------------------------------------------------------------- /tests/testthat.R: -------------------------------------------------------------------------------- 1 | # This file is part of the standard setup for testthat. 2 | # It is recommended that you do not modify it. 3 | # 4 | # Where should you do additional test configuration? 5 | # Learn more about the roles of various files in: 6 | # * https://r-pkgs.org/tests.html 7 | # * https://testthat.r-lib.org/reference/test_package.html#special-files 8 | 9 | library(testthat) 10 | library(rsocsim) 11 | 12 | test_check("rsocsim") 13 | -------------------------------------------------------------------------------- /tests/testthat/test_download_and_run.R: -------------------------------------------------------------------------------- 1 | library(testthat) 2 | library(rsocsim) 3 | 4 | test_that("Download rates and run simulation", { 5 | dir.create("tmp/tmp", recursive = TRUE) 6 | tmpdir <- file.path(getwd(), "tmp/tmp") 7 | 8 | expect_true(dir.exists(tmpdir)) 9 | 10 | countrycode <- "MM" 11 | final_sim_year <- 2010 12 | rsocsim::download_rates(tmpdir, countrycode, yearStart = 2003, yearEnd = final_sim_year, source = "UN") 13 | 14 | # Assuming the download_rates function creates a specific file, check if it exists 15 | expect_true(file.exists(file.path(tmpdir, "rates", paste0(countrycode, "_rates_info.sup")))) 16 | 17 | rsocsim::create_initial_population(tmpdir, size_opop = 1000, output_base = "presim") 18 | 19 | result <- rsocsim::socsim(tmpdir, paste0(countrycode, "_rates_info.sup")) 20 | print(paste("Result:", result)) 21 | # Add assertions based on expected results from the simulation 22 | expect_is(result, 1) 23 | 24 | 25 | # read simulation outputs 26 | omar = rsocsim::read_omar(folder,supfile,seed,suffix=suffix) 27 | omar.head() 28 | 29 | opop = rsocsim::read_opop(folder,supfile,seed,suffix) 30 | opop.head() 31 | 32 | # Obtain partial kinship network, with omar and opop already in R environment 33 | pid <- c("111", "10211", "10311") 34 | kin_network <- getKin(opop = opop, omar = omar, pid = pid, 35 | extra_kintypes = c("unclesaunts", "niblings"), kin_by_sex = TRUE) 36 | 37 | kin_network$nieces[[3]][1] 38 | 39 | opop$pid[kin_network$nieces[[3]]] 40 | 41 | 42 | #### 43 | 44 | fert_rates <- estimate_fertility_rates( 45 | opop=opop, 46 | final_sim_year=final_sim_year, 47 | year_min=2004, 48 | year_max=2009, 49 | year_group = 5, 50 | age_min_fert = 15, 51 | age_max_fert = 50, 52 | age_group = 5 53 | ) 54 | print(fert_rates.head()) 55 | }) -------------------------------------------------------------------------------- /tests/testthat/test_futurecalls.R: -------------------------------------------------------------------------------- 1 | 2 | if (FALSE) { # for now, don't run this test! 3 | library("rsocsim") 4 | 5 | # create a new folder for all the files related to a simulation. 6 | # this will be in your home- or user-directory: 7 | folder = rsocsim::create_simulation_folder() 8 | 9 | # create a new supervisory-file. supervisory-files tell socsim what 10 | # to simulate. create_sup_file will create a very basic supervisory file 11 | # and it copies some rate-files that will also be needed into the 12 | # simulation folder: 13 | supfile = "socsim.sup" #rsocsim::create_sup_file(folder) 14 | 15 | # Choose a random-number seed: 16 | seed = 300 17 | 18 | # Start the simulation: 19 | rsocsim::socsim(folder,supfile,seed) 20 | 21 | 22 | rsocsim::socsim(folder,supfile,seed,process_method = "future") 23 | 24 | warnings() 25 | 26 | print("jobida!") 27 | 28 | rsocsim::socsim(folder,supfile,seed,process_method = "clustercall") 29 | 30 | 31 | callr::r(print,c("hallo welt")) 32 | 33 | 34 | 35 | processFile = function(filepath) { 36 | con = file(filepath, "r") 37 | while ( TRUE ) { 38 | line = readLines(con, n = 1) 39 | if ( length(line) == 0 ) { 40 | break 41 | } 42 | print(line) 43 | } 44 | 45 | close(con) 46 | } 47 | processFile(paste0(folder,supfile)) 48 | 49 | 50 | 51 | 52 | f1 <- future::future({ 53 | #startSocsimWithFile(supfile,seed,compatibility_mode) 54 | Sys.sleep(10) 55 | },seed=TRUE) 56 | print("started!") 57 | # start a loop and check whether the simulation in the future is finished. 58 | # if it is not yet finished, read the output file and print the last line 59 | # to the console 60 | print("wait for simulation to finish") 61 | while (!future::resolved(f1)) { 62 | Sys.sleep(0.333) 63 | processFile(supfile) 64 | } 65 | 66 | } 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | -------------------------------------------------------------------------------- /tests/testthat/test_simulations.R: -------------------------------------------------------------------------------- 1 | if (FALSE) { 2 | 3 | folder = rsocsim::create_simulation_folder() 4 | folder 5 | print(paste0("folder: ", folder)) 6 | 7 | supfile = rsocsim::create_sup_file(folder) 8 | print(supfile) 9 | 10 | seed = 123345 11 | suffix="test7" 12 | 13 | rsocsim::socsim( 14 | folder, 15 | supfile, 16 | seed = seed, 17 | process_method = "inprocess", 18 | compatibility_mode = "1", 19 | suffix = suffix 20 | ) 21 | 22 | omar = rsocsim::read_omar(folder,supfile,seed,suffix=suffix) 23 | omar 24 | 25 | opop = rsocsim::read_opop(folder,supfile,seed,suffix) 26 | opop 27 | 28 | pid <- c("111", "10211", "10311") 29 | kin_network <- getKin(opop = opop, omar = omar, pid = pid, 30 | extra_kintypes = c("unclesaunts", "niblings"), kin_by_sex = TRUE) 31 | 32 | kin_network$nieces[[3]][1] 33 | 34 | opop$pid[kin_network$nieces[[3]]] 35 | 36 | 37 | #### 38 | 39 | fert_rates <- estimate_fertility_rates( 40 | opop=opop, 41 | final_sim_year=1966, 42 | year_min=1963, 43 | year_max=1965, 44 | year_group = 5, 45 | age_min_fert = 15, 46 | age_max_fert = 50, 47 | age_group = 5 48 | ) 49 | 50 | } -------------------------------------------------------------------------------- /tests/testthat/testit.R: -------------------------------------------------------------------------------- 1 | if (FALSE) { 2 | 3 | folder = "D:\\dev\\r\\socsimprojects\\CousinDiversity" 4 | supfile = "CousinDiversity.sup" 5 | seed="33" 6 | 7 | rsocsim::run1simulationwithfile(folder,supfile,seed,process_method = "inprocess") 8 | rsocsim::run1simulationwithfile(folder,supfile,seed,process_method = "future") 9 | rsocsim::run1simulationwithfile(folder,supfile,seed,process_method = "clustercall") 10 | 11 | #rsocsim::run1simulationwithfile_clustercall(folder,supfile,seed) 12 | 13 | socsim_path = "D:\\downloads\\socsim1.exe" 14 | rsocsim::run1simulationwithfile_from_binary(folder,supfile,seed) 15 | rsocsim::run1simulationwithfile_from_binary(folder,supfile,seed,socsim_path) 16 | 17 | 18 | rsocsim::get_asfr_socsim() 19 | 20 | rsocsim::getKin() 21 | 22 | basename(socsim_path) 23 | dirname(socsim_path) 24 | dirname(folder) 25 | 26 | ############################################ 27 | 28 | 29 | 30 | 31 | ################################# 32 | } -------------------------------------------------------------------------------- /tests/testthat/testit2.R: -------------------------------------------------------------------------------- 1 | if (FALSE) { 2 | folder = rsocsim::create_simulation_folder() 3 | folder 4 | #folder = "C:/Users/tom/socsim/socsim_sim_2541/" 5 | #folder= "C:\Users\tom\socsim\socsim_sim_2541" 6 | 7 | supfile = rsocsim::create_sup_file(folder) 8 | # supfile = "socsim.sup" 9 | supfile 10 | 11 | seed = 777 12 | suffix="sufffi33f" 13 | 14 | rsocsim::socsim(folder,supfile,seed,suffix=suffix)#,process_method = "inprocess") 15 | 16 | opop <- rsocsim::read_opop(folder,supfile,seed,suffix) 17 | opop 18 | omar <- rsocsim::read_omar(folder,supfile,seed,suffix) 19 | omar 20 | #Obtain partial kinship network, with omar and opop already in R environment 21 | pid <- c(1000,1001) #opop$pid[-3:-1] 22 | pid 23 | 24 | kin_network <- rsocsim::getKin(opop = opop, omar = omar, pid = pid, extra_kintypes = c("unclesaunts", "niblings"), kin_by_sex = TRUE) 25 | 26 | kin_network 27 | 28 | kin_network$ggparents 29 | kin_network$gdaughters 30 | 31 | rsocsim::socsim(folder,supfile,seed,process_method = "inprocess",suffix=suffix) 32 | rsocsim::socsim(folder,supfile,seed,process_method = "future",suffix=suffix) 33 | 34 | rsocsim::socsim(folder,supfile,seed,process_method = "clustercall",suffix=suffix) 35 | 36 | #rsocsim::run1simulationwithfile_clustercall(folder,supfile,seed) 37 | 38 | socsim_path = "D:\\downloads\\socsim1.exe" 39 | rsocsim::run1simulationwithfile_from_binary(folder,supfile,seed) 40 | rsocsim::run1simulationwithfile_from_binary(folder,supfile,seed,socsim_path) 41 | 42 | 43 | basename(socsim_path) 44 | dirname(socsim_path) 45 | dirname(folder) 46 | 47 | system.file("extdata", "SWEfert2022", package = "rsocsim", mustWork = TRUE) 48 | 49 | 50 | 51 | 52 | Rcpp::compileAttributes() 53 | 54 | 55 | devtools::build(binary = TRUE, args = c('--preclean')) 56 | 57 | 58 | # Rcmd.exe INSTALL --preclean --no-multiarch --with-keep.source rsocsim 59 | 60 | install.packages('rsocsim') 61 | 62 | devtools::install(dependencies = TRUE, build = TRUE, args = c('--preclean')) 63 | 64 | 65 | 66 | # retrieve Kin: 67 | # Try it out ----- 68 | 69 | opop <- read_opop("output_pop.opop") 70 | omar <- read_omar("output_pop.omar") 71 | 72 | 73 | 74 | # ISSUES ----- 75 | } --------------------------------------------------------------------------------