{"text": "#' ---\n#' title: \"Uvod u R\"\n#' subtitle: Kontrola toka i oblikovanje podataka\n#' author:\n#' - \"Milutin Pejovic, Petar Bursac\"\n#' date: \"`r format(Sys.time(), '%d %B %Y')`\"\n#' output:\n#' html_document:\n#' keep_md: true\n#' theme: \"simplex\"\n#' highlight: tango\n#' toc: true\n#' toc_depth: 5\n#' toc_float: true\n#' fig_caption: yes\n#' ---\n#'\n#' # Kontrola toka u R-u\n#' \n#' U okviru ovog predavanja upoznaćemo se sa mogućnostima kontrole toka i automatizacije izvršavanja komandi primenom komandi `if` i `for`. \n#'\n#' ## `if` - grananje toka \n#' \n#' Komanda `if` omogućava da postavimo uslov kojim će izvršavanje neke komande zavisiti od rezultata nekog logičkog upita. Na taj način moguće je stvoriti razgranatu strukturu toka izvršavanja komandi (algoritma). Komanda `if` se koristi na sledeći način:\n#' \n#' $$if(condition) \\quad \\textrm{{true_expression}} \\quad elsе \\quad \\textrm{{false_expression}}$$ \n#' \n#' Na primer, ukoliko promenljiva `x` sadrži numerički podatak, podeliti ga sa 2, a ukoliko je neki drugi podatak ispisati \"Nije moguće izvršiti komandu jer x ne sadrži numerički podatak\"\n#' \n#' \nx <- 5\nif(is.numeric(x)) x/2 else print(\"Nije moguće izvršiti komandu jer x ne sadrži numerički podatak\")\n\nx <- \"a\"\nif(is.numeric(x)) x/2 else print(\"Nije moguće izvršiti komandu jer x ne sadrži numerički podatak\")\n#' \n#' Ukoliko ne postoji određena operacija koja se uzvršava u slučaju `else`, nije potrebno pisati taj deo. Na primer:\n#' \nx <- 5\nif(is.numeric(x)) x/2 \n\nx <- \"a\"\nif(is(x, \"numeric\")) x/2 \n\n\n#' \n#' Međutim, pravi smisao `if` komande se vidi tek kada očekujemo da prilikom izvršavanja niza komandi računar sam odluči šta treba uraditi u određenom trenutku u zavisnosti od ulazinih parametara. \n#' \n#' \n#' ## `for` petlja\n#' \n#' `for` petlja se koristi kada želimo da automatizujemo izvršavanje neke komande ili niza komandi određeni broj puta. `for` petlja se koristi na sledeći način:\n#'\n#' $$ for(i \\quad in \\quad list) \\quad \\textrm{{expression}} $$\n#'\n#' Na primer, ako želimo da podacima `studenti` dodamo jednu kolonu pod nazivom \"ispit\" u vidu logičkog vektora koji će sadržati vrednost TRUE za studente koji su položili oba ispita (IG1 i Praksu) i FALSE za one koji nisu.\n#'\n#'\n#'\nstudenti <- read.csv(file = \"D:/R_projects/Nauka_R/Slides/data/Students_IG1.txt\", header = TRUE, stringsAsFactors = FALSE)\n\nstudenti$ispit <- NA # Prvo cemo kreirati kolonu \"ispit\" koja ima sve NA vrednosti\n\n \n# Komanda dim(studenti) vraca broj dimenzija, prvi se odnosi na broj vrsta.\ndim(studenti)\n\n\nfor(i in 1:dim(studenti)[1]){ \n # Sekvenca `1:dim(studenti)[1]` sadrzi niz brojeva od 1 do ukupnog broja vrsta u data.frame-u studenti.\n # i ide kroz svaku vrstu data.frame-a `studenti`\n studenti$ispit[i] <- if(is.na(studenti$Ocena[i]) | is.na(studenti$Praksa[i])){FALSE}else{TRUE}\n} \n\nhead(studenti, 15)\n\nsum(studenti$ispit) # Koliko studenata je polozilo oba ispita\n\n#' \n#' \n#' >

Zadatak

\n#' \n#' > Potrebno je oblikovati fajl sa podacima nivelanja geometrijskim nivelmanom. Fajl sadrži sledeće informacije:\n#' \n#' > > + Prva kolona: tacka - sadrzi imena repera i veznih tačaka. Reperi su B1, B3, B4 i B5, a vezne tacke su 1:n.\n#' \n#' > > + Druga kolona: merenje - sadrži čitanja na letvi.\n#' \n#' > > + Treća kolona: duzina - sadrži merenu dužinu od instrumenta do letve.\n#' \n#' > U zadatku se traži sledeće:\n#' > 1. Učitati podatke\n#' \n#' > 2. Kreirati `data.frame` sa sledećim kolonama: od, do, dh i dužina. Pri tome, treba imati u vidu da je na svakoj stanici merena visinska razlika po principu zadnja-prednja-prednja-zadnja. To znači da svakoj stanici pripada po četiri reda izvornih podataka. Rezultujući `data.frame` treba da sadrži po jedan red po stanici, koji će u prvoj koloni (\"od\") imati \"zadnju\" tačku, u drugoj koloni (\"do\") imati prednju tačku, u trećoj koloni (\"dh\") imati srednju visinsku razliku sračunatu iz čitanja na letvi i u poslednjoj koloni (\"duzina\") imatu srednju dužinu od letve do letve sračunatu iz merenih dužina. Prilikom rada, pokušajte da se vodite sledećim principima:\n#' \n#' \n#' > > *Generalna preporuka je da podelite zadatak na više manjih zadataka. Na primer, izdvojite podatke za samo jednu stanicu i pokušajte da kreirate željeni `data.frame` sa podacima samo jedne stanice. Uvidite šta su problemi u tom slučaju. Na početku, napravite rezultujući `data.frame` koji će sadržati samo `NA` vrednosti koje će biti zamenjene vrednostima koje treba da sadrži. Taj `data.frame` će imati broj redova onoliko koliko ima stanica i četiri kolone. Za te potrebe možete koristiti komandu `rep(NA, broj stanica)` za svaku kolonu `data.frame`-a. Komanda `rep` (repeat) pravi vektor određene dužine od vektora (sa jednom ili više) vrednosti. Za tim u taj `data.frame` upišite vrednosti koje izračunate ili isčitate iz ulaznih podataka. Kada rešite problem za jednu stanicu, razmislite kako ćete to automatizovati koristeći petlju `for`. Tu je preporuka da u ulaznim podacima napravite još jednu kolonu (faktorsku) koja će označiti koji red pripada kojoj stanici. Pa zatim, transformisati ulazne podatke u `list`-u prema toj promenljivoj i onda u okviru petlje `for`, na svaki član liste primeniti korake koje ste smislili kada ste rešavali samo jednu stanicu.*\n#' \n#' > 3. Za tim, potrebno je rezultujući `data.frame` dodatno transformisati (sumirati) tako da sadrži samo merenja od repera do repera, sa sledećim kolonama: od (reper), do (reper), dh (ukupna visinska razlika između repera), n (broj stanica od repera do repera) i duzina (ukupna duzina od repera do repera).\n#' \n#' ## Prvi način - korišćenjem petlje `for`\n#' \n#' ### Kreiranje prve tabele - visinske razlike po stanici\n#' \n#+ eval = TRUE, include = TRUE \n\n# Ucitavanje merenja\nmerenja <- read.table(file = \"D:/R_projects/Nauka_R/Slides/data/nivelman.txt\", header = TRUE, sep = \",\", stringsAsFactors = FALSE)\n\n# Kreiranje pomocne kolone (faktorske) koja pokazuje pripadnost redova stanici\nmerenja$stanica <- factor(rep(1:(dim(merenja)[1]/4), each = 4))\n\n# Kreiranje liste prema pomocnoj faktorskoj promenljivoj (stanica)\nmerenja_list <- split(merenja, merenja$stanica)\n\n# Kreiranje praznog data.frame-a\nmerenja_df <- data.frame( od = rep(NA, length(merenja_list)), \n do = rep(NA, length(merenja_list)), \n dh = rep(NA, length(merenja_list)), \n duzina = rep(NA, length(merenja_list)))\n\n# popunjavanje data.frame-a\nfor(i in 1:length(merenja_list)){\n merenja_df$od[i] <- as.character(merenja_list[[i]]$tacka[1])\n merenja_df$do[i] <- as.character(merenja_list[[i]]$tacka[2])\n merenja_df$dh[i] <- ((merenja_list[[i]]$merenje[1]-merenja_list[[i]]$merenje[2])+(merenja_list[[i]]$merenje[4]-merenja_list[[i]]$merenje[3]))/2\n merenja_df$duzina[i] <- sum(merenja_list[[i]]$duzina)/2 \n}\n\nmerenja_df\n\n#' Kreiranje fajla\n#+ eval = FALSE\nwritexl::write_xlsx(merenja_df, path = \"merenja_df.xlsx\")\n\n#' \n#' ### Kreiranje sumarne tabele - visinske razlike od repera do repera\n\nreperi <- c(\"B1\", \"B3\", \"B4\", \"B5\")\n\nmerenja_df$isReperOD <- merenja_df$od %in% reperi\nmerenja_df$isReperDO <- merenja_df$do %in% reperi\n\n\n# broj vis razlika izmedju repera\nndh <- sum(merenja_df$isReperOD)\n\n#indeks pozicije \"od\" repera,\nind.od <- which(merenja_df$isReperOD == T)\n# indeks pozicije \"do\" repera\nind.do <- which(merenja_df$isReperDO == T)\n\n# Visinske razlike\n\n# Naziv \"od\" repera\nod <- merenja_df$od[ind.od]\n\n# Naziv \"do\" repera\ndo <- merenja_df$do[ind.do]\n\n# Racunanje visinskih razlika od repera do repera\ndh <- rep(NA, ndh)\n\nfor(i in 1:ndh){\n dh[i] <- sum(merenja_df$dh[ind.od[i]:ind.do[i]])\n}\n\n# Racunanje broja stanica od repera do repera\nn <- rep(NA, ndh)\n\nfor(i in 1:ndh){\n n[i] <- length(ind.od[i]:ind.do[i])\n}\n\n# Racunanje duzina od repera do repera\nduzina <- rep(NA, ndh)\n\nfor(i in 1:ndh){\n duzina[i] <- sum(merenja_df$duzina[ind.od[i]:ind.do[i]])\n}\n\n# Kreiranje data.frame-a\nmerenja_df_sum <- data.frame(od = od, do = do, dh = dh, n = n, duzina = duzina)\n\n\nmerenja_df_sum\n\n\n#' Kreiranje fajla\n#+ eval = FALSE\nwritexl::write_xlsx(merenja_df_sum, path = \"merenja_df_reperi.xlsx\")\n\n#'\n#' # Transformacija podataka korišćenjem `dplyr` paketa \n#'\n#'\n#'\n#' Kao što ste već videli, oblikovanje podataka često podrazumeva kreiranje novih promenljivih (atribute ili kolone), sumiranje podataka u novu tabelu, reimenovati ili rasporediti podatke u tabeli. Za te potrebe razvijeni su brojni alati koji omogućavaju laku manupulaciju podacima, a najpoznatiji paket u R okruženju je `dplyr` paket iz `tidyverse` famijije paketa. Da bi se koristio paket `dplyr` neophodno ga je instalirati. Medjutim, preporučuje se instalacija celog `tidyverse` paketa, koji uključuje celu grupu korisnih paketa.\n#' \n#+ echo = FALSE, fig.align=\"center\", out.width = '25%'\nknitr::include_graphics(\"D:/R_projects/Nauka_R/Slides/Figures/tidyverse-logo.png\")\n#' \n#+ echo = FALSE, fig.align=\"center\", out.width = '70%'\nknitr::include_graphics(\"D:/R_projects/Nauka_R/Slides/Figures/tidyverse_website.png\")\n#' \n#' \n#' Instalacija `tidyverse` paketa\n#+ eval = FALSE\ninstall.packages(\"tidyverse\")\nlibrary(tidyverse)\n#'\n#'\n#' `dplyr` paket ima nekoliko osnovnih funkcionalnosti koje rešavaju najčešće probleme, kao što su:\n#' \n#' **selekcija pojedinačnih merenja (instanci ili vrsta u tabeli) komandom `dplyr::filter()`**\n#' \n#+ echo = FALSE, fig.align=\"center\", out.width = '70%'\nknitr::include_graphics(\"D:/R_projects/Nauka_R/Slides/Figures/filter.png\")\n#' \n#' **selekcija atributa (kolona) komandom `dplyr::select()`**\n#' \n#+ echo = FALSE, fig.align=\"center\", out.width = '70%'\nknitr::include_graphics(\"D:/R_projects/Nauka_R/Slides/Figures/rstudio-cheatsheet-select.png\") \n#' \n#' \n#' **Kreiranje novih promenljivih komandom `dplyr::mutate()`** \n#' \n#+ echo = FALSE, fig.align=\"center\", out.width = '70%'\nknitr::include_graphics(\"D:/R_projects/Nauka_R/Slides/Figures/mutate.png\") \n#' \n#' \n#' **Sumiranje podataka komandom `dplyr::summarise()`**\n#' \n#+ echo = FALSE, fig.align=\"center\", out.width = '70%'\nknitr::include_graphics(\"D:/R_projects/Nauka_R/Slides/Figures/summarise.png\")\n#' \n#' \n#' **Grupisanje podataka `dplyr::group_by()` (često u kombinaciji sa `summarise`)**\n#' \n#+ echo = FALSE, fig.align=\"center\", out.width = '70%'\nknitr::include_graphics(\"D:/R_projects/Nauka_R/Slides/Figures/group_by.png\")\n#' \n#' \n#' **Kombninovanje (spajanje) tabela komandom `dplyr::_join`**\n#' \n#+ echo = FALSE, fig.align=\"center\", out.width = '70%'\nknitr::include_graphics(\"D:/R_projects/Nauka_R/Slides/Figures/combine-options1.png\")\n#' \n#' \n#' **Sortiranje podataka komandom `dplyr::arrange()`** \n#' \n#+ echo = FALSE, fig.align=\"center\", out.width = '70%'\nknitr::include_graphics(\"D:/R_projects/Nauka_R/Slides/Figures/reorder-data-frame-rows-in-r.png\")\n#'\n#' \n#' \n#' ## Drugi način - korišćenjem `dplyr` paketa\n#' \n#' \n#' \n#+ warning = FALSE, message = FALSE \nlibrary(tidyverse)\nlibrary(magrittr)\n\n# Ucitavanje merenja\nmerenja <- read.table(file = \"D:/R_projects/Nauka_R/Slides/data/nivelman.txt\", header = TRUE, sep = \",\", stringsAsFactors = FALSE)\n\nmerenja_df <- merenja %>% \n dplyr::mutate(stanica = factor(rep(1:(dim(merenja)[1]/4), each = 4))) %>% # Kreiranje novih kolona\n dplyr::group_by(stanica) %>% # grupisanje podataka prema nekoj promenljivoj\n dplyr::summarise(od = as.character(tacka[1]), # sumiranje podataka\n do = as.character(tacka[2]),\n dh = ((merenje[1]-merenje[2])+(merenje[4]-merenje[3]))/2,\n duzina = sum(duzina)/2)\n\nmerenja_df\n\n\n#' \n#' \n#' >

Obrati pažnju na `%>%`

\n#' > Operator `%>%` (`pipe`) je moćan operator koji nam omogućava da sekvencijalno povezujemo operacije i da na taj način izbegnemo kreiranje nepotrebnih promenljivih. `Pipe` je dostupan preko paketa `magrittr`, što znači da je potrebno instalirati paket `magrittr` ako želimo da koristimo `pipe`. Međutim, `pipe` je takođe dostupan preko `tidyverse` paketa. Više detalja na [linku](https://r4ds.had.co.nz/pipes.html).\n#' \n\n#' \n#' ### Kreiranje sumarne tabele - visinske razlike od repera do repera\n#' \nreperi <- c(\"B1\", \"B3\", \"B4\", \"B5\")\n\nmerenja_df <- merenja_df %>% dplyr::mutate(isReperOD = merenja_df$od %in% reperi,\n isReperDO = merenja_df$do %in% reperi)\n\n\n\n#indeks pozicije \"od\" repera,\nind.od <- which(merenja_df$isReperOD == T)\n# indeks pozicije \"do\" repera\nind.do <- which(merenja_df$isReperDO == T) \n\n# broj vis razlika izmedju repera\nndh = sum(merenja_df$isReperOD)\n\n# Promenljiva koja pokazuje koja merenja pripadaju odredjenom nivelmanskom vlaku\nvlak <- c()\nfor(i in 1:ndh){\n vlak <- c(vlak, rep(i, ind.do[i]-(ind.od[i]-1)))\n}\n\nmerenja_df$vlak <- factor(vlak) \n\n# Sumiranje visinskih razlika po vlaku\nmerenja_df %>% dplyr::select(od, do, dh, duzina, vlak) %>%\n dplyr::group_by(vlak) %>% \n dplyr::summarize(dh_mean = sum(dh))\n\n# Sumiranje visinskih razlika po vlaku sa dodatnim kolonama\nmerenja_df_sum <- merenja_df %>% dplyr::select(od, do, dh, duzina, vlak) %>%\n dplyr::group_by(vlak) %>% \n dplyr::summarize(od = od[1],\n do = do[length(vlak)],\n dh = sum(dh),\n stanica = n())\n\nmerenja_df_sum\n\n\n#' # Kreiranje funkcija\n#' \n#' R omogućava kreranje funkcija koje nam omogućavaju da automatizujemo određene korake u našem algoritmu. Kreiranje funkcija je poželjno u slučajevima kada imamo određeni deo koda koji je potrebno ponoviti više puta. Na taj način, umesto da kopiramo kod više puta, moguće je kreirati funkciju koja će izvršiti taj deo koda pozivanjem kreirane funkcije. Generalno, kreiranje funkcija se sastoji iz tri koraka:\n#' \n#' + Dodeljivanje `imena`\n#' + Definisanje `argumenata`\n#' + Programiranje `tela` funckije (body) koje se sastoji od koda koji treba da se izvrši\n#' \n#' Na primer ukoliko zelimo da napravimo funkciju koja pretvara decimalni zapis ugla u stepenima u radijane, to ćemo učiniti na sledeći način\n#'\n#+\n\n\nstep2rad <- function(ang_step){\n ang_step*pi/180\n}\n\nstep2rad(180)\n\n#' Ukoliko zelimo da napravimo funkciju koja pretvara decimalni zapis ugla u zapis step-min-sec to ćemo uraditi na sledeći način:\n\ndec2dms <- function(ang){ # ime funkcije je `dec2dms`, a argument `ang`\n deg <- floor(ang) \n minut <- floor((ang-deg)*60)\n sec <- ((ang-deg)*60-minut)*60\n return(paste(deg, minut, round(sec, 0), sep = \" \"))\n}\n\ndec2dms(ang = 35.26589)\n\ndec2dms(45.52658)\n\n#' \n#' Ukoliko želimo da napravimo funkciju od koda koji smo kreirali za potrebe oblikovanja ulaznih podataka to ćemo uraditi na sledeći način. \n#' \n\nmerenja <- read.table(file = \"D:/R_projects/Nauka_R/Slides/data/nivelman.txt\", header = TRUE, sep = \",\", stringsAsFactors = FALSE)\n\nnivelman <- function(niv_merenja, reperi){ # ime funkcije je nivelman, a argumenti niv_merenja (ulazna merenja) i reperi (naziv repera)\n \n # kopiramo kod koji smo kreirali ()\n merenja_df <- niv_merenja %>% dplyr::mutate(stanica = factor(rep(1:(dim(niv_merenja)[1]/4), each = 4))) %>% \n dplyr::group_by(stanica) %>%\n dplyr::summarise(od = as.character(tacka[1]),\n do = as.character(tacka[2]),\n dh = ((merenje[2]-merenje[1])+(merenje[3]-merenje[4]))/2,\n duzina = sum(duzina)/2)\n \n merenja_df <- merenja_df %>% dplyr::mutate(isReperOD = merenja_df$od %in% reperi,\n isReperDO = merenja_df$do %in% reperi)\n \n #indeks pozicije \"od\" repera,\n ind.od <- which(merenja_df$isReperOD == T)\n # indeks pozicije \"do\" repera\n ind.do <- which(merenja_df$isReperDO == T) \n \n # broj vis razlika izmedju repera\n ndh = sum(merenja_df$isReperOD)\n \n # Promenljiva koja pokazuje koja merenja pripadaju odredjenom nivelmanskom vlaku\n vlak <- c()\n for(i in 1:ndh){\n vlak <- c(vlak, rep(i, ind.do[i]-(ind.od[i]-1)))\n }\n \n merenja_df$vlak <- factor(vlak) \n \n \n merenja_df_sum <- merenja_df %>% dplyr::select(od, do, dh, duzina, vlak) %>%\n dplyr::group_by(vlak) %>% \n dplyr::summarize(od = od[1],\n do = do[length(vlak)],\n dh = sum(dh),\n stanica = length(vlak))\n \n merenja_df <- merenja_df %>% dplyr::select(od, do, dh, duzina)\n \n results <- list(tabela_1 = merenja_df, tabela_2 = merenja_df_sum)\n return(results) # Ukoliko je u okviru funkcije kreirano više promenljivih, komandom `return` biramo koja promenljiva će biti rezultat naše funkcije\n}\n\n\nnivelman(niv_merenja = merenja, reperi = c(\"B1\", \"B3\", \"B4\", \"B5\"))\n\n#'\n#' \n#' \n#' >

Zadatak 1

\n#' > + Učitati excel fajl sa svim merenjima u mreži (`niv_merenja.xlsx`). Fajl je organizovan tako da su merenja u pojedinačnim vlakovima smeštena u odvojenim excel sheet-ovima. Za učitavanje excel fajla sa više sheet-ova koristiti uputstva data na linku `readxl` paketa: https://readxl.tidyverse.org/articles/articles/readxl-workflows.html#iterate-over-multiple-worksheets-in-a-workbook. Rezultat učitanih merenja je lista!\n#' > + Primeniti funkciju na svim elementima liste.\n#' > + Spojiti odgovarajuće tabele u jednu, tako da na kraju imamo dve tabele, jednu koja se odnosi na merenja na stanici i jednu sumarnu tabelu.\n\n\n#'\n#' \n#' >

Zadatak 1 - Resenje 1

\n\n# Imena svih repera u mrezi:\nreperi <- c(\"B1\", \"B3\", \"B4\", \"B5\", \"B6\", \"B7\", \"B8\", \"B9\", \"S1\", \"S2\", \"S3\", \"D1\", \"H1\", \"J1\", \"M1\", \"P1\", \"D7\", \"H7\", \"N7\", \"D10\", \"E10\", \"I10\", \"P10\", \"P13\", \"L116\",\t\"D19\", \"G19\", \"J19\", \"M19\", \"P19\", \"E26\", \"P26\", \"D29\", \"J29\", \"M29\", \"P29\", \"D32\", \"H32\", \"D38\", \"G38\", \"J38\", \"M38\", \"P38\", \"A11\", \"A12\", \"A13\", \"A14\", \"A21\", \"A22\",\t\"A23\", \"A24\")\n\n# Putanja ka fajlu (3 nacina)\nmerenja_path <- \"D:/R_projects/Nauka_R/Slides/data/niv_merenja.xlsx\"\nmerenja_path <- here::here(\"data\", \"niv_merenja.xlsx\")\nfiles_data <- list.files(\"D:/R_projects/Nauka_R/Slides/data/\", full.names = TRUE)\nmerenja_path <- files_data[6]\n\n# Nazivi sheet-ova\nnazivi_sheets <- merenja_path %>%\n readxl::excel_sheets()\n\n# Ucitavanje svakog sheet-a i smestanje u listu\nlista_sheets <- list()\nfor(i in 1:length(nazivi_sheets)){\n lista_sheets[[i]] <- readxl::read_excel(path = merenja_path, sheet = nazivi_sheets[i])\n}\nnames(lista_sheets) <- nazivi_sheets # postavljanje naziva elemenata liste\n# lista_sheets\n\n# Primena funkcije nivelman\nlista_nivelman <- list()\nfor(i in 1:length(lista_sheets)){\n lista_nivelman[[i]] <- nivelman(niv_merenja = lista_sheets[[i]], reperi = reperi)\n}\n# lista_nivelman\n\n# Visinske razlike po stanici - Tabela 1\ntabela_1 <- data.frame()\nfor(i in 1:length(lista_nivelman)){\n tabela_1 <- rbind(tabela_1, lista_nivelman[[i]][[1]])\n}\n# tabela_1\n\n# Visinske razlike od repera do repera - Tabela 2\ntabela_2 <- data.frame()\nfor(i in 1:length(lista_nivelman)){\n tabela_2 <- rbind(tabela_2, lista_nivelman[[i]][[2]])\n}\n# tabela_2 \n\n\n\n#' >

Zadatak 1 - Resenje 2

\n\n\n# Imena svih repera u mrezi:\n\nlibrary(tidyverse)\nlibrary(magrittr)\nlibrary(here)\nlibrary(readxl)\nlibrary(purrr)\n\nreperi <- c(\"B1\", \"B3\", \"B4\", \"B5\", \"B6\", \"B7\", \"B8\", \"B9\", \"S1\", \"S2\", \"S3\", \"D1\", \"H1\", \"J1\", \"M1\", \"P1\", \"D7\", \"H7\", \"N7\", \"D10\", \"E10\", \"I10\", \"P10\", \"P13\", \"L116\",\t\"D19\", \"G19\", \"J19\", \"M19\", \"P19\", \"E26\", \"P26\", \"D29\", \"J29\", \"M29\", \"P29\", \"D32\", \"H32\", \"D38\", \"G38\", \"J38\", \"M38\", \"P38\", \"A11\", \"A12\", \"A13\", \"A14\", \"A21\", \"A22\",\t\"A23\", \"A24\")\n\nmerenja_path <- here::here(\"data\", \"niv_merenja.xlsx\")\n\nmerenja <- merenja_path %>%\n readxl::excel_sheets() %>%\n purrr::set_names() %>%\n purrr::map(read_excel, path = merenja_path)\n\n# Drugi nacin\n# https://stackoverflow.com/questions/12945687/read-all-worksheets-in-an-excel-workbook-into-an-r-list-with-data-frames\nlibrary(rio)\ndata_list <- import_list(\"D:/R_projects/Nauka_R/Slides/data/niv_merenja.xlsx\", rbind = TRUE) # parametrom rbind (row bind - spojiti redove) dobijamo sve clanove liste spojene u jedan data.frame\n\n# Nazivi repera\nTacke <- unique(data_list$tacka)\nsubstr(Tacke,1,1)\ntoupper(substr(Tacke,1,1))\nTacke_sve <- tapply(Tacke, toupper(substr(Tacke,1,1)),identity)\n# tapply() is a very powerful function that lets you break a vector into pieces and then apply some function to each of the pieces\nReperi <- unlist(Tacke_sve[9:21][]) %>% as.data.frame() %>% dplyr::rename(tac = \".\")\nreperi <- as.vector(Reperi$tac)\n\n# Primena funkcije nivelman nad svim clanovima liste \nmreza_all <- lapply(merenja, function(x) nivelman(niv_merenja = x, reperi = reperi))\n\n# Visinske razlike po stanici - Tabela 1\nmreza_by_station <- lapply(mreza_all, function(x) x[[1]])\n\n# Visinske razlike od repera do repera - Tabela 2\nmreza_oddo <- lapply(mreza_all, function(x) x[[2]])\n\n# Tabela merenja po stanici\nmreza_by_station <- do.call(rbind, mreza_by_station) \nmreza_by_station %<>% as.data.frame()\n\n# Sumarna tabela\nmreza_oddo <- do.call(rbind, mreza_oddo)\nmreza_oddo %<>% dplyr::mutate(vlak = row_number()) %>% as.data.frame() \n\n#' ", "meta": {"hexsha": "7d9fedb134ce7f843c25e88ce526432d8ac8545b", "size": 20988, "ext": "r", "lang": "R", "max_stars_repo_path": "R/03-Uvod u R.r", "max_stars_repo_name": "Nauka-o-podacima-u-R-u/Slides", "max_stars_repo_head_hexsha": "5280e5cfa68bd097038fe72ddba66e355fd7ba64", "max_stars_repo_licenses": ["AFL-1.1"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/03-Uvod u R.r", "max_issues_repo_name": "Nauka-o-podacima-u-R-u/Slides", "max_issues_repo_head_hexsha": "5280e5cfa68bd097038fe72ddba66e355fd7ba64", "max_issues_repo_licenses": ["AFL-1.1"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/03-Uvod u R.r", "max_forks_repo_name": "Nauka-o-podacima-u-R-u/Slides", "max_forks_repo_head_hexsha": "5280e5cfa68bd097038fe72ddba66e355fd7ba64", "max_forks_repo_licenses": ["AFL-1.1"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.4393063584, "max_line_length": 1174, "alphanum_fraction": 0.6810558414, "num_tokens": 7692, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5350984286266115, "lm_q2_score": 0.7461389930307512, "lm_q1q2_score": 0.39925780270779715}} {"text": "\r\n\r\n# Goal: Visualisation of 3-dimensional (x,y,z) data using contour\r\n# plots and using colour to represent the 3rd dimension.\r\n# The specific situation is: On a grid of (x,y) points, you have\r\n# evaluated f(x,y). Now you want a graphical representation of\r\n# the resulting list of (x,y,z) points that you have.\r\n\r\n# Setup an interesting data matrix of (x,y,z) points:\r\npoints <- structure(c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.05, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.15, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.25, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.3, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.35, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.45, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.55, 0.55, 0.55, 0.55, 0.55, 0.55, 0.55, 0.55, 0.55, 0.55, 0.55, 0.55, 0.55, 0.55, 0.55, 0.55, 0.55, 0.55, 0.55, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.65, 0.65, 0.65, 0.65, 0.65, 0.65, 0.65, 0.65, 0.65, 0.65, 0.65, 0.65, 0.65, 0.65, 0.65, 0.65, 0.65, 0.65, 0.65, 0.7, 0.7, 0.7, 0.7, 0.7, 0.7, 0.7, 0.7, 0.7, 0.7, 0.7, 0.7, 0.7, 0.7, 0.7, 0.7, 0.7, 0.7, 0.7, 0.75, 0.75, 0.75, 0.75, 0.75, 0.75, 0.75, 0.75, 0.75, 0.75, 0.75, 0.75, 0.75, 0.75, 0.75, 0.75, 0.75, 0.75, 0.75, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.8, 0.85, 0.85, 0.85, 0.85, 0.85, 0.85, 0.85, 0.85, 0.85, 0.85, 0.85, 0.85, 0.85, 0.85, 0.85, 0.85, 0.85, 0.85, 0.85, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.9, 0.95, 0.95, 0.95, 0.95, 0.95, 0.95, 0.95, 0.95, 0.95, 0.95, 0.95, 0.95, 0.95, 0.95, 0.95, 0.95, 0.95, 0.95, 0.95, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0.998, 0.124, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0.998, 0.71, 0.068, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0.998, 0.898, 0.396, 0.058, 0.002, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0.998, 0.97, 0.726, 0.268, 0.056, 0.006, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0.996, 0.88, 0.546, 0.208, 0.054, 0.012, 0.002, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.998, 0.964, 0.776, 0.418, 0.18, 0.054, 0.014, 0.002, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.998, 0.906, 0.664, 0.342, 0.166, 0.056, 0.018, 0.006, 0.002, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.986, 0.862, 0.568, 0.29, 0.15, 0.056, 0.022, 0.008, 0.002, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.954, 0.778, 0.494, 0.26, 0.148, 0.056, 0.024, 0.012, 0.004, 0.002, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.906, 0.712, 0.43, 0.242, 0.144, 0.058, 0.028, 0.012, 0.006, 0.002, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0.878, 0.642, 0.38, 0.222, 0.142, 0.066, 0.034, 0.014, 0.008, 0.004, 0.002, 0, 0, 0, 0, 0, 0, 0, 0, 0.846, 0.586, 0.348, 0.208, 0.136, 0.068, 0.034, 0.016, 0.012, 0.006, 0.004, 0.002, 0, 0, 0, 0, 0, 0, 0, 0.8, 0.538, 0.318, 0.204, 0.136, 0.07, 0.046, 0.024, 0.012, 0.008, 0.004, 0.002, 0.002, 0, 0, 0, 0, 0, 0, 0.762, 0.496, 0.294, 0.2, 0.138, 0.072, 0.05, 0.024, 0.014, 0.012, 0.006, 0.004, 0.002, 0.002, 0, 0, 0, 0, 0, 0.704, 0.472, 0.286, 0.198, 0.138, 0.074, 0.054, 0.028, 0.016, 0.012, 0.008, 0.006, 0.004, 0.002, 0.002, 0, 0, 0, 0, 0.668, 0.438, 0.276, 0.196, 0.138, 0.078, 0.054, 0.032, 0.024, 0.014, 0.012, 0.008, 0.004, 0.004, 0.002, 0.002, 0, 0, 0, 0.634, 0.412, 0.27, 0.194, 0.14, 0.086, 0.056, 0.032, 0.024, 0.016, 0.012, 0.01, 0.006, 0.004, 0.004, 0.002, 0.002, 0, 0, 0.604, 0.388, 0.26, 0.19, 0.144, 0.088, 0.058, 0.048, 0.026, 0.022, 0.014, 0.012, 0.008, 0.006, 0.004, 0.004, 0.002, 0.002, 0, 0.586, 0.376, 0.256, 0.19, 0.146, 0.094, 0.062, 0.052, 0.028, 0.024, 0.014, 0.012, 0.012, 0.008, 0.004, 0.004, 0.004, 0.002, 0.002, 0.566, 0.364, 0.254, 0.192, 0.148, 0.098, 0.064, 0.054, 0.032, 0.024, 0.022, 0.014, 0.012, 0.012, 0.008, 0.004, 0.004, 0.004, 0.002), .Dim = c(399, 3), .Dimnames = list(NULL, c(\"x\", \"y\", \"z\")))\r\n\r\n# Understand this object --\r\nsummary(points)\r\n # x is a grid from 0 to 1\r\n # y is a grid from 20 to 200\r\n # z is the interesting object which will be the 3rd dimension.\r\n\r\n# Solution using contourplot() from package 'lattice'\r\nlibrary(lattice)\r\nd3 <- data.frame(points)\r\ncontourplot(z ~ x+y, data=d3)\r\n## or nicer\r\ncontourplot(z ~ x+y, data=d3, cuts=20, region = TRUE)\r\n## or using logit - transformed z values:\r\ncontourplot(qlogis(z) ~ x+y, data=d3, pretty=TRUE, region = TRUE)\r\n\r\n# An interesting alternative is levelplot()\r\nlevelplot(z ~ x+y, pretty=TRUE, contour=TRUE, data=d3)\r\n\r\n# There is a contour() function in R. Even though it sounds obvious\r\n# for the purpose, it is a bit hard to use.\r\n# contour() wants 3 inputs: vectors of x and y values, and a matrix of\r\n# z values, where the x values correspond to the rows of z, and the y\r\n# values to the columns. A collection of points like `points' above\r\n# needs to be turned into such a grid. It might sound odd, but contour()\r\n# image() and persp() have used this kind of input for the longest time.\r\n#\r\n# For irregular data, there's an interp function in the akima package\r\n# that can convert from irregular data into the grid format.\r\n#\r\n# The `points' object that I have above - a list of (x,y,z) points -\r\n# fits directly into the mentality of lattice::contourplot() but not\r\n# into the requirements of contour()\r\n\r\n", "meta": {"hexsha": "5ab8d337121e2b23d48f54de873d1df6a93551c6", "size": 7867, "ext": "r", "lang": "R", "max_stars_repo_path": "RFrontEndSolution/Tests Repo/Rscripts All (163 files)/g4.r", "max_stars_repo_name": "AlexandrosPlessias/CompilerFrontEndForRLanguage", "max_stars_repo_head_hexsha": "71e3e60476f6f83b05cc97c625265edbde086341", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "RFrontEndSolution/Tests Repo/Rscripts All (163 files)/g4.r", "max_issues_repo_name": "AlexandrosPlessias/CompilerFrontEndForRLanguage", "max_issues_repo_head_hexsha": "71e3e60476f6f83b05cc97c625265edbde086341", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "RFrontEndSolution/Tests Repo/Rscripts All (163 files)/g4.r", "max_forks_repo_name": "AlexandrosPlessias/CompilerFrontEndForRLanguage", "max_forks_repo_head_hexsha": "71e3e60476f6f83b05cc97c625265edbde086341", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 174.8222222222, "max_line_length": 6087, "alphanum_fraction": 0.5478581416, "num_tokens": 5256, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7248702761768249, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.39911891312052367}} {"text": "########################### BayesKin ###########################\n## Bayesian estimates of rigid body kinematics\n## Andy Pohl\n## UofC - Faculty of Kinesiology\n\n## Written by: Andy Pohl\n## UofC - Faculty of Kinesiology\n## June-Dec 2020\n## Revision 1: April 2021\n################################################################\n\n##################### process_results.r ###################\n## processes_results table for a batch of simulations\n#############################################################\n\n# preliminaries \nrm(list = ls()) # clear workspace\n\nlibrary('rjags') # load rstan package to analyze rstan objects\nlibrary('coda') # load coda package for mcmc analysis\nWORKING_DIR = \"\" # Replace with the location of the BayesKin/src directory on the local PC.\nsetwd(WORKING_DIR)\nRESULTS_DIR = paste0(WORKING_DIR, \"/src/\") # location of results directory\nPOSE_DIRS = c(\"SingleLink_Mdl\", \"DoubleLink_Mdl\", \"TripleLink_Mdl\") # Folder names for the various model configurations\nMODELS = c(\"LS\", \"Bayes_p1\", \"Bayes_p2\", \"Bayes_p3\", \"Bayes_p4\", \"Bayes_p5\") # Names of Models used\nfile_ends = c('LSModel.rda', 'BayesModel_p1.rda', 'BayesModel_p2.rda', 'BayesModel_p3.rda', 'BayesModel_p4.rda', 'BayesModel_p5.rda')\n\nPARMS = c('r[1]', 'r[2]', 'theta[1]', 'theta[2]', 'theta[3]', 'sigma') # Parameters of interest\n\nnfiles = 1000 # the number of results files to process\nnmodels = length(MODELS)\n\n################################################################################\n# Single Link\n################################################################################\nresults_single = data.frame(pose = rep('SingleLink', nmodels*4*nfiles),\n seed = rep(1:nfiles, each = nmodels*4),\n model = rep(rep(MODELS, each = 4),nfiles),\n parameter = rep(c('r1', 'r2', 'theta1', 'sigma'), nfiles*nmodels),\n est = NA,\n quantile = matrix(NA, nfiles*4*nmodels, 5),\n neff = NA,\n rhat = NA,\n ts_se = NA, \n run_time = NA)\n\nfiles = list.files(path = paste0(RESULTS_DIR, \"SingleLink_Mdl/Bayes_p3\"))\nseeds = as.numeric(gsub(\"(.+?)(\\\\_.*)\", \"\\\\1\", files))\nseeds = seeds[order(seeds)]\nrowcnt = 1\nfor(i in 1:nfiles){\n nlinks = 1\n seed = seeds[i]\n print(sprintf(\"Processing Single Link file %.0f of %.0f\", i, nfiles))\n \n # process LS results\n lsmdl = readRDS(paste0(RESULTS_DIR, \"SingleLink_Mdl/LS/\", seed, \"_LSModel.rda\"))\n est = c(lsmdl$r.hat, lsmdl$theta.hat, lsmdl$sigma.hat)\n int = lsmdl$intervals[1:(nlinks+2),]\n results_single[rowcnt:(rowcnt+3), c('est')] = est\n results_single[rowcnt:(rowcnt+2), c('quantile.1', 'quantile.5')] = int\n results_single[rowcnt:(rowcnt+3), c('run_time')] = lsmdl$time\n rowcnt = rowcnt + 4\n \n # process Bayes P1\n p1mdl = readRDS(paste0(RESULTS_DIR, \"SingleLink_Mdl/Bayes_p1/\", seed, \"_BayesModel_p1.rda\"))\n p1sum = summary(p1mdl$fit)\n results_single[rowcnt:(rowcnt+3),c('est', 'ts_se')] = p1sum$statistics[c('r[1]', 'r[2]', 'theta', 'sigma'),c('Mean', 'Time-series SE')]\n results_single[rowcnt:(rowcnt+3),c('quantile.1', 'quantile.2','quantile.3','quantile.4','quantile.5')] = p1sum$quantiles[c('r[1]', 'r[2]', 'theta', 'sigma'),]\n results_single[rowcnt:(rowcnt+3), c('neff')] = effectiveSize(p1mdl$fit)[c('r[1]', 'r[2]', 'theta', 'sigma')]\n results_single[rowcnt:(rowcnt+3), c('rhat')] = gelman.diag(p1mdl$fit)$psrf[c('r[1]', 'r[2]', 'theta', 'sigma'),1]\n results_single[rowcnt:(rowcnt+3), c('run_time')] = p1mdl$time \n rowcnt = rowcnt + 4\n \n # process Bayes P2\n p2mdl = readRDS(paste0(RESULTS_DIR, \"SingleLink_Mdl/Bayes_p2/\", seed, \"_BayesModel_p2.rda\"))\n p2sum = summary(p2mdl$fit)\n results_single[rowcnt:(rowcnt+3),c('est', 'ts_se')] = p2sum$statistics[c('r[1]', 'r[2]', 'theta', 'sigma'),c('Mean', 'Time-series SE')]\n results_single[rowcnt:(rowcnt+3),c('quantile.1', 'quantile.2','quantile.3','quantile.4','quantile.5')] = p2sum$quantiles[c('r[1]', 'r[2]', 'theta', 'sigma'),]\n results_single[rowcnt:(rowcnt+3), c('neff')] = effectiveSize(p2mdl$fit)[c('r[1]', 'r[2]', 'theta', 'sigma')]\n results_single[rowcnt:(rowcnt+3), c('rhat')] = gelman.diag(p2mdl$fit)$psrf[c('r[1]', 'r[2]', 'theta', 'sigma'),1]\n results_single[rowcnt:(rowcnt+3), c('run_time')] = p2mdl$time \n rowcnt = rowcnt + 4\n \n # process Bayes P3\n p3mdl = readRDS(paste0(RESULTS_DIR, \"SingleLink_Mdl/Bayes_p3/\", seed, \"_BayesModel_p3.rda\"))\n p3sum = summary(p3mdl$fit)\n results_single[rowcnt:(rowcnt+3),c('est', 'ts_se')] = p3sum$statistics[c('r[1]', 'r[2]', 'theta[1]', 'sigma'),c('Mean', 'Time-series SE')]\n results_single[rowcnt:(rowcnt+3),c('quantile.1', 'quantile.2','quantile.3','quantile.4','quantile.5')] = p3sum$quantiles[c('r[1]', 'r[2]', 'theta[1]', 'sigma'),]\n results_single[rowcnt:(rowcnt+3), c('neff')] = effectiveSize(p3mdl$fit)[c('r[1]', 'r[2]', 'theta[1]', 'sigma')]\n results_single[rowcnt:(rowcnt+3), c('rhat')] = gelman.diag(p3mdl$fit)$psrf[c('r[1]', 'r[2]', 'theta[1]', 'sigma'),1]\n results_single[rowcnt:(rowcnt+3), c('run_time')] = p3mdl$time \n rowcnt = rowcnt + 4\n \n # process Bayes P4\n p4mdl = readRDS(paste0(RESULTS_DIR, \"SingleLink_Mdl/Bayes_p4/\", seed, \"_BayesModel_p4.rda\"))\n p4sum = summary(p4mdl$fit)\n results_single[rowcnt:(rowcnt+3),c('est', 'ts_se')] = p4sum$statistics[c('r[1]', 'r[2]', 'theta', 'sigma'),c('Mean', 'Time-series SE')]\n results_single[rowcnt:(rowcnt+3),c('quantile.1', 'quantile.2','quantile.3','quantile.4','quantile.5')] = p4sum$quantiles[c('r[1]', 'r[2]', 'theta', 'sigma'),]\n results_single[rowcnt:(rowcnt+3), c('neff')] = effectiveSize(p4mdl$fit)[c('r[1]', 'r[2]', 'theta', 'sigma')]\n results_single[rowcnt:(rowcnt+3), c('rhat')] = gelman.diag(p4mdl$fit)$psrf[c('r[1]', 'r[2]', 'theta', 'sigma'),1]\n results_single[rowcnt:(rowcnt+3), c('run_time')] = p4mdl$time \n rowcnt = rowcnt + 4\n \n # process Bayes P5\n p5mdl = readRDS(paste0(RESULTS_DIR, \"SingleLink_Mdl/Bayes_p5/\", seed, \"_BayesModel_p5.rda\"))\n p5sum = summary(p5mdl$fit)\n results_single[rowcnt:(rowcnt+3),c('est', 'ts_se')] = p5sum$statistics[c('r[1]', 'r[2]', 'theta', 'sigma'),c('Mean', 'Time-series SE')]\n results_single[rowcnt:(rowcnt+3),c('quantile.1', 'quantile.2','quantile.3','quantile.4','quantile.5')] = p5sum$quantiles[c('r[1]', 'r[2]', 'theta', 'sigma'),]\n results_single[rowcnt:(rowcnt+3), c('neff')] = effectiveSize(p5mdl$fit)[c('r[1]', 'r[2]', 'theta', 'sigma')]\n results_single[rowcnt:(rowcnt+3), c('rhat')] = gelman.diag(p5mdl$fit)$psrf[c('r[1]', 'r[2]', 'theta', 'sigma'),1]\n results_single[rowcnt:(rowcnt+3), c('run_time')] = p5mdl$time \n rowcnt = rowcnt + 4\n \n}\n\n################################################################################\n# Double Link\n################################################################################\nresults_double = data.frame(pose = rep('DoubleLink', nmodels*5*nfiles),\n seed = rep(1:nfiles, each = nmodels*5),\n model = rep(rep(MODELS, each = 5),nfiles),\n parameter = rep(c('r1', 'r2', 'theta1', 'theta2', 'sigma'), nfiles*nmodels),\n est = NA,\n quantile = matrix(NA, nfiles*5*nmodels, 5),\n neff = NA,\n rhat = NA,\n ts_se = NA,\n run_time = NA)\n\nfiles = list.files(path = paste0(RESULTS_DIR, \"DoubleLink_Mdl/Bayes_p3\"))\nseeds = as.numeric(gsub(\"(.+?)(\\\\_.*)\", \"\\\\1\", files))\nseeds = seeds[order(seeds)]\nrowcnt = 1\nfor(i in 1:nfiles){\n nlinks = 2\n seed = seeds[i]\n print(sprintf(\"Processing Double Link file %.0f of %.0f\", i, nfiles))\n \n # process LS results\n lsmdl = readRDS(paste0(RESULTS_DIR, \"DoubleLink_Mdl/LS/\", seed, \"_LSModel.rda\"))\n est = c(lsmdl$r.hat, lsmdl$theta.hat, lsmdl$sigma.hat)\n int = lsmdl$intervals[1:(nlinks+2),]\n results_double[rowcnt:(rowcnt+4), c('est')] = est\n results_double[rowcnt:(rowcnt+3), c('quantile.1', 'quantile.5')] = int\n results_double[rowcnt:(rowcnt+4), c('run_time')] = lsmdl$time\n rowcnt = rowcnt + 5\n \n # process Bayes P1\n p1mdl = readRDS(paste0(RESULTS_DIR, \"DoubleLink_Mdl/Bayes_p1/\", seed, \"_BayesModel_p1.rda\"))\n p1sum = summary(p1mdl$fit)\n results_double[rowcnt:(rowcnt+4),c('est', 'ts_se')] = p1sum$statistics[c('r[1]', 'r[2]', 'theta[1]', 'theta[2]', 'sigma'),c('Mean', 'Time-series SE')]\n results_double[rowcnt:(rowcnt+4),c('quantile.1', 'quantile.2','quantile.3','quantile.4','quantile.5')] = p1sum$quantiles[c('r[1]', 'r[2]', 'theta[1]', 'theta[2]', 'sigma'),]\n results_double[rowcnt:(rowcnt+4), c('neff')] = effectiveSize(p1mdl$fit)[c('r[1]', 'r[2]', 'theta[1]','theta[2]', 'sigma')]\n results_double[rowcnt:(rowcnt+4), c('rhat')] = gelman.diag(p1mdl$fit)$psrf[c('r[1]', 'r[2]', 'theta[1]', 'theta[2]', 'sigma'), 1]\n results_double[rowcnt:(rowcnt+4), c('run_time')] = p1mdl$time\n rowcnt = rowcnt + 5\n \n # process Bayes P2\n p2mdl = readRDS(paste0(RESULTS_DIR, \"DoubleLink_Mdl/Bayes_p2/\", seed, \"_BayesModel_p2.rda\"))\n p2sum = summary(p2mdl$fit)\n results_double[rowcnt:(rowcnt+4),c('est', 'ts_se')] = p2sum$statistics[c('r[1]', 'r[2]', 'theta[1]', 'theta[2]', 'sigma'),c('Mean', 'Time-series SE')]\n results_double[rowcnt:(rowcnt+4),c('quantile.1', 'quantile.2','quantile.3','quantile.4','quantile.5')] = p2sum$quantiles[c('r[1]', 'r[2]', 'theta[1]','theta[2]', 'sigma'),]\n results_double[rowcnt:(rowcnt+4), c('neff')] = effectiveSize(p2mdl$fit)[c('r[1]', 'r[2]', 'theta[1]', 'theta[2]', 'sigma')]\n results_double[rowcnt:(rowcnt+4), c('rhat')] = gelman.diag(p2mdl$fit)$psrf[c('r[1]', 'r[2]', 'theta[1]', 'theta[2]', 'sigma'),1]\n results_double[rowcnt:(rowcnt+4), c('run_time')] = p2mdl$time\n rowcnt = rowcnt + 5\n \n # process Bayes P3\n p3mdl = readRDS(paste0(RESULTS_DIR, \"DoubleLink_Mdl/Bayes_p3/\", seed, \"_BayesModel_p3.rda\"))\n p3sum = summary(p3mdl$fit)\n results_double[rowcnt:(rowcnt+4),c('est', 'ts_se')] = p3sum$statistics[c('r[1]', 'r[2]', 'theta[1]', 'theta[2]', 'sigma'),c('Mean', 'Time-series SE')]\n results_double[rowcnt:(rowcnt+4),c('quantile.1', 'quantile.2','quantile.3','quantile.4','quantile.5')] = p3sum$quantiles[c('r[1]', 'r[2]', 'theta[1]', 'theta[2]', 'sigma'),]\n results_double[rowcnt:(rowcnt+4), c('neff')] = effectiveSize(p3mdl$fit)[c('r[1]', 'r[2]', 'theta[1]', 'theta[2]', 'sigma')]\n results_double[rowcnt:(rowcnt+4), c('rhat')] = gelman.diag(p3mdl$fit)$psrf[c('r[1]', 'r[2]', 'theta[1]', 'theta[2]', 'sigma'),1]\n results_double[rowcnt:(rowcnt+4), c('run_time')] = p3mdl$time\n rowcnt = rowcnt + 5\n \n # process Bayes P4\n p4mdl = readRDS(paste0(RESULTS_DIR, \"DoubleLink_Mdl/Bayes_p4/\", seed, \"_BayesModel_p4.rda\"))\n p4sum = summary(p4mdl$fit)\n results_double[rowcnt:(rowcnt+4),c('est', 'ts_se')] = p4sum$statistics[c('r[1]', 'r[2]','theta[1]', 'theta[2]', 'sigma'),c('Mean', 'Time-series SE')]\n results_double[rowcnt:(rowcnt+4),c('quantile.1', 'quantile.2','quantile.3','quantile.4','quantile.5')] = p4sum$quantiles[c('r[1]', 'r[2]', 'theta[1]', 'theta[2]', 'sigma'),]\n results_double[rowcnt:(rowcnt+4), c('neff')] = effectiveSize(p4mdl$fit)[c('r[1]', 'r[2]', 'theta[1]', 'theta[2]','sigma')]\n results_double[rowcnt:(rowcnt+4), c('rhat')] = gelman.diag(p4mdl$fit)$psrf[c('r[1]', 'r[2]', 'theta[1]', 'theta[2]','sigma'),1]\n results_double[rowcnt:(rowcnt+4), c('run_time')] = p4mdl$time \n rowcnt = rowcnt + 5\n \n # process Bayes P5\n p5mdl = readRDS(paste0(RESULTS_DIR, \"DoubleLink_Mdl/Bayes_p5/\", seed, \"_BayesModel_p5.rda\"))\n p5sum = summary(p5mdl$fit)\n results_double[rowcnt:(rowcnt+4),c('est', 'ts_se')] = p5sum$statistics[c('r[1]', 'r[2]', 'theta[1]', 'theta[2]', 'sigma'),c('Mean', 'Time-series SE')]\n results_double[rowcnt:(rowcnt+4),c('quantile.1', 'quantile.2','quantile.3','quantile.4','quantile.5')] = p5sum$quantiles[c('r[1]', 'r[2]', 'theta[1]', 'theta[2]', 'sigma'),]\n results_double[rowcnt:(rowcnt+4), c('neff')] = effectiveSize(p5mdl$fit)[c('r[1]', 'r[2]', 'theta[1]', 'theta[2]', 'sigma')]\n results_double[rowcnt:(rowcnt+4), c('rhat')] = gelman.diag(p5mdl$fit)$psrf[c('r[1]', 'r[2]', 'theta[1]', 'theta[2]', 'sigma'),1]\n results_double[rowcnt:(rowcnt+4), c('run_time')] = p5mdl$time \n rowcnt = rowcnt + 5\n \n}\n\n################################################################################\n# Triple Link\n################################################################################\nresults_triple = data.frame(pose = rep('TripleLink', nmodels*6*nfiles),\n seed = rep(1:nfiles, each = nmodels*6),\n model = rep(rep(MODELS, each = 6),nfiles),\n parameter = rep(c('r1', 'r2', 'theta1', 'theta2', 'theta3', 'sigma'), nfiles*nmodels),\n est = NA,\n quantile = matrix(NA, nfiles*6*nmodels, 5),\n neff = NA,\n rhat = NA,\n ts_se = NA,\n run_time = NA)\n\nfiles = list.files(path = paste0(RESULTS_DIR, \"TripleLink_Mdl/Bayes_p3\"))\nseeds = as.numeric(gsub(\"(.+?)(\\\\_.*)\", \"\\\\1\", files))\nseeds = seeds[order(seeds)]\nrowcnt = 1\nfor(i in 1:nfiles){\n nlinks = 3\n seed = seeds[i]\n print(sprintf(\"Processing Triple Link file %.0f of %.0f\", i, nfiles))\n \n # process LS results\n lsmdl = readRDS(paste0(RESULTS_DIR, \"TripleLink_Mdl/LS/\", seed, \"_LSModel.rda\"))\n est = c(lsmdl$r.hat, lsmdl$theta.hat, lsmdl$sigma.hat)\n int = lsmdl$intervals[1:(nlinks+2),]\n results_triple[rowcnt:(rowcnt+5), c('est')] = est\n results_triple[rowcnt:(rowcnt+4), c('quantile.1', 'quantile.5')] = int\n results_triple[rowcnt:(rowcnt+5), c('run_time')] = lsmdl$time\n rowcnt = rowcnt + 6\n \n # process Bayes P1\n p1mdl = readRDS(paste0(RESULTS_DIR, \"TripleLink_Mdl/Bayes_p1/\", seed, \"_BayesModel_p1.rda\"))\n p1sum = summary(p1mdl$fit)\n results_triple[rowcnt:(rowcnt+5),c('est', 'ts_se')] = p1sum$statistics[c('r[1]', 'r[2]', 'theta[1]', 'theta[2]', 'theta[3]', 'sigma'),c('Mean', 'Time-series SE')]\n results_triple[rowcnt:(rowcnt+5),c('quantile.1', 'quantile.2','quantile.3','quantile.4','quantile.5')] = p1sum$quantiles[c('r[1]', 'r[2]', 'theta[1]', 'theta[2]', 'theta[3]', 'sigma'),]\n results_triple[rowcnt:(rowcnt+5), c('neff')] = effectiveSize(p1mdl$fit)[c('r[1]', 'r[2]', 'theta[1]', 'theta[2]', 'theta[3]', 'sigma')]\n results_triple[rowcnt:(rowcnt+5), c('rhat')] = gelman.diag(p1mdl$fit)$psrf[c('r[1]', 'r[2]', 'theta[1]', 'theta[2]', 'theta[3]', 'sigma'), 1]\n results_triple[rowcnt:(rowcnt+5), c('run_time')] = p1mdl$time\n rowcnt = rowcnt + 6\n \n # process Bayes P2\n p2mdl = readRDS(paste0(RESULTS_DIR, \"TripleLink_Mdl/Bayes_p2/\", seed, \"_BayesModel_p2.rda\"))\n p2sum = summary(p2mdl$fit)\n results_triple[rowcnt:(rowcnt+5),c('est', 'ts_se')] = p2sum$statistics[c('r[1]', 'r[2]', 'theta[1]', 'theta[2]', 'theta[3]', 'sigma'),c('Mean', 'Time-series SE')]\n results_triple[rowcnt:(rowcnt+5),c('quantile.1', 'quantile.2','quantile.3','quantile.4','quantile.5')] = p2sum$quantiles[c('r[1]', 'r[2]', 'theta[1]', 'theta[2]', 'theta[3]', 'sigma'),]\n results_triple[rowcnt:(rowcnt+5), c('neff')] = effectiveSize(p2mdl$fit)[c('r[1]', 'r[2]', 'theta[1]', 'theta[2]', 'theta[3]', 'sigma')]\n results_triple[rowcnt:(rowcnt+5), c('rhat')] = gelman.diag(p2mdl$fit)$psrf[c('r[1]', 'r[2]', 'theta[1]', 'theta[2]', 'theta[3]', 'sigma'),1]\n results_triple[rowcnt:(rowcnt+5), c('run_time')] = p2mdl$time\n rowcnt = rowcnt + 6\n \n # process Bayes P2\n p3mdl = readRDS(paste0(RESULTS_DIR, \"TripleLink_Mdl/Bayes_p3/\", seed, \"_BayesModel_p3.rda\"))\n p3sum = summary(p3mdl$fit)\n results_triple[rowcnt:(rowcnt+5),c('est', 'ts_se')] = p3sum$statistics[c('r[1]', 'r[2]', 'theta[1]', 'theta[2]', 'theta[3]', 'sigma'),c('Mean', 'Time-series SE')]\n results_triple[rowcnt:(rowcnt+5),c('quantile.1', 'quantile.2','quantile.3','quantile.4','quantile.5')] = p3sum$quantiles[c('r[1]', 'r[2]', 'theta[1]', 'theta[2]', 'theta[3]', 'sigma'),]\n results_triple[rowcnt:(rowcnt+5), c('neff')] = effectiveSize(p3mdl$fit)[c('r[1]', 'r[2]', 'theta[1]', 'theta[2]', 'theta[3]', 'sigma')]\n results_triple[rowcnt:(rowcnt+5), c('rhat')] = gelman.diag(p3mdl$fit)$psrf[c('r[1]', 'r[2]', 'theta[1]', 'theta[2]', 'theta[3]', 'sigma'),1]\n results_triple[rowcnt:(rowcnt+5), c('run_time')] = p3mdl$time\n rowcnt = rowcnt + 6\n \n # process Bayes P4\n p4mdl = readRDS(paste0(RESULTS_DIR, \"TripleLink_Mdl/Bayes_p4/\", seed, \"_BayesModel_p4.rda\"))\n p4sum = summary(p4mdl$fit)\n results_triple[rowcnt:(rowcnt+5),c('est', 'ts_se')] = p4sum$statistics[c('r[1]', 'r[2]','theta[1]', 'theta[2]', 'theta[3]', 'sigma'),c('Mean', 'Time-series SE')]\n results_triple[rowcnt:(rowcnt+5),c('quantile.1', 'quantile.2','quantile.3','quantile.4','quantile.5')] = p4sum$quantiles[c('r[1]', 'r[2]', 'theta[1]', 'theta[2]', 'theta[3]', 'sigma'),]\n results_triple[rowcnt:(rowcnt+5), c('neff')] = effectiveSize(p4mdl$fit)[c('r[1]', 'r[2]', 'theta[1]', 'theta[2]', 'theta[3]','sigma')]\n results_triple[rowcnt:(rowcnt+5), c('rhat')] = gelman.diag(p4mdl$fit)$psrf[c('r[1]', 'r[2]', 'theta[1]', 'theta[2]', 'theta[3]','sigma'),1]\n results_triple[rowcnt:(rowcnt+5), c('run_time')] = p4mdl$time \n rowcnt = rowcnt + 6\n \n # process Bayes P5\n p5mdl = readRDS(paste0(RESULTS_DIR, \"TripleLink_Mdl/Bayes_p5/\", seed, \"_BayesModel_p5.rda\"))\n p5sum = summary(p5mdl$fit)\n results_triple[rowcnt:(rowcnt+5),c('est', 'ts_se')] = p5sum$statistics[c('r[1]', 'r[2]', 'theta[1]', 'theta[2]', 'theta[3]', 'sigma'),c('Mean', 'Time-series SE')]\n results_triple[rowcnt:(rowcnt+5),c('quantile.1', 'quantile.2','quantile.3','quantile.4','quantile.5')] = p5sum$quantiles[c('r[1]', 'r[2]', 'theta[1]', 'theta[2]', 'theta[3]', 'sigma'),]\n results_triple[rowcnt:(rowcnt+5), c('neff')] = effectiveSize(p5mdl$fit)[c('r[1]', 'r[2]', 'theta[1]', 'theta[2]', 'theta[3]', 'sigma')]\n results_triple[rowcnt:(rowcnt+5), c('rhat')] = gelman.diag(p5mdl$fit)$psrf[c('r[1]', 'r[2]', 'theta[1]', 'theta[2]', 'theta[3]', 'sigma'),1]\n results_triple[rowcnt:(rowcnt+5), c('run_time')] = p5mdl$time \n rowcnt = rowcnt + 6\n \n}\n\n################################################################################\n# Combine and save\n################################################################################\nprint(\"Combing files\")\nresults = rbind(results_single, results_double, results_triple)\nprint(\"Saving Results...\")\n\nsaveRDS(results, file = paste0(RESULTS_DIR, 'results/results_', format(Sys.time(), \"%d%m%Y\"),\".rda\"))\nwrite.table(results, file = paste0(RESULTS_DIR, 'results/results_', format(Sys.time(), \"%d%m%Y\"),\".csv\"), sep = ',', col.names = TRUE, row.names = FALSE)\nprint(\"Complete!\")\n", "meta": {"hexsha": "f100654d0d3d80b727e8bf464f15f35913fb0a17", "size": 19044, "ext": "r", "lang": "R", "max_stars_repo_path": "src/process_results.r", "max_stars_repo_name": "AndyPohlNZ/BayesKin", "max_stars_repo_head_hexsha": "1eac3d30f09491d8b371a433e4621a53a2b5d2ef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/process_results.r", "max_issues_repo_name": "AndyPohlNZ/BayesKin", "max_issues_repo_head_hexsha": "1eac3d30f09491d8b371a433e4621a53a2b5d2ef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/process_results.r", "max_forks_repo_name": "AndyPohlNZ/BayesKin", "max_forks_repo_head_hexsha": "1eac3d30f09491d8b371a433e4621a53a2b5d2ef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 64.5559322034, "max_line_length": 189, "alphanum_fraction": 0.5745641672, "num_tokens": 6492, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.668880247169804, "lm_q2_score": 0.5964331462646255, "lm_q1q2_score": 0.3989423502937466}} {"text": "# Function to find nodes that can be realistically dated by the Hedman technique:\r\nfind.dateable.nodes <- function(tree, tip.ages) {\r\n\r\n\t# Requires ape library for reading tree structure:\r\n\trequire(ape)\r\n\t\r\n\t# List all internal nodes except root:\r\n\tlist.nodes <- (Ntip(tree) + 2):(Ntip(tree) + Nnode(tree))\r\n\t\r\n\t# Create vector to store nodes that are dateable:\r\n\tdefo.nodes <- vector(mode=\"numeric\")\r\n\t\r\n\t# For each node in the list:\r\n\tfor(i in length(list.nodes):1) {\r\n\t\t\r\n\t\t# Find descendant nodes:\r\n\t\tdescs <- tree$edge[grep(TRUE, tree$edge[, 1] == list.nodes[i]), 2]\r\n\t\t\r\n\t\t# If all immediate descendants are internal nodes than it cannot be dated and is removed:\r\n\t\tif(length(which(descs > Ntip(tree))) == length(descs)) list.nodes <- list.nodes[-i]\r\n\t\t\r\n\t\t# If all immediate descendants are terminal nodes than it can definitely be dated...:\r\n\t\tif(length(which(descs <= Ntip(tree))) == length(descs)) {\r\n\t\t\t\r\n\t\t\t# ...and is retained...:\r\n\t\t\tdefo.nodes <- c(defo.nodes, list.nodes[i])\r\n\t\t\t\r\n\t\t\t# ...but can be removed from list.nodes:\r\n\t\t\tlist.nodes <- list.nodes[-i]\r\n\t\t\r\n\t\t}\r\n\t\r\n\t}\r\n\t\r\n\t# For each internal node with both a terminal and internal node descendant:\r\n\tfor(i in length(list.nodes):1) {\r\n\t\t\r\n\t\t# Find node age:\r\n\t\tnode.age <- max(tip.ages[FindDescendants(list.nodes[i], tree)])\r\n\t\t\r\n\t\t# List its descendants:\r\n\t\tdescs.ages <- descs <- tree$edge[grep(TRUE, tree$edge[, 1] == list.nodes[i]), 2]\r\n\t\t\r\n\t\t# For each descendant:\r\n\t\tfor(j in length(descs.ages):1) {\r\n\t\t\t\r\n\t\t\t# If an internal node date as oldest descendant:\r\n\t\t\tif(descs[j] > Ntip(tree)) descs.ages[j] <- max(tip.ages[FindDescendants(descs[j], tree)])\r\n\t\t\t\r\n\t\t\t# Remove if terminal node:\r\n\t\t\tif(descs[j] <= Ntip(tree)) descs.ages <- descs.ages[-j]\r\n\t\t\t\r\n\t\t}\r\n\t\t\r\n\t\t# If node age is older than any descendant internal nodes:\r\n\t\tif(node.age > max(descs.ages)) {\r\n\t\t\t\r\n\t\t\t# Then can be dated so add to list:\r\n\t\t\tdefo.nodes <- c(defo.nodes, list.nodes[i])\r\n\t\t\t\r\n\t\t}\r\n\t\t\r\n\t}\r\n\t\r\n\t# Output all dateable nodes:\r\n\treturn(defo.nodes)\r\n\r\n}\r\n\r\n# Function that retrieves dates for use as tnodes variable in Hedman function\r\nget.tnodes <- function(node, tree, tip.ages) {\r\n\t\r\n\t# Require ape library:\r\n\trequire(ape)\r\n\t\r\n\t# Number of root node (point at which searching for ancestral nodes stops):\r\n\troot.node <- Ntip(tree) + 1\r\n\t\r\n\t# If the input node is the root node:\r\n\tif(node == root.node) {\r\n\t\t\r\n\t\t# Error and warning:\r\n\t\tstop(\"ERROR: Input node is root node - tnodes has length one!\")\r\n\t\t\r\n\t# If input node is not root node:\r\n\t} else {\r\n\t\t\r\n\t\t# Find first ancestor node:\r\n\t\tinternodes <- tree$edge[match(node, tree$edge[, 2]), 1]\r\n\t\t\r\n\t\t# As long as we have not yet reached the root:\r\n\t\twhile(internodes[length(internodes)] != root.node) {\r\n\t\t\t\r\n\t\t\t# Add next internode to set:\r\n\t\t\tinternodes <- c(internodes, tree$edge[match(internodes[length(internodes)], tree$edge[, 2]), 1])\r\n\t\t}\r\n\t\t\r\n\t\t# Add in original node as that is counted too!:\r\n\t\tinternodes <- c(node, internodes)\r\n\t\t\r\n\t\t# Create tnodes vector for storage:\r\n\t\ttnodes <- vector(mode=\"numeric\")\r\n\t\t\r\n\t\t# Date first (original) node:\r\n\t\ttnodes[1] <- max(tip.ages[FindDescendants(internodes[1], tree)])\r\n\t\t\r\n\t\t# For each internode:\r\n\t\tfor(i in 2:length(internodes)) {\r\n\t\t\t\r\n\t\t\t# Find descendants:\r\n\t\t\tdescs <- tree$edge[grep(TRUE, tree$edge[, 1] == internodes[i]), 2]\r\n\t\t\t\r\n\t\t\t# Remove previously dated node:\r\n\t\t\tdescs <- descs[-match(internodes[(i - 1)], descs)]\r\n\t\t\t\r\n\t\t\t# For each other descendant:\r\n\t\t\tfor(j in 1:length(descs)) {\r\n\t\t\t\t\r\n\t\t\t\t# If descendant node is internal:\r\n\t\t\t\tif(descs[j] > Ntip(tree)) {\r\n\t\t\t\t\t\r\n\t\t\t\t\t# Get maximum possible age:\r\n\t\t\t\t\tdescs[j] <- max(tip.ages[FindDescendants(descs[j], tree)])\r\n\t\t\t\t\t\r\n\t\t\t\t# If descendant node is terminal:\r\n\t\t\t\t} else {\r\n\t\t\t\t\t\r\n\t\t\t\t\t# Get maximum possible age:\r\n\t\t\t\t\tdescs[j] <- tip.ages[descs[j]]\r\n\t\t\t\t\r\n\t\t\t\t}\r\n\t\t\t\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t# Store in tnodes:\r\n\t\t\ttnodes[i] <- max(descs)\r\n\t\t\r\n\t\t}\r\n\t\t\r\n\t\t# Vector for storing node ages to be deleted:\r\n\t\tdeletes <- vector(mode=\"numeric\")\r\n\t\t\r\n\t\t# For each potential tnode:\r\n\t\tfor(i in 2:length(tnodes)) {\r\n\t\t\t\r\n\t\t\t# Find nodes too young for dating and store in deletes:\r\n\t\t\tif(max(tnodes[1:(i-1)]) > tnodes[i]) deletes <- c(deletes, i)\r\n\t\t\t\r\n\t\t}\r\n\t\t\r\n\t\t# Remove these nodes (if there are any) from tnodes:\r\n\t\tif(length(deletes) > 0) tnodes <- tnodes[-deletes]\r\n\t\t\r\n\t\t# Give in order from oldest to youngest:\r\n\t\ttnodes <- rev(tnodes)\r\n\t\t\r\n\t\t# Return tnodes:\r\n\t\treturn(tnodes)\r\n\t\t\r\n\t}\r\n\t\r\n}\r\n\r\n# Hedman (2010) method for estimating confidence given ages of ougroups (tnodes is the sequence of ages, from oldest to youngest; t0 is the arbitrary lower stratigraphic bound; resolution is the number of steps to take between the FAD and the lower stratigraphic bound):\r\nHedman.2010 <- function (tnodes, t0, resolution) { # Outputs estimate with two-tailed 95% CIs\r\n \r\n # Check t0 is older than any other node age:\r\n if(!all(t0 > tnodes)) stop(\"t0 must be older than any tnode value.\")\r\n \r\n\t# Store requested resolution:\r\n\trequested.resolution <- resolution\r\n\t\r\n\t# Function returns p.d.f. for node ages\t(t0 is an arbitrary oldest age to consider, tnodes are the ages of oldest known fossil stemming from each node, and tsteps is a vector of arbitrary time steps on which the p.d.f. is calculated):\r\n\tnodeage <- function(tsteps, tnodes, t0) {\r\n\r\n\t\t# Get number of outgroups (tnodes):\r\n\t\tnn <- length(tnodes)\r\n\t\t\r\n\t\t# Get number of time steps (resolution):\r\n\t\tnt <- length(tsteps)\r\n\t\t\r\n\t\t# Initialize array:\r\n\t\tpnodes <- matrix(0, nn, nt)\r\n\t\t\r\n\t\t# First get pdf for node 1, at discrete values:\r\n\t\tii <- which(tsteps > t0 & tsteps < tnodes[1])\r\n\t\t\r\n\t\t# Assume uniform distribution for oldest node:\r\n\t\tpnodes[1, ii] <- 1.0 / length(ii)\r\n\t\t\r\n\t\t# Cycle through remaining nodes:\r\n\t\tfor (i in 2:nn) {\r\n\t\t\t\r\n\t\t\t# Cycle through series of time steps:\r\n\t\t\tfor (j in 1:nt) {\r\n\t\t\t\t\r\n\t\t\t\t# Initialize vector:\r\n\t\t\t\tp21 <- rep(0, nt)\r\n\t\t\t\t\r\n\t\t\t\t# Get p.d.f. for ith node ay discrete values:\r\n\t\t\t\tii <- which(tsteps >= tsteps[j] & tsteps < tnodes[i])\r\n\t\t\t\t\r\n\t\t\t\t\r\n\t\t\t\tp21[ii] <- 1.0 / length(ii) * pnodes[(i - 1), j]\r\n\t\t\t\t\r\n\t\t\t\t# Conditional probability of this age, given previous node age, times probability of previous node age, added to cumulative sum:\r\n\t\t\t\tpnodes[i, ii] <- pnodes[i, ii] + p21[ii]\r\n\t\t\t\t\r\n\t\t\t}\r\n\t\t\t\r\n\t\t}\r\n\t\t\r\n\t\t# Get just the p.d.f. vector for the youngest node:\r\n\t\tout <- pnodes[nn, ]\r\n\t\t\r\n\t\t# Return output:\r\n\t\treturn(out)\r\n\t\t\r\n\t}\r\n\t\r\n\t# Calculate c.d.f. from p.d.f., find median and 95% credibility limits:\r\n\tHedmanAges <- function(tnodes, t0, resolution) {\r\n\t\r\n\t\t# Store input resolution for later reuse:\r\n\t\told.resolution <- resolution\r\n\t\r\n\t\t# Get uniformly spaced p-values (including 95% limits adn median) for calculating CIs:\r\n\t\tCIs <- sort(unique(c(0.025, 0.975, 0.5, c(1:old.resolution) * (1 / old.resolution))))\r\n\t\r\n\t\t# Get enw resolution (may be longer by adding limits and/or median):\r\n\t\tresolution <- length(CIs)\r\n\t\r\n\t\t# Get oldest possible age to consider:\r\n\t\tfirst <- t0\r\n\t\r\n\t\t# Get youngest possible age to consider:\r\n\t\tlast <- min(tnodes)\r\n\t\r\n\t\t# Make tnodes negative for Hedman function:\r\n\t\ttnodes <- -tnodes\r\n\t\r\n\t\t# Get uniformly spaced time steps for Hedman function:\r\n\t\ttsteps <- seq(-first, -last, length=resolution)\r\n\r\n\t\t# Make t0 negative for Hedman function:\r\n\t\tt0 <- -t0\r\n\t\r\n\t\t# Run Hedman function to get p.d.f.:\r\n\t\tvector <- nodeage(tsteps, tnodes, t0)\r\n\t\r\n\t\t# Convert from p-value scale to age scale:\r\n\t\tintegral.vector <- vector * ((abs(first - last)) / resolution)\r\n\t\r\n\t\t# Get sum of probabilities in order to re-scale as p.d.f.:\r\n\t\tprobability.sum <- sum(integral.vector)\r\n\t\r\n\t\t# Get re-scaled p-values for CIs:\r\n\t\tps.CIs <- probability.sum * CIs\r\n\t\r\n\t\t# Cretae empty vector to store dates:\r\n\t\tdate.distribution <- vector(mode=\"numeric\")\r\n\t\r\n\t\t# Set initial value:\r\n\t\tvalue <- 0\r\n\t\r\n\t\t# For each re-scaled p-value:\r\n\t\tfor(i in length(ps.CIs):1) {\r\n\t\t\r\n\t\t\t# Update value:\r\n\t\t\tvalue <- value + integral.vector[i]\r\n\t\t\r\n\t\t\t# If in age window:\r\n\t\t\tif(length(which(value >= ps.CIs)) > 0) {\r\n\r\n\t\t\t\t# Store dates:\r\n\t\t\t\tdate.distribution <- c(date.distribution, rep(tsteps[i], length(which(value >= ps.CIs))))\r\n\t\t\t\r\n\t\t\t\t# Update re-scaled p-values:\r\n\t\t\t\tps.CIs <- ps.CIs[-grep(TRUE, value >= ps.CIs)]\r\n\t\t\t\r\n\t\t\t}\r\n\t\t\r\n\t\t}\r\n\t\r\n\t\t# Add t0 at end if length is short:\r\n\t\twhile(length(date.distribution) < resolution) date.distribution <- c(date.distribution, t0)\r\n\r\n\t\t# Find median of distribution:\r\n\t\tBest.guess <- date.distribution[CIs == 0.5]\r\n\t\t\t\r\n\t\t# Get upper 95% CI:\r\n\t\tBest.guess.lower <- date.distribution[CIs == 0.975]\r\n\t\t\r\n\t\t# Get lower 95% CI:\r\n\t\tBest.guess.upper <- date.distribution[CIs == 0.025]\r\n\t\t\r\n\t\t# Combine results and reverse sign to give palaeo ages:\r\n\t\tresults <- list(-Best.guess, -Best.guess.lower, -Best.guess.upper, -date.distribution[match(c(c(1:old.resolution) * (1 / old.resolution)), CIs)])\r\n\t\t\r\n\t\t# Name subvariables:\r\n\t\tnames(results) <- c(\"Best.guess\", \"Best.guess.lower\", \"Best.guess.upper\", \"Age.distribution\")\r\n\t\t\r\n\t\t# Return result\r\n\t\treturn(results)\r\n\t\t\r\n\t}\r\n\t\r\n\t# Get Hedman ages:\r\n\tout <- HedmanAges(tnodes, t0, resolution)\r\n\t\r\n\t# If Hedman ages represent less than five unique values (leading to downstream problem of flat distributions):\r\n\twhile(length(unique(out$Age.distribution[round(seq(1, length(out$Age.distribution), length.out=requested.resolution))])) < 5) {\r\n\t\t\r\n\t\t# Double the resolution size:\r\n\t\tresolution <- resolution * 2\r\n\t\t\r\n\t\t# Get Hedman ages:\r\n\t\tout <- HedmanAges(tnodes, t0, resolution)\r\n\t\t\r\n\t}\r\n\t\r\n\t# Update output:\r\n\tout$Age.distribution <- out$Age.distribution[round(seq(1, length(out$Age.distribution), length.out=requested.resolution))]\r\n\t\r\n\t# Return output:\r\n\treturn(out)\r\n\t\r\n}\r\n\r\n# Over-arching Hedman tree-dating function:\r\nHedman.tree.dates <- function(tree, tip.ages, outgroup.ages, t0, resolution = 1000, conservative = TRUE) {\r\n\t\r\n# MORE CONDITIONALS NEEDED FOR WHEN RESOLUTION IS LOW\r\n\r\n\t# Load libraries:\r\n\trequire(ape)\r\n\trequire(strap)\r\n \r\n # Check tree is fully bifurcating:\r\n if(!is.binary.tree(tree)) stop(\"Tree must be fully bifurcating.\")\r\n \r\n\t# Ensure tip ages are in tree tip order:\r\n\ttip.ages <- tip.ages[tree$tip.label]\r\n\r\n\t# Find root node:\r\n\troot.node <- Ntip(tree) + 1\r\n\t\r\n\t# Create variables to store age estimates:\r\n\tage.estimates <- matrix(nrow = Nnode(tree), ncol = 3)\r\n\t\r\n\t# Create variables to store age distributions:\r\n\tage.distributions <- matrix(nrow = Nnode(tree), ncol = resolution)\r\n\t\r\n\t# Set column headings:\r\n\tcolnames(age.estimates) <- c(\"Best.guess\", \"Best.guess.lower\", \"Best.guess.upper\")\r\n\r\n\t# Set row names:\r\n\trownames(age.estimates) <- rownames(age.distributions) <- c((Ntip(tree) + 1):(Ntip(tree) + Nnode(tree)))\r\n\t\r\n\t# Vector to store outgroup sequences:\r\n\tog.seq <- vector(mode = \"numeric\")\r\n\r\n\t# Report progress:\r\n\tcat(\"Identifying nodes that are date-able using the Hedman technique_\")\r\n\t\r\n\t# Find dateable conservative nodes:\r\n\tif(conservative) dateable.nodes <- find.dateable.nodes(tree, tip.ages)\r\n\t\r\n\t# Find dateable non-conservative nodes:\r\n\tif(!conservative) dateable.nodes <- c((Ntip(tree) + 1):(Ntip(tree) + Nnode(tree)))\r\n\r\n\t# Report progress:\r\n\tcat(\"Done\\nDating nodes using Hedman technique_\")\r\n\r\n\t# If not using the conservative approach:\r\n\tif(!conservative) {\r\n\r\n\t\t# Create ages matrix:\r\n\t\tages <- cbind(tip.ages, tip.ages)\r\n\r\n\t\t# Add rownames:\r\n\t\trownames(ages) <- names(tip.ages)\r\n\r\n\t\t# Add column names:\r\n\t\tcolnames(ages) <- c(\"FAD\", \"LAD\")\r\n\r\n\t\t# Sort by taxon order in tree:\r\n\t\tages <- ages[tree$tip.label, ]\r\n\r\n\t\t# Date tree using basic algorithm:\r\n\t\tstree <- DatePhylo(tree, ages, 0, \"basic\", FALSE)\r\n\r\n\t\t# Get node ages:\r\n\t\tsages <- GetNodeAges(stree)\r\n\r\n\t\t# Set first outgroup sequence (i.e. root) as this is special case:\r\n\t\tog.seq[1] <- paste(c(outgroup.ages, sages[root.node]), collapse = \"%%\")\r\n\r\n\t\t# For each non-root node:\r\n\t\tfor(i in 2:length(dateable.nodes)) {\r\n\t\t\t\r\n\t\t\t# Identify node:\r\n\t\t\tnode <- dateable.nodes[i]\r\n\t\t\t\r\n\t\t\t# Find preceding node:\r\n\t\t\tinternodes <- tree$edge[match(node, tree$edge[, 2]), 1] \r\n\t\t\t\r\n\t\t\t# Keep going until we reach the root and add next internode to set:\r\n\t\t\twhile(internodes[length(internodes)] != root.node) internodes <- c(internodes, tree$edge[match(internodes[length(internodes)], tree$edge[, 2]), 1])\r\n\t\t\t\r\n\t\t\t# Collate nodes and put in order:\r\n\t\t\tinternodes <- sort(c(node, internodes))\r\n\t\t\t\r\n\t\t\t# Find outgroup age sequence and collaspe to single string and store:\r\n\t\t\tog.seq[i] <- paste(c(outgroup.ages, sages[internodes]), collapse=\"%%\")\r\n\r\n\t\t}\r\n\r\n\t# If using the conservative approach:\r\n\t} else {\r\n\r\n\t\t# Find age estimates for each dateable node:\r\n\t\tfor(i in 1:length(dateable.nodes)) {\r\n\t\t\r\n\t\t\t# Find tnodes for a specific node:\r\n\t\t\ttnodes <- get.tnodes(dateable.nodes[i], tree, tip.ages)\r\n\t\t\r\n\t\t\t# Add additional outgroup tnodes:\r\n\t\t\ttnodes <- c(outgroup.ages, tnodes)\r\n\r\n\t\t\t# Turn outgroup sequence into single string and store:\r\n\t\t\tog.seq[i] <- paste(tnodes, collapse=\"%%\")\r\n\t\t\t\r\n\t\t}\r\n\r\n\t}\r\n\t\r\n\t# Get unique outgroup sequences:\r\n\tunq.og.seq <- unique(og.seq)\r\n\r\n\t# For each unique outgroup sequence:\r\n\tfor(i in 1:length(unq.og.seq)) {\r\n\t\t\r\n\t\t# List nodes with this outgroup sequence:\r\n\t\tnodes <- dateable.nodes[which(og.seq == unq.og.seq[i])]\r\n\t\t\r\n\t\t# Define tnodes:\r\n\t\ttnodes <- as.numeric(strsplit(unq.og.seq[i], \"%%\")[[1]])\r\n\r\n\t\t# Get Hedman dates:\r\n\t\thedman.out <- Hedman.2010(tnodes = tnodes, t0 = t0, resolution = resolution)\r\n\t\t\r\n\t\t# Update age distributions:\r\n for(j in 1:length(nodes)) age.distributions[as.character(nodes[j]), ] <- hedman.out$Age.distribution\r\n\t\t\r\n\t}\r\n\t\r\n\t# Separate check to see if root is dateable (first find root descendants that are tips, if any):\r\n\troot.desc.tips <- sort(tree$tip.label[tree$edge[which(root.node == tree$edge[, 1]), 2]])\r\n\t\r\n\t# Now check that there are descendants that are tips:\r\n\tif(length(root.desc.tips) > 0) {\r\n\t\t\r\n\t\t# Get maximum root descendant age:\r\n\t\troot.tip.age <- max(tip.ages[root.desc.tips])\r\n\r\n\t\t# Now check that descendants are older than any other tips and get Hedman dates for root and update age distributions:\r\n\t\tif(root.tip.age > max(tip.ages[setdiff(tree$tip.label, root.desc.tips)])) age.distributions[as.character(root.node), ] <- Hedman.2010(tnodes = c(outgroup.ages, root.tip.age), t0 = t0, resolution = resolution)$Age.distribution\r\n\t\t\r\n\t}\r\n\r\n\t# If not using the conservative approach:\r\n\tif(conservative == FALSE) {\r\n\t\r\n\t\t# Report progress:\r\n\t\tcat(\"Done\\nIdentifying remaining undated nodes_\")\r\n\t\t\r\n\t\t# Report progress:\r\n\t\tcat(\"Done\\nDating remaining undated nodes using randomisation technique_\")\r\n\r\n\t# If using the conservative approach:\r\n\t} else {\r\n\r\n\t\t# Report progress:\r\n\t\tcat(\"Done\\nIdentifying remaining undated nodes_\")\r\n\t\t\r\n\t\t# Find undated nodes by first establishing actually dated nodes:\r\n\t\tdated.nodes <- sort(dateable.nodes)\r\n\t\t\r\n\t\t# List all internal nodes:\r\n\t\tall.nodes <- (Ntip(tree) + 1):(Ntip(tree) + Nnode(tree))\r\n\t\t\r\n\t\t# Get undated nodes:\r\n\t\tundated.nodes <- setdiff(all.nodes, dated.nodes)\r\n\t\t\r\n\t\t# Find branches that define undated nodes:\r\n\t\tinternal.branches <- tree$edge[which(tree$edge[, 2] > Ntip(tree)), ]\r\n\t\t\r\n\t\t# Is root dated? (default to \"yes\" before actually checking):\r\n\t\troot.dated <- \"Yes\"\r\n\t\t\r\n\t\t# If the root is undated (then it needs to be):\r\n\t\tif(is.na(match(root.node, dated.nodes))) {\r\n\t\t\t\r\n\t\t\t# Update root.dated:\r\n\t\t\troot.dated <- \"no\"\r\n\t\t\t\r\n\t\t\t# Create tnodes from outgroup ages ONLY (this will later be used to constrain the root age through the saem randomisation process as the other undated nodes):\r\n\t\t\ttnodes <- outgroup.ages\r\n\t\t\t\r\n\t\t\t# Date root node:\r\n\t\t\thedman.out <- Hedman.2010(tnodes = tnodes, t0 = t0, resolution = resolution)\r\n\t\t\t\r\n\t\t\t# Add to age estimates:\r\n\t\t\tage.estimates <- rbind(age.estimates, c(hedman.out$Best.guess, hedman.out$Best.guess.lower, hedman.out$Best.guess.upper))\r\n\t\t\t\r\n\t\t\t# Add to age distributions:\r\n\t\t\tage.distributions <- rbind(age.distributions, hedman.out$Age.distribution)\r\n\t\t\t\r\n\t\t\t# Add node name 0:\r\n\t\t\trownames(age.estimates)[length(rownames(age.estimates))] <- rownames(age.distributions)[length(rownames(age.distributions))] <- \"0\"\r\n\t\t\t\r\n\t\t}\r\n\t\t\r\n\t\t# Vector for storing strings of sequences of undated node(s) bound by dated nodes:\r\n\t\tanc.strings.trimmed <- anc.strings <- vector(mode = \"character\")\r\n\t\t\r\n\t\t# Work through dated nodes to find sequences of undated nodes bracketed by them:\r\n\t\tfor(i in 1:length(dated.nodes)) {\r\n\t\t\t\r\n\t\t\t# As long as the dated node is not the root (which has no ancestors):\r\n\t\t\tif(dated.nodes[i] != root.node) {\r\n\t\t\t\t\r\n\t\t\t\t# Get ancestors:\r\n\t\t\t\tancestors <- internal.branches[which(internal.branches[, 2] == dated.nodes[i]), 1]\r\n\t\t\t\t\r\n\t\t\t\t# As long as the ancestor is neither the root or a dated node:\r\n\t\t\t\tif(ancestors != root.node && length(sort(match(ancestors, dated.nodes))) == 0) {\r\n\t\t\t\t\t\r\n\t\t\t\t\t# And as long as it remains so find next ancestral node:\r\n\t\t\t\t\twhile(ancestors[length(ancestors)] != root.node && length(sort(match(ancestors[length(ancestors)], dated.nodes))) == 0) ancestors <- c(ancestors, internal.branches[match(ancestors[length(ancestors)], internal.branches[, 2]), 1])\r\n\t\t\t\t\t\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\t# Add initial dated node:\r\n\t\t\t\tancestors <- c(dated.nodes[i], ancestors)\r\n\t\t\t\t\r\n\t\t\t\t# Only need retain those with at least one undated node between dated nodes:\r\n\t\t\t\tif(length(ancestors) > 2) {\r\n\t\t\t\t\t\r\n\t\t\t\t\t# Add to ancestor strings:\r\n\t\t\t\t\tanc.strings <- c(anc.strings, paste(ancestors, collapse = \" \"))\r\n\t\t\t\t\t\r\n\t\t\t\t\t# Add to trimmed ancestor strings:\r\n\t\t\t\t\tanc.strings.trimmed <- c(anc.strings.trimmed, paste(ancestors[2:(length(ancestors) - 1)], collapse = \" \"))\r\n\t\t\t\t\t\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t}\r\n\t\t\t\r\n\t\t}\r\n\t\t\r\n\t\t# If root is undated then anc.strings with the root present must be modified to include node 0 at the end:\r\n\t\tif(root.dated == \"no\") {\r\n\t\t\t\r\n\t\t\t# Go through each anc.string:\r\n\t\t\tfor(i in 1:length(anc.strings)) {\r\n\t\t\t\t\r\n\t\t\t\t# Get ancestors vector:\r\n\t\t\t\tancestors <- as.numeric(strsplit(anc.strings[i], \" \")[[1]])\r\n\t\t\t\t\r\n\t\t\t\t# If last node is the root:\r\n\t\t\t\tif(ancestors[length(ancestors)] == root.node) {\r\n\t\t\t\t\t\r\n\t\t\t\t\t# Add 0 node to end:\r\n\t\t\t\t\tancestors <- c(ancestors, 0)\r\n\t\t\t\t\t\r\n\t\t\t\t\t# Re-store in anc.strings:\r\n\t\t\t\t\tanc.strings[i] <- paste(ancestors, collapse = \" \")\r\n\t\t\t\t\t\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t}\r\n\t\t\t\r\n\t\t}\r\n\t\t\r\n\t\t# Find oldest node from each ancestral sequence (first set up empty vector):\r\n\t\toldest.nodes <- vector(mode=\"numeric\")\r\n\t\t\r\n\t\t# Go through each anc.string:\r\n\t\tfor(i in 1:length(anc.strings)) {\r\n\t\t\t\r\n\t\t\t# Get ancestors vector:\r\n\t\t\tancestors <- as.numeric(strsplit(anc.strings[i], \" \")[[1]])\r\n\t\t\t\r\n\t\t\t# Store oldest node:\r\n\t\t\toldest.nodes <- c(oldest.nodes, ancestors[length(ancestors)])\r\n\t\t\t\r\n\t\t}\r\n\t\t\r\n\t\t# Collapse to unique oldest nodes only:\r\n\t\toldest.nodes <- sort(unique(oldest.nodes))\r\n\t\t\r\n\t\t# Clump anc.strings by shared oldest node (i.e. blocks that will be dated at the same time) - first create empty vector:\r\n\t\tclumped.anc.strings <- vector(mode=\"character\")\r\n\t\t\r\n\t\t# For each oldest node find anc.strings with oldest node and collapse with %%:\r\n\t\tfor(i in 1:length(oldest.nodes)) clumped.anc.strings <- c(clumped.anc.strings, paste(anc.strings[grep(paste(\" \", oldest.nodes[i], sep = \"\"), anc.strings)], collapse = \"%%\"))\r\n\r\n\t\t# Report progress:\r\n\t\tcat(\"Done\\nDating remaining undated nodes using randomisation technique_\")\r\n\t\t\r\n\t\t# Can now date undated nodes using random draws from bounding Hedman dated nodes:\r\n\t\tfor(i in 1:length(clumped.anc.strings)) {\r\n\t\t\t\r\n\t\t\t# First retrieve anc.strings with shared oldest node:\r\n\t\t\tanc.strings <- strsplit(clumped.anc.strings[i], \"%%\")[[1]]\r\n\t\t\t\r\n\t\t\t# Get young dated nodes (for drawing from for upper bounds):\r\n\t\t\tyoung.dated.nodes <- vector(mode=\"numeric\")\r\n\t\t\t\r\n\t\t\t# For each ancestor string find youngest dated node, i.e., lower bounds::\r\n\t\t\tfor(j in 1:length(anc.strings)) young.dated.nodes <- c(young.dated.nodes, as.numeric(strsplit(anc.strings[j], \" \")[[1]][1]))\r\n\t\t\t\r\n\t\t\t# Get age distributions for young dated nodes:\r\n\t\t\tyoung.distributions <- age.distributions[as.character(young.dated.nodes), ]\r\n\t\t\t\r\n\t\t\t# Force into a single row matrix if only a vector:\r\n\t\t\tif(!is.matrix(young.distributions)) young.distributions <- t(as.matrix(young.distributions))\r\n\t\t\t\r\n\t\t\t# Set young distribution half up from young distributions:\r\n\t\t\tyoung.distributions.old.half <- young.distributions\r\n\t\t\t\r\n\t\t\t# Get old half as age distributions for young dated nodes:\r\n\t\t\tfor(j in 1:length(apply(young.distributions, 1, median))) {\r\n\t\t\t\t\r\n\t\t\t\t# As long as the median is not the maximum:\r\n\t\t\t\tif(max(young.distributions[j, ]) > median(young.distributions[j, ])) {\r\n\t\t\t\t\t\r\n\t\t\t\t\t# Split distribution into older half using median:\r\n\t\t\t\t\ttemp.distribution <- young.distributions[j, which(young.distributions[j, ] > median(young.distributions[j, ]))]\r\n\t\t\t\t\t\r\n\t\t\t\t# If the median is the maximum:\r\n\t\t\t\t} else {\r\n\t\t\t\t\t\r\n\t\t\t\t\t# Just use the maximum:\r\n\t\t\t\t\ttemp.distribution <- max(young.distributions[j, ])\r\n\t\t\t\t\t\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\t# ???:\r\n\t\t\t\tyoung.distributions.old.half[j, ] <- c(temp.distribution, rep(NA, length(young.distributions[j, ]) - length(temp.distribution)))\r\n\t\t\t\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t# Get old dated node (for drawing from for lower bounds):\r\n\t\t\told.dated.node <- as.numeric(strsplit(anc.strings[1], \" \")[[1]][length(strsplit(anc.strings[1], \" \")[[1]])])\r\n\t\t\t\r\n\t\t\t# Get age distributions for old dated node:\r\n\t\t\told.distribution <- age.distributions[as.character(old.dated.node), ]\r\n\t\t\t\r\n\t\t\t# As long as the median is not the minimum:\r\n\t\t\tif(min(old.distribution) < median(old.distribution)) {\r\n\t\t\t\t\r\n\t\t\t\t# Split distribution using median:\r\n\t\t\t\told.distribution.young.half <- old.distribution[which(old.distribution < median(old.distribution))]\r\n\t\t\t\t\r\n\t\t\t# If the median is the minimum:\r\n\t\t\t} else {\r\n\t\t\t\t\r\n\t\t\t\t# Just use the minimum:\r\n\t\t\t\told.distribution.young.half <- min(old.distribution)\r\n\t\t\t\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t# Get undated nodes (vector for storing output):\r\n\t\t\tundated.nodes <- vector(mode=\"numeric\")\r\n\t\t\t\r\n\t\t\t# For each anc.string:\r\n\t\t\tfor(j in 1:length(anc.strings)) {\r\n\t\t\t\t\r\n\t\t\t\t# Get ancestors:\r\n\t\t\t\tancestors <- strsplit(anc.strings[j], \" \")[[1]]\r\n\t\t\t\t\r\n\t\t\t\t# Store undated nodes:\r\n\t\t\t\tundated.nodes <- c(undated.nodes, as.numeric(ancestors[2:(length(ancestors) - 1)]))\r\n\t\t\t\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t# Collapse to unique nodes only:\r\n\t\t\tundated.nodes <- sort(unique(undated.nodes))\r\n\t\t\t\r\n\t\t\t# Find young constraints for each undated node (vector for storing results):\r\n\t\t\tyoung.constraints <- vector(mode = \"numeric\")\r\n\t\t\t\r\n\t\t\t# For each undated node add young constraints to list:\r\n\t\t\tfor(j in 1:length(undated.nodes)) young.constraints <- c(young.constraints, paste(young.dated.nodes[grep(paste(\" \", undated.nodes[j], sep = \"\"), anc.strings)], collapse = \" \"))\r\n\t\t\t\r\n\t\t\t# Find old constraints for each undated node (i.e. all nodes that are lower in tree as these will potentially be dated first and replace the current oldest age; vector for storing results):\r\n\t\t\told.constraints <- vector(mode=\"numeric\")\r\n\t\t\t\r\n\t\t\t# For each undated node:\r\n\t\t\tfor(j in 1:length(undated.nodes)) {\r\n\t\t\t\t\r\n\t\t\t\t# Get just anc.strings where undated node is present:\r\n\t\t\t\tnode.strings <- anc.strings[grep(paste(\" \", undated.nodes[j], sep=\"\"), anc.strings)]\r\n\t\t\t\t\r\n\t\t\t\t# Vector for storing older nodes:\r\n\t\t\t\tolder.nodes <- vector(mode=\"numeric\")\r\n\t\t\t\t\r\n\t\t\t\t# For each anc.string where the undated node exists ?????:\r\n\t\t\t\tfor(k in 1:length(node.strings)) older.nodes <- c(older.nodes, as.numeric(strsplit(strsplit(node.strings[k], undated.nodes[j])[[1]][2], \" \")[[1]]))\r\n\t\t\t\t\r\n\t\t\t\t# ????:\r\n\t\t\t\told.constraints <- c(old.constraints, paste(unique(sort(older.nodes)), collapse=\" \"))\r\n\t\t\t\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\t# Find undated nodes constrained by dated nodes (vector for storage):\r\n\t\t\tyoung.dated.nodes.constrain <- vector(mode = \"character\")\r\n\t\t\t\r\n\t\t\t# For each young dated node constraint find undated nodes which it contrains:\r\n\t\t\tfor(j in 1:length(young.dated.nodes)) young.dated.nodes.constrain[j] <- paste(as.numeric(strsplit(anc.strings[j], \" \")[[1]][2:(length(strsplit(anc.strings[j], \" \")[[1]]) - 1)]), collapse = \" \")\r\n\t\t\t\r\n\t\t\t# Main dating loop (repeats random draw N times, where N is defined by the variable resolution):\r\n\t\t\tfor(j in 1:resolution) {\r\n\t\t\t\t\r\n\t\t\t\t# Modify age distributions used if medians of undated nodes exceed bounds of medians of dated nodes (needs to have been at least two entries already):\r\n\t\t\t\tif(j >= 3 && j >= floor(resolution / 2)) {\r\n\t\t\t\t\t\r\n\t\t\t\t\t# If there is more than one undated node establish present medians for undated nodes:\r\n\t\t\t\t\tif(length(undated.nodes) > 1) undated.medians <- apply(age.distributions[as.character(undated.nodes), 1:(j - 1)], 1, median)\r\n\t\t\t\t\t\r\n\t\t\t\t\t# If there is only one undated node\r\n\t\t\t\t\tif(length(undated.nodes) == 1) {\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t# Establish present median of undated node:\r\n\t\t\t\t\t\tundated.medians <- median(age.distributions[as.character(undated.nodes), 1:(j - 1)])\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t# Add name for reference later:\r\n\t\t\t\t\t\tnames(undated.medians) <- as.character(undated.nodes)\r\n\t\t\t\t\t\r\n\t\t\t\t\t}\r\n\t\t\t\t\t\r\n\t\t\t\t\t# Case if oldest median of the undated nodes exceeds the median of the bounding old dated node:\r\n\t\t\t\t\tif(max(undated.medians) >= median(sort(old.distribution))) {\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t# Update active distribution with older half only (to force undated nodes towards median ages consistent with dated nodes):\r\n\t\t\t\t\t\tactive.old.distribution <- old.distribution.young.half\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t# If oldest median ages do not conflict:\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t# Draw from full distribution:\r\n\t\t\t\t\t\tactive.old.distribution <- old.distribution\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t}\r\n\t\t\t\t\t\r\n\t\t\t\t\t# Set default active young distributions:\r\n\t\t\t\t\tactive.young.distributions <- young.distributions\r\n\t\t\t\t\t\r\n\t\t\t\t\t# For each young (top bounding) dated node:\r\n\t\t\t\t\tfor(k in 1:length(young.dated.nodes)) {\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t# Case if youngest median of the undated nodes exceeds the median of the bounding young dated node - update active distribution with younger half only (to force undated nodes towards median ages consistent with dated nodes):\r\n\t\t\t\t\t\tif(min(undated.medians[strsplit(young.dated.nodes.constrain[k], \" \")[[1]]]) <= median(sort(age.distributions[as.character(young.dated.nodes[k]), ]))) active.young.distributions[k, ] <- young.distributions.old.half[k, ]\r\n\t\t\t\t\t\r\n\t\t\t\t\t}\r\n\t\t\t\t\t\r\n\t\t\t\t# Case if still in first half of resolution:\r\n\t\t\t\t} else {\r\n\t\t\t\t\t\r\n\t\t\t\t\t# Use uncorrected distribution for upper bound:\r\n\t\t\t\t\tactive.old.distribution <- old.distribution\r\n\t\t\t\t\t\r\n\t\t\t\t\t# Use uncorrected distributions for lower bound:\r\n\t\t\t\t\tactive.young.distributions <- young.distributions\r\n\t\t\t\t\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\t# Special case of last iteration where we want to ensure we draw a date between the constraining medians:\r\n\t\t\t\tif(j == resolution) {\r\n\t\t\t\t\t\r\n\t\t\t\t\t# Set old distribution to young half only:\r\n\t\t\t\t\tactive.old.distribution <- old.distribution.young.half\r\n\t\t\t\t\t\r\n\t\t\t\t\t# Set default active young distributions:\r\n\t\t\t\t\tactive.young.distributions <- young.distributions\r\n\t\t\t\t\t\r\n\t\t\t\t\t# For each young (top bounding) dated node set all young distribution to old half only:\r\n\t\t\t\t\tfor(k in 1:length(young.dated.nodes)) active.young.distributions[k, ] <- young.distributions.old.half[k, ]\r\n\t\t\t\t\t\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\t# Modify young and old distributions to remove tails which will always violate node order (young node older than old node and vice versa) to speed up the random draw step below; if part of young distributions are older than the oldest part of the old distribution:\r\n\t\t\t\tif(max(sort(as.vector(active.young.distributions))) >= max(sort(active.old.distribution))) {\r\n\t\t\t\t\r\n\t\t\t\t\t# Find oldest part of old distribution\r\n\t\t\t\t\tupper.limit <- max(sort(active.old.distribution))\r\n\t\t\t\t\t\r\n\t\t\t\t\t# ????:\r\n\t\t\t\t\tactive.young.distributions[which(active.young.distributions >= upper.limit)] <- NA\r\n\t\t\t\t\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\t# Vector to store young distribution minima:\r\n\t\t\t\tactive.young.distribution.mins <- vector(mode=\"numeric\")\r\n\t\t\t\t\r\n\t\t\t\t# For each young node store minima:\r\n\t\t\t\tfor(k in 1:length(active.young.distributions[, 1])) active.young.distribution.mins <- c(active.young.distribution.mins, min(sort(active.young.distributions[k, ])))\r\n\t\t\t\t\r\n\t\t\t\t# If part of old distribution is younger than the youngest part of the youngest young distribution:\r\n\t\t\t\tif(min(sort(active.old.distribution)) <= min(active.young.distribution.mins)) {\r\n\t\t\t\t\t\r\n\t\t\t\t\t# Find lower limit (minimum of minima):\r\n\t\t\t\t\tlower.limit <- min(active.young.distribution.mins)\r\n\t\t\t\t\t\r\n\t\t\t\t\t# Remove values less than or equal to the lower limit from the old distribution:\r\n\t\t\t\t\tactive.old.distribution <- active.old.distribution[grep(FALSE, active.old.distribution <= lower.limit)]\r\n\t\t\t\t\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\t# Draw upper and lower bounds at random from old and young nodes:\r\n\t\t\t\tyoung.random.ages <- vector(mode=\"numeric\")\r\n\t\t\t\t\r\n\t\t\t\t# For each young node draw a random age from its distributon:\r\n\t\t\t\tfor(k in 1:length(young.dated.nodes)) young.random.ages <- c(young.random.ages, sort(active.young.distributions[k, ])[ceiling(runif(1, 0, length(sort(active.young.distributions[k, ]))))])\r\n\t\t\t\t\r\n\t\t\t\t# Repeat for old age:\r\n\t\t\t\told.random.age <- sort(active.old.distribution)[ceiling(runif(1, 0, length(sort(active.old.distribution))))]\r\n\r\n\t\t\t\t# Ensure old node is older than all young nodes; while old node is younger or equal in age to oldest young nodes:\r\n\t\t\t\twhile(old.random.age <= max(young.random.ages)) {\r\n\t\t\t\t\t\r\n\t\t\t\t\t# Re-draw ages as above:\r\n\t\t\t\t\tyoung.random.ages <- vector(mode=\"numeric\")\r\n\t\t\t\t\t\r\n\t\t\t\t\t# For each young node draw a random age from its distributon:\r\n\t\t\t\t\tfor(k in 1:length(young.dated.nodes)) young.random.ages <- c(young.random.ages, sort(active.young.distributions[k, ])[ceiling(runif(1, 0, length(sort(active.young.distributions[k, ]))))])\r\n\t\t\t\t\t\r\n\t\t\t\t\t# Repeat for old age:\r\n\t\t\t\t\told.random.age <- sort(active.old.distribution)[ceiling(runif(1, 0, length(sort(active.old.distribution))))]\r\n\t\t\t\t\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\t# Need to add names so can extract data later:\r\n\t\t\t\tnames(young.random.ages) <- young.dated.nodes\r\n\t\t\t\t\r\n\t\t\t\t# Find oldest (i.e. constraining) young node for each undated node (vector for storing output):\r\n\t\t\t\tyoung.constraints.node <- young.constraints.age <- vector(mode=\"numeric\")\r\n\t\t\t\t\r\n\t\t\t\t# For each undated node:\r\n\t\t\t\tfor(k in 1:length(undated.nodes)) {\r\n\t\t\t\t\t\r\n\t\t\t\t\t# Store young age:\r\n\t\t\t\t\tyoung.constraints.age <- c(young.constraints.age, max(young.random.ages[strsplit(young.constraints[k], \" \")[[1]]]))\r\n\t\t\t\t\t\r\n\t\t\t\t\t# Store young node:\r\n\t\t\t\t\tyoung.constraints.node <- c(young.constraints.node, as.numeric(names(young.random.ages[strsplit(young.constraints[k], \" \")[[1]]])[which(young.random.ages[strsplit(young.constraints[k], \" \")[[1]]] == max(young.random.ages[strsplit(young.constraints[k], \" \")[[1]]]))[1]]))\r\n\t\t\t\t\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\t# Vector for storing node dates:\r\n\t\t\t\tnode.dates <- rep(NA, length(undated.nodes))\r\n\t\t\t\t\r\n\t\t\t\t# Date undated nodes using randomisation process:\r\n\t\t\t\tfor(k in 1:length(unique(young.constraints.node)) ) {\r\n\t\t\t\t\t\r\n\t\t\t\t\t# Find top.node:\r\n\t\t\t\t\ttop.node <- unique(young.constraints.node)[k]\r\n\t\t\t\t\t\r\n\t\t\t\t\t# Find target (.e. undated) nodes:\r\n\t\t\t\t\ttarget.nodes <- undated.nodes[which(young.constraints.node == top.node)]\r\n\t\t\t\t\t\r\n\t\t\t\t\t# Find bounding dates (potential old constraints):\r\n\t\t\t\t\told.constraining.nodes <- as.numeric(sort(unique(strsplit(paste(old.constraints[match(target.nodes, undated.nodes)], collapse=\" \"), \" \")[[1]])))\r\n\t\t\t\t\t\r\n\t\t\t\t\t# Remove any target nodes present\r\n\t\t\t\t\tif(length(sort(match(target.nodes, old.constraining.nodes))) > 0) old.constraining.nodes <- old.constraining.nodes[-sort(match(target.nodes, old.constraining.nodes))]\r\n\t\t\t\t\t\r\n\t\t\t\t\t# Find youngest old node as actual constraint:\r\n\t\t\t\t\told.constraining.node <- max(old.constraining.nodes)\r\n\t\t\t\t\t\r\n\t\t\t\t\t# If lower bound is the previously dated old node:\r\n\t\t\t\t\tif(old.constraining.node == old.dated.node) {\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t# Use that as maximum limit\r\n\t\t\t\t\t\tmax <- old.random.age\r\n\t\t\t\t\t\r\n\t\t\t\t\t# If lower bound is a previously undated node:\r\n\t\t\t\t\t} else {\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t\t# Use that as maximum limit\r\n\t\t\t\t\t\tmax <- node.dates[match(old.constraining.node, undated.nodes)]\r\n\t\t\t\t\t\t\r\n\t\t\t\t\t}\r\n\t\t\t\t\t\r\n\t\t\t\t\t# Set minimum age:\r\n\t\t\t\t\tmin <- young.random.ages[as.character(top.node)]\r\n\t\t\t\t\t\r\n\t\t\t\t\t# Get node dates:\r\n\t\t\t\t\tnode.dates[match(target.nodes, undated.nodes)] <- sort(runif(length(target.nodes), min = min, max = max), decreasing = TRUE) # Draw node ages from bounding minima and maxima\r\n\t\t\t\t\r\n\t\t\t\t}\r\n\t\t\t\t\r\n\t\t\t\t# Store results:\r\n\t\t\t\tage.distributions[as.character(undated.nodes), j] <- node.dates\r\n\t\t\t\t\r\n\t\t\t}\r\n\t\t\t\r\n\t\t}\r\n\t\t\r\n\t\t# Can now remove node \"0\" (i.e., if root is undated by Hedman method) if present:\r\n\t\tif(root.dated == \"no\") {\r\n\t\t\t\r\n\t\t\t# Remove zero node from distributions:\r\n\t\t\tage.distributions <- age.distributions[-which(rownames(age.distributions) == \"0\"), ]\r\n\t\t\r\n\t\t\t# Remove zero node from estimates:\r\n\t\t\tage.estimates <- age.estimates[-which(rownames(age.estimates) == 0), ]\r\n\t\r\n\t\t}\r\n\r\n\t}\r\n\t\r\n\t# Report progress:\r\n\tcat(\"Done\\nTidying up and returning results_\")\r\n\r\n\t# Create vector of nodes estimated using Hedman method:\r\n\tHedman.estimated <- rep(1, length(rownames(age.estimates)))\r\n\t\r\n\t# Update those not estimated using Hedman method:\r\n\tif(conservative == TRUE) Hedman.estimated[match(setdiff(rownames(age.estimates), dateable.nodes), rownames(age.estimates))] <- 0\r\n\t\r\n\t# Add to age estimates:\r\n\tage.estimates <- cbind(age.estimates, Hedman.estimated)\r\n\t\r\n\t# Sort age distributions in advance of picking confidence intervals:\r\n\tage.distributions <- t(apply(age.distributions, 1, sort))\r\n\t\r\n\t# Add median values to age estimates:\r\n\tage.estimates[, \"Best.guess\"] <- apply(age.distributions, 1, median)\r\n\t\r\n\t# Add upper CI to age estimates:\r\n\tage.estimates[, \"Best.guess.upper\"] <- age.distributions[, ceiling(0.975 * resolution)]\r\n\t\r\n\t# Add lower CI to age estimates:\r\n\tage.estimates[, \"Best.guess.lower\"] <- age.distributions[, max(c(1, floor(0.025 * resolution)))]\r\n\r\n\t# Create vectors to store node ages for each branch:\r\n\tto.ages <- from.ages <- age.estimates[match(tree$edge[, 1], rownames(age.estimates)), \"Best.guess\"]\r\n\t\r\n\t# Get to ages for terminal branches:\r\n\tto.ages[which(tree$edge[, 2] <= Ntip(tree))] <- tip.ages[tree$edge[which(tree$edge[, 2] <= Ntip(tree)), 2]]\r\n\t\r\n\t# Get to ages for internal branches:\r\n\tto.ages[which(tree$edge[, 2] > Ntip(tree))] <- age.estimates[match(tree$edge[which(tree$edge[, 2] > Ntip(tree)), 2], rownames(age.estimates)), \"Best.guess\"]\r\n\t\r\n\t# Update tree with branch lengths scaled to time using median ages:\r\n\ttree$edge.length <- from.ages-to.ages\r\n\t\r\n\t# Update tree to include root time:\r\n\ttree$root.time <- age.estimates[as.character(root.node), \"Best.guess\"]\r\n\t\r\n\t# Collate results:\r\n\tresults <- list(age.estimates, age.distributions, tree)\r\n\t\r\n\t# Add names:\r\n\tnames(results) <- c(\"age.estimates\", \"age.distributions\", \"tree\")\r\n\t\r\n\t# Repprt progress\r\n\tcat(\"Done\")\r\n\t\r\n\t# Return output:\r\n\treturn(results)\r\n\t\r\n}", "meta": {"hexsha": "dcb6b34caa9dc9bfe8e39f1952c2ca53fc3584e8", "size": 34650, "ext": "r", "lang": "R", "max_stars_repo_path": "Evolutionary rates analysis (Fig 5d-e and Supplementary Fig 2-4)/cal3/Hedman_functions.r", "max_stars_repo_name": "SusanaGutarra/Plesiosaur-hydrodynamics-evolution", "max_stars_repo_head_hexsha": "68f9903bcc9885d9bf551191dffb3e86beb676a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Evolutionary rates analysis (Fig 5d-e and Supplementary Fig 2-4)/cal3/Hedman_functions.r", "max_issues_repo_name": "SusanaGutarra/Plesiosaur-hydrodynamics-evolution", "max_issues_repo_head_hexsha": "68f9903bcc9885d9bf551191dffb3e86beb676a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Evolutionary rates analysis (Fig 5d-e and Supplementary Fig 2-4)/cal3/Hedman_functions.r", "max_forks_repo_name": "SusanaGutarra/Plesiosaur-hydrodynamics-evolution", "max_forks_repo_head_hexsha": "68f9903bcc9885d9bf551191dffb3e86beb676a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.4657113613, "max_line_length": 276, "alphanum_fraction": 0.6455411255, "num_tokens": 9341, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6370307806984444, "lm_q2_score": 0.6261241772283034, "lm_q1q2_score": 0.3988603734339173}} {"text": "\n\n#' Model fitting\n#' \n#' @description This function fits the occupancy model of Diana et al. (2021). \n#' Note that in the following the parameters are described with the notations used in the paper.\n#' \n#' @param data The data frame containing the data.\n#' @param index_year The index of the column containing the year variable.\n#' @param index_site The index of the column containing the site variable.\n#' @param index_occ The index of the column containing the detections.\n#' @param index_spatial_x The index of the x coordinate of the site.\n#' @param index_spatial_y The index of the y coordinate of the site. \n#' @param covariates_psi_text Indexes of the column of the occupancy probability. To be separated by a comma, eg. \"5,6,8\". Set to \"0\" if no covariate is available\n#' @param covariates_p_text Indexes of the column of the detection probability. \n#' @param prior_psi Prior mean for the occupancy probability\n#' @param sigma_psi Standard deviation for the prior on the occupancy probability\n#' @param prior_p Prior mean for the detection probability\n#' @param sigma_p Standard deviation for the prior on the detection probability\n#' @param usingYearDetProb Should the model include year-specific detection probabilities (as opposed to a constant one)?\n#' @param usingSpatial Should the model include the auto-correlated spatial effects?\n#' @param gridStep Step of the grid to use for the approximation of the auto-correlated spatial effects. Use \\code{\\link{buildSpatialGrid}} to show the grid for a value of \\code{gridStep}.\n#' @param storeRE Should the model store the site-specific independent random effects for each iteration (instead of just their mean across all chain)? Not suggested if the number of sites is greater than 1000.\n#' @param nchain Number of chains.\n#' @param nburn Number of burn-in iterations.\n#' @param niter Number of (non burn-in) iterations.\n#' @param verbose Should the progress of the MCMC be printed?.\n#' @param computeGOF Should the model perform calculations of the goodness of fit?\n#' \n#' @importFrom magrittr %>%\n#' \n#' @export\n#' \n#' @return \n#' A list with components:\n#' \n#' \\itemize{\n#' \n#' \\item \\code{modelResults} A list with components:\n#' \n#' \\describe{\n#' \n#' \\item{\\code{beta_psi_output}}{ An array of dimensions \\code{nchain} x \\code{niter} x (number of coefficients for \n#' occupancy probability) containing the values of the coefficients of the occupancy probability.\n#' The coefficients are reported in the order (year r.e., space r.e., covariates for time-space interaction,\n#' standard covariates).}\n#' \n#' \\item{\\code{eps_unique_output}}{ if \\code{storeRE = T}, an array of dimensions \n#' \\code{nchain} x \\code{niter} x S containing the values of the site-specific independent random effects\n#' of the occupancy probability. If \\code{storeRE = F}, a matrix of dimensions \\code{nchain} x S \n#' containing the mean value of the random effect across a chain.}\n#' \n#' \\item{\\code{beta_p_output}}{ An array of dimensions \\code{nchain} x \\code{niter} x (number of coefficients for \n#' detection probability) containing the values of the coefficients of the detection probability.\n#' The coefficients are reported in the order (intercepts, covariates).}\n#' \n#' \\item{\\code{sigma_T_output}}{ A array of dimensions \\code{nchain} x \\code{niter} containing the values of\n#' \\eqn{\\sigma_T}.}\n#' \n#' \\item{\\code{l_T_output}}{ A array of dimensions \\code{nchain} x \\code{niter} containing the values of\n#' \\eqn{l_T}.}\n#' \n#' \\item{\\code{sigma_s_output}}{ A array of dimensions \\code{nchain} x \\code{niter} containing the values of\n#' \\eqn{\\sigma_S}.}\n#' \n#' \\item{\\code{l_s_output}}{ A array of dimensions \\code{nchain} x \\code{niter} containing the values of\n#' \\eqn{l_S}.}\n#' \n#' \\item{\\code{sigma_eps_output}}{ A array of dimensions \\code{nchain} x \\code{niter} containing the values of\n#' \\eqn{\\sigma_\\epsilon}.}\n#' \n#' \\item{\\code{psi_mean_output}}{ A array of dimensions \\code{nchain} x \\code{niter} containing the values of\n#' the occupancy index.}\n#' \n#' \\item{\\code{GOF_output}}{ A list with components:\n#' \n#' \\describe{\n#' \n#' \\item{ \\code{gofYear_output} }{An array of dimensions \\code{nchain} x \\code{niter} x Y containing the values \n#' of the test statistics of yearly detections.}\n#' \n#' \\item{ \\code{gofSpace_output} }{An array of dimensions \\code{nchain} x \\code{niter} x (M), where M is the number\n#' of regions in the approximation, containing the values of the test statistics of the detections in\n#' each region.}\n#' \n#' \\item{ \\code{trueYearStatistics} }{ A vector containing the true values of the test statistics of the detections\n#' in each year.}\n#' \n#' \\item{ \\code{trueSpaceStatistics} }{ A vector containing the true values of the test statistics of the detections\n#' in each region}\n#' \n#' }\n#' \n#' }\n#' \n#' }\n#' \n#' \n#' \\item \\code{dataCharacteristics}: A list with components:\n#' \n#' \\describe{\n#' \n#' \\item{\\code{Years}}{A vector with the years.}\n#' \n#' \\item{\\code{X_tilde}}{A matrix of dimension M x 2, where M is the number of points chosen in the \n#' spatial approximation, with the location of the points used for the approximation. The points are\n#' arranged in the same as order as in the coefficients vector \\code{beta_psi_output}.}\n#' \n#' \\item{\\code{gridStep}}{The width of the grid chosen in the approximation.}\n#' \n#' \\item{\\code{usingSptial}}{Same as in the input.}\n#' \n#' \\item{\\code{usingYearDetProb}}{Same as in the input.}\n#' \n#' \n#' }\n#' }\n#' \n#' @examples\n#' \n#' modelResults <- runModel(sampleData, \n#' index_year = 1, \n#' index_site = 2, \n#' index_occ = 8, \n#' index_spatial_x = 3, \n#' index_spatial_y = 4, \n#' covariates_psi_text = \"5\", \n#' covariates_p_text = \"6-7\", \n#' usingSpatial = TRUE,\n#' gridStep = .2, \n#' nchain = 1, \n#' nburn = 100,\n#' niter = 100) \n#' \nrunModel <- function(data, index_year, index_site, \n index_occ, index_spatial_x = 0, index_spatial_y = 0,\n covariates_psi_text, covariates_p_text, \n prior_psi = .5, sigma_psi = 2,\n prior_p = .5, sigma_p = 2, \n usingYearDetProb = F,\n usingSpatial = F, gridStep,\n storeRE = F, nchain, nburn, niter, \n verbose = T, computeGOF = T){\n \n print(\"Analyzing the data..\")\n \n # CLEAN DATA \n {\n \n colnames(data)[c(index_year, index_site, index_occ)] <- c(\"Year\",\"Site\",\"Occ\") \n \n if(usingSpatial){\n colnames(data)[c(index_spatial_x, index_spatial_y)] <- c(\"X_sp\",\"Y_sp\") \n } \n \n data$Year <- as.numeric(data$Year)\n \n S <- length(unique(data$Site))\n Y <- length(unique(data$Year))\n years <- sort(unique(data$Year))\n \n # transform site codes to numbers\n originalsites <- unique(data$Site)\n names(originalsites) <- seq_along(originalsites)\n data$Site <- as.numeric(names(originalsites)[match(data$Site, originalsites)])\n \n data <- data %>% dplyr::arrange(Site, Year)\n \n # define data for occupancies\n \n {\n k_s <- data %>% dplyr::group_by(Year, Site) %>% \n dplyr::summarise(Occupied = as.numeric(sum(Occ) > 0),\n Visits = dplyr::n()) %>% \n dplyr::arrange(Site, Year) \n k_s <- as.data.frame(k_s)\n \n # match row in data_p to row in k_s\n indexes_occobs <- rep(1:nrow(k_s), k_s$Visits)\n \n Occs <- data$Occ\n }\n \n # covariate for psi\n \n {\n \n X_psi <- data[!duplicated(data[,c(\"Site\",\"Year\")]),] %>% dplyr::arrange(Site, Year)\n \n # year covariates\n {\n X_psi$Year <- as.factor(X_psi$Year)\n X_psi_year <- stats::model.matrix( ~ . - 1, data = X_psi[,c(\"Year\"),drop = F])\n \n X_y_index <- apply(X_psi_year, 1, function(x) {which(x != 0)})\n X_y_index <- unlist(X_y_index)\n \n }\n \n # spatial covariates\n {\n \n if(usingSpatial){\n \n X_sp <- X_psi$X_sp\n Y_sp <- X_psi$Y_sp\n \n uniqueIndexesSite <- which(!duplicated(X_psi$Site))\n X_sp_unique <- X_sp[uniqueIndexesSite]\n Y_sp_unique <- Y_sp[uniqueIndexesSite]\n XY_sp_unique <- cbind(X_sp_unique, Y_sp_unique)\n \n # build the grid\n X_tilde <- as.matrix(buildGrid(XY_sp_unique, gridStep))\n XY_centers <- findClosestPoint(XY_sp_unique, X_tilde)\n \n # get rid of unused cells by refinding the grid\n X_tilde <- X_tilde[sort(unique(XY_centers)),]\n \n # refit\n XY_centers <- findClosestPoint(cbind(X_psi$X_sp,X_psi$Y_sp), X_tilde)\n XY_centers_unique <- findClosestPoint(XY_sp_unique, X_tilde)\n \n X_psi$Center <- as.factor(XY_centers)\n X_s_index <- XY_centers\n \n X_psi_s <- stats::model.matrix( ~ . - 1, data = X_psi[,c(\"Center\"),drop = F])\n \n X_centers <- nrow(X_tilde)\n \n } else {\n X_centers <- 0\n XY_centers <- NULL\n X_psi_s <- NULL\n XY_sp_unique <- NULL\n X_s_index <- numeric(0)\n X_tilde <- NULL\n gridStep <- NULL\n }\n \n }\n \n # time space covariates \n {\n numTimeSpaceCov <- 0\n \n X_psi_yearcov <- scale(as.numeric(X_psi$Year))\n X_psi_yearcov_values <- sort(unique(X_psi_yearcov))\n \n if(usingSpatial){\n \n X_psi_spcov <- cbind(X_sp, Y_sp)\n \n X_timesp_cov <- cbind(X_psi_yearcov * X_sp, X_psi_yearcov * Y_sp)\n \n numTimeSpaceCov <- numTimeSpaceCov + 2\n \n } else {\n X_timesp_cov <- NULL\n }\n \n }\n \n # standard covariates\n {\n \n column_covariate_psi <- ExtractCovariatesFromText(covariates_psi_text)\n \n nameVariables_psi <- colnames(data)[column_covariate_psi]\n ncov_psi <- length(nameVariables_psi)\n \n if(ncov_psi > 0){\n \n X_psi_cov <- stats::model.matrix(~ ., data = X_psi[,column_covariate_psi,drop = F])[,-1] \n \n } \n \n }\n \n X_psi <- cbind(X_psi_year)\n if(usingSpatial) X_psi <- cbind(X_psi, X_psi_s, X_timesp_cov)\n if(ncov_psi > 0) X_psi <- cbind(X_psi, X_psi_cov)\n \n }\n \n # covariates for p\n \n {\n data_p <- data\n \n column_covariate_p <- ExtractCovariatesFromText(covariates_p_text)\n \n X_p_cov <- data_p[,column_covariate_p, drop = F]\n \n ncov_p <- ncol(X_p_cov)\n \n if(ncov_p > 0){\n nameVariables_p <- colnames(data_p)[column_covariate_p] \n } else {\n nameVariables_p <- c()\n }\n \n if(usingYearDetProb){\n \n data_p$Year <- as.factor(data_p$Year)\n X_p_year <- stats::model.matrix( ~ . - 1, data = data_p[,c(\"Year\"),drop = F])\n \n X_y_index_p <- apply(X_p_year, 1, function(x) {which(x != 0)})\n X_y_index_p <- unlist(X_y_index_p)\n \n X_p <- X_p_year\n } else {\n X_p <- matrix(1, nrow = nrow(data_p), ncol = 1)\n X_y_index_p <- rep(1, nrow(data_p))\n }\n \n if(ncov_p > 0){\n X_p <- cbind(X_p, X_p_cov)\n } \n \n X_p <- as.matrix(X_p)\n \n p_intercepts <- ifelse(usingYearDetProb, Y, 1)\n \n }\n \n # data for GOF\n \n {\n \n k_s_all <- data %>% dplyr::arrange(Site, Year)\n \n trueYearStatistics <- k_s_all %>% dplyr::group_by(Year) %>% \n dplyr::summarise(Detections = sum(Occ)) %>% dplyr::arrange(Year)\n \n if(usingSpatial){\n \n k_s_all$SitePatch <- findClosestPoint(cbind(k_s_all$X_sp,k_s_all$Y_sp), X_tilde)\n \n trueSpaceStatistics <- k_s_all %>% dplyr::group_by(SitePatch) %>% \n dplyr::summarise(Detections = sum(Occ)) %>% dplyr::arrange(SitePatch)\n \n k_s_all <- k_s_all %>% dplyr::select(SitePatch, Year, ) %>% dplyr::mutate(Present = 0)\n \n } else {\n \n k_s_all <- k_s_all %>% dplyr::select(Year) %>% dplyr::mutate(Present = 0)\n \n trueSpaceStatistics <- NULL\n }\n \n }\n }\n \n # ASSIGN THE PRIOR\n {\n print(\"Setting up the priors\")\n \n # fixed parameters\n {\n phi_psi <- 2\n phi_p <- 2\n \n a_l_T <- 1\n b_l_T <- 1\n \n a_sigma_T <- 2\n b_sigma_T <- .25\n \n a_l_s <- 1\n b_l_s <- 10\n \n a_sigma_s <- 2\n b_sigma_s <- 1\n \n a_sigma_eps <- 2\n b_sigma_eps <- .25\n \n sd_l_T <- .2 \n sd_sigma_T <- .2 \n }\n \n sigma_s <- b_sigma_s / (a_sigma_s - 1)\n sigma_T <- b_sigma_T / (a_sigma_T - 1)\n \n l_T <- a_l_T / b_l_T\n l_s <- a_l_s / b_l_s\n \n mu_psi <- invLogit(prior_psi)\n mu_p <- invLogit(prior_p)\n \n # priors on psi\n \n {\n \n b_psi <- c(rep(mu_psi,Y), rep(0, ncol(X_psi) - Y))\n B_psi <- matrix(0, nrow = ncol(X_psi), ncol = ncol(X_psi))\n \n C <- matrix(0, nrow = Y + X_centers, ncol = Y + X_centers)\n C[1:Y, 1:Y] <- K(1:Y,1:Y, sigma_T^2, l_T) + sigma_psi^2\n if(usingSpatial){\n C[Y + 1:X_centers, Y + 1:X_centers] <- K2(X_tilde,X_tilde, sigma_s^2, l_s) \n }\n \n B_psi[1:(Y + X_centers), 1:(Y + X_centers)] <- C\n \n B_psi[Y + X_centers + seq_len(numTimeSpaceCov), \n Y + X_centers + seq_len(numTimeSpaceCov)] <- diag(phi_psi^2, nrow = numTimeSpaceCov)\n \n if(ncov_psi > 0){\n \n C_covs <- diag(phi_psi^2, nrow = ncov_psi)\n \n B_psi[(Y + X_centers) + numTimeSpaceCov + 1:ncov_psi,\n (Y + X_centers) + numTimeSpaceCov + 1:ncov_psi] <- C_covs\n \n } \n \n inv_B_psi <- solve(B_psi)\n }\n \n # prior on p\n \n {\n b_p <- c(rep(mu_p, p_intercepts), rep(0, ncol(X_p) - p_intercepts))\n B_p <- matrix(0, nrow = ncol(X_p), ncol = ncol(X_p))\n diag(B_p)[1:p_intercepts] <- sigma_p^2\n \n if(ncov_p > 0){\n \n C <- diag(phi_p^2, nrow = ncov_p)\n \n B_p[p_intercepts + 1:ncov_p, p_intercepts + 1:ncov_p] <- C\n \n } \n \n inv_B_p <- solve(B_p)\n \n }\n }\n \n # run MCMC\n {\n # initialize output\n {\n beta_psi_output <- array(NA, dim = c(nchain , niter, ncol(X_psi)),\n dimnames = list(c(), c(), colnames(X_psi)))\n \n beta_p_output <- array(NA, dim = c(nchain , niter, ncol(X_p)),\n dimnames = list(c(), c(), colnames(X_p)))\n \n l_T_output <- matrix(NA, nrow = nchain, ncol = niter)\n l_s_output <- matrix(NA, nrow = nchain, ncol = niter)\n sigma_T_output <- array(NA, dim = c(nchain, niter))\n sigma_s_output <- array(NA, dim = c(nchain, niter))\n sigma_eps_output <- array(NA, dim = c(nchain, niter))\n \n psi_mean_output <- array(NA, dim = c(nchain, niter, Y))\n indexUniqueSite <- which(!duplicated(k_s$Site))\n namesUniqueSite <- k_s$Site[indexUniqueSite]\n \n gofYear_output <- array(NA, dim = c(nchain, niter, Y))\n if(usingSpatial){\n gofSpace_output <- array(NA, dim = c(nchain, niter, nrow(X_tilde))) \n } else {\n gofSpace_output <- NULL\n }\n \n if(storeRE){\n eps_unique_output <- array(NA, dim = c(nchain, niter, S),\n dimnames = list(c(), c(), namesUniqueSite))\n } else {\n eps_unique_output <- matrix(0, nchain , S)\n colnames(eps_unique_output) <- namesUniqueSite\n }\n \n }\n \n for (chain in 1:nchain) {\n \n # initialize parameters\n {\n \n print(\"Initializing the parameters\")\n \n beta_psi <- b_psi\n psi <- as.vector(logit(X_psi %*% beta_psi))\n \n Xbetapsi <- X_psi %*% beta_psi\n \n beta_p <- b_p\n p <- as.vector(logit(X_p %*% beta_p))\n \n Xbetap <- X_p %*% beta_p\n \n eps_s <- rep(0, nrow(k_s))\n \n z <- rep(NA, nrow(k_s))\n for (i in 1:nrow(k_s)) {\n if(k_s[i,1] == 1){\n z[i] <- 1\n } else {\n z[i] <- stats::rbinom(1, 1, psi[i])\n }\n }\n \n # presences across each sampling occasion\n z_all <- z[indexes_occobs]\n \n # hyperparameters\n {\n l_T <- a_l_T / b_l_T\n l_s <- a_l_s / b_l_s\n \n sigma_T <- b_sigma_T / (a_sigma_T - 1)\n sigma_s <- b_sigma_s / (a_sigma_s - 1)\n \n sigma_eps <- b_sigma_eps / (a_sigma_eps - 1)\n \n # precompute parameters to update l_s\n if(usingSpatial){\n \n length_grid_ls <- 20\n l_s_grid <- seq(0.01, 0.5, length.out = length_grid_ls)\n K_s_grid <- array(NA, dim = c(X_centers, X_centers, length_grid_ls))\n inv_K_s_grid <- array(NA, dim = c(X_centers, X_centers, length_grid_ls))\n diag_K_s_grid <- array(NA, dim = c(X_centers, length_grid_ls))\n inv_chol_K_s_grid <- array(NA, dim = c(X_centers, X_centers, length_grid_ls))\n \n for (j in 1:length_grid_ls) {\n l_s <- l_s_grid[j]\n K_s_grid[,,j] <- K_l <- K2(X_tilde, X_tilde, 1, l_s) + diag(exp(-10), nrow = nrow(X_tilde))\n diag_K_s_grid[,j] <- FastGP::rcppeigen_get_diag(K_s_grid[,,j])\n inv_K_s_grid[,,j] <- FastGP::rcppeigen_invert_matrix(K_s_grid[,,j])\n inv_chol_K_s_grid[,,j] <- FastGP::rcppeigen_invert_matrix(FastGP::rcppeigen_get_chol(K_s_grid[,,j]))\n } \n \n l_s <- l_s_grid[length_grid_ls / 2]\n \n } else {\n l_s_grid <- NULL\n K_s_grid <- NULL\n inv_K_s_grid <- NULL\n diag_K_s_grid <- NULL\n inv_chol_K_s_grid <- NULL\n }\n \n }\n \n }\n \n for (iter in seq_len(nburn + niter)) {\n \n if(verbose){\n if(iter <= nburn){\n print(paste0(\"Chain = \",chain,\" - Burn-in Iteration = \",iter)) \n } else {\n print(paste0(\"Chain = \",chain,\" - Iteration = \",iter - nburn))\n } \n }\n # print(paste0(\"l_s = \",l_s,\" / sigma_s = \",sigma_s,\n # \" / max(beta_psi) = \",max(abs(beta_psi[Y + 1:X_centers]))))\n \n # sample z ----\n \n z <- sample_z_cpp(psi, p, as.matrix(k_s[,3:4]))\n z_all <- z[indexes_occobs]\n \n # sample psi ----\n \n list_psi <- update_psi(beta_psi, X_psi, Xbetapsi,\n b_psi, inv_B_psi, \n z, k_s, sites, Y, X_centers, ncov_psi, \n X_y_index, X_s_index, numTimeSpaceCov,\n usingSpatial, eps_s, sigma_eps)\n psi <- list_psi$psi\n beta_psi <- list_psi$beta\n Omega <- list_psi$Omega\n eps_s <- list_psi$eps_s\n XbetaY <- list_psi$XbetaY\n Xbetas <- list_psi$Xbetas\n Xbeta_cov <- list_psi$Xbeta_cov\n Xbetapsi <- list_psi$Xbeta\n \n # sample hyperparameters ---------\n \n list_hyperparameters <- update_hyperparameters(l_T, a_l_T, b_l_T, sd_l_T, sd_sigma_T,\n sigma_T, a_sigma_T, b_sigma_T, Y,\n beta_psi, inv_B_psi, \n b_psi, sigma_psi,\n l_s_grid, K_s_grid, inv_K_s_grid, \n inv_chol_K_s_grid, diag_K_s_grid,\n a_l_s, b_l_s, \n sigma_s, a_sigma_s, b_sigma_s, X_tilde,\n a_sigma_eps, b_sigma_eps,\n usingSpatial, \n XbetaY, Xbetas, Xbeta_cov,\n eps_s, k_s, \n z, X_psi, Omega, X_y_index)\n l_T <- list_hyperparameters$l_T\n sigma_T <- list_hyperparameters$sigma_T\n sigma_s <- list_hyperparameters$sigma_s\n l_s <- list_hyperparameters$l_s\n index_l_s <- list_hyperparameters$index_l_s\n inv_B_psi <- list_hyperparameters$inv_B_psi\n sigma_eps <- list_hyperparameters$sigma_eps\n \n # sample p ----------------\n \n if(sum(z) > 0){\n list_p <- update_p(beta_p, Occs, z_all, X_p, b_p, inv_B_p, Xbetap, \n ncov_p, p_intercepts, X_y_index_p, usingYearDetProb)\n p <- list_p$p\n beta_p <- list_p$beta\n Xbetap <- list_p$Xbeta\n }\n \n # write parameters -------------------------------------------------------\n \n if(iter > nburn){\n \n beta_psi_output[chain,iter - nburn,] <- beta_psi\n \n eps_unique <- eps_s[indexUniqueSite]\n \n if(usingSpatial){\n a_s_unique <- beta_psi[Y + XY_centers_unique] + \n eps_unique\n psi_mean_output[chain,iter - nburn,] <- computeYearEffect(Y, a_s_unique, beta_psi) \n } else {\n psi_mean_output[chain,iter - nburn,] <- logit(beta_psi[1:Y]) + mean(eps_unique)\n }\n \n if(storeRE){\n eps_unique_output[chain, iter - nburn,] <- eps_s[indexUniqueSite]\n } else {\n eps_unique_output[chain,] <- eps_unique_output[chain,] + \n (1 / niter) * eps_s[indexUniqueSite] \n }\n \n sigma_eps_output[chain, iter - nburn] <- sigma_eps\n \n l_T_output[chain, iter - nburn] <- l_T\n sigma_T_output[chain, iter - nburn] <- sigma_T\n \n l_s_output[chain, iter - nburn] <- l_s\n sigma_s_output[chain, iter - nburn] <- sigma_s\n \n beta_p_output[chain,iter - nburn,] <- beta_p\n \n # GOF\n if (computeGOF) {\n k_s_all$Present <- simulateDetections(p, z_all)\n \n detectionsByYear <- k_s_all %>% dplyr::group_by(Year) %>% \n dplyr::summarise(Detections = sum(Present)) \n \n gofYear_output[chain,iter - nburn,] <- detectionsByYear$Detections\n \n if(usingSpatial){\n \n detectionsByPatch <- k_s_all %>% dplyr::group_by(SitePatch) %>% \n dplyr::summarise(Detections = sum(Present)) \n \n gofSpace_output[chain,iter - nburn,] <- detectionsByPatch$Detections\n \n }\n \n }\n \n }\n \n }\n \n }\n \n }\n \n # store summaries of the dataset\n {\n \n dataCharacteristics <- list(\"Years\" = years,\n \"X_tilde\" = X_tilde,\n \"originalsites\" = originalsites,\n \"gridStep\" = gridStep,\n \"XY_sp_unique\" = XY_sp_unique,\n \"usingYearDetProb\" = usingYearDetProb,\n \"usingSpatial\" = usingSpatial,\n \"numTimeSpaceCov\" = numTimeSpaceCov,\n \"X_psi_yearcov_values\" = X_psi_yearcov_values,\n \"nameVariables_psi\" = nameVariables_psi,\n \"nameVariables_p\" = nameVariables_p) \n }\n \n # create model output\n {\n GOF_output <- list(\n \"trueYearStatistics\" = trueYearStatistics,\n \"trueSpaceStatistics\" = trueSpaceStatistics,\n \"gofYear_output\" = gofYear_output,\n \"gofSpace_output\" = gofSpace_output\n )\n \n modelOutput <- list(\n \"beta_psi_output\" = beta_psi_output,\n \"eps_unique_output\" = eps_unique_output,\n \"beta_p_output\" = beta_p_output,\n \"sigma_T_output\" = sigma_T_output,\n \"l_T_output\" = l_T_output,\n \"sigma_s_output\" = sigma_s_output,\n \"l_s_output\" = l_s_output,\n \"sigma_eps_output\" = sigma_eps_output,\n \"psi_mean_output\" = psi_mean_output,\n \"GOF_output\" = GOF_output\n )\n }\n \n list(\"dataCharacteristics\" = dataCharacteristics,\n \"modelOutput\" = modelOutput)\n}", "meta": {"hexsha": "9908857b898128668b9b3c9a5d5d079e305346d1", "size": 25205, "ext": "r", "lang": "R", "max_stars_repo_path": "R/runmodel.r", "max_stars_repo_name": "alexdiana1992/FastOccupancy", "max_stars_repo_head_hexsha": "49855f99dcd8b256ee3167374d3753c12e0d21a2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/runmodel.r", "max_issues_repo_name": "alexdiana1992/FastOccupancy", "max_issues_repo_head_hexsha": "49855f99dcd8b256ee3167374d3753c12e0d21a2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/runmodel.r", "max_forks_repo_name": "alexdiana1992/FastOccupancy", "max_forks_repo_head_hexsha": "49855f99dcd8b256ee3167374d3753c12e0d21a2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 35.0069444444, "max_line_length": 210, "alphanum_fraction": 0.5296171395, "num_tokens": 6678, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.785308580887758, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.3987890144950688}} {"text": "###############################################################################\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n###############################################################################\n# Examples for the R/Finance Presentation\n# Copyright (C) 2012 Michael Kapler\n#\n# For more information please visit my blog at www.SystematicInvestor.wordpress.com\n# or drop me a line at TheSystematicInvestor at gmail\n###############################################################################\n\n\n\n\n\n\n\n\n\n#############################################################################\n# Seasonality Analysis - TIME patterns\n# R/Finance 2012\n###############################################################################\nseasonality.test <- function() \n{\n\t#*****************************************************************\n\t# Load historical data\n\t#****************************************************************** \n\tload.packages('quantmod')\n\tticker = 'WMT'\n\t\n\tdata = getSymbols(ticker, src = 'yahoo', from = '1970-01-01', auto.assign = F)\n\t\tdata = adjustOHLC(data, use.Adjusted=T)\n\t\t\n\tdata = data['1980::2012:04:07']\n\t\t\n\t#*****************************************************************\n\t# Look at the Month of the Year Seasonality\n\t#****************************************************************** \npng(filename = 'plot.month.year.seasonality.png', width = 600, height = 500, units = 'px', pointsize = 12, bg = 'white')\t\t\t\t\t\t\t\t\t\t\n\tmonth.year.seasonality(data, ticker)\ndev.off()\t\n\n\t#*****************************************************************\n\t# Look at What seasonally happens in the first 20 days of May\n\t#****************************************************************** \n\t# Find first day of May: it is one day after the last day of April\n\tmonth.ends = endpoints(data, 'months')\t\n\t\tmonth.ends = month.ends[month.ends > 0 & month.ends < nrow(data)]\n\t\tindex = which(format(index(data), '%b')[month.ends] == 'Apr')\n\t\npng(filename = 'plot.time.seasonality.png', width = 600, height = 500, units = 'px', pointsize = 12, bg = 'white')\n\tlayout(1)\n\ttime.seasonality(data, 1 + month.ends[index], 20, ticker)\ndev.off()\t\n}\n\n\n\n\n\n#############################################################################\n# Pattern Matching - PRICE patterns\n# R/Finance 2012\n###############################################################################\npattern.test <- function() \n{\n\t#*****************************************************************\n\t# Load historical data\n\t#****************************************************************** \n\tload.packages('quantmod')\n\tticker = 'SPY'\n\t\n\tdata = getSymbols(ticker, src = 'yahoo', from = '1970-01-01', auto.assign = F)\n\t\tdata = adjustOHLC(data, use.Adjusted=T)\n\t\n\tdata = data['::2012:04:07']\n\t#*****************************************************************\n\t# Find historical Matches similar to the last 90 days of price history\n\t#****************************************************************** \npng(filename = 'plot1.time.series.pattern.matching.png', width = 600, height = 500, units = 'px', pointsize = 12, bg = 'white')\t\t\t\n\tmatches = bt.matching.find(Cl(data), main = ticker,\tn.query=90, plot=TRUE)\t\ndev.off()\t\t\n\t\t\npng(filename = 'plot2.time.series.pattern.matching.png', width = 600, height = 500, units = 'px', pointsize = 12, bg = 'white')\t\t\n\tout = bt.matching.overlay(matches, plot=TRUE)\t\ndev.off()\t\t\n\n\t#*****************************************************************\n\t# Find Classical Techical Patterns, based on\n\t# Pattern Matching. Based on Foundations of Technical Analysis\n\t# by A.W. LO, H. MAMAYSKY, J. WANG\t\n\t#****************************************************************** \npng(filename = 'plot.pattern.matching.png', width = 600, height = 500, units = 'px', pointsize = 12, bg = 'white')\t\t\n\tplot.patterns(data, 190, ticker)\ndev.off()\t\t\n}\n\t\n\n\n\n\n\n\n\n\n\n\n#############################################################################\n# Month of the Year Seasonality\n#' @export \n#############################################################################\nmonth.year.seasonality <- function\n(\n\tdata,\t# xts time series data\n\tticker,\n\tlookback.len = 20*252\t# last 20 years of data\n) \n{\n\tdata = last(data, lookback.len)\n\t\tnperiods = nrow(data)\n\t\n\t#*****************************************************************\n\t# Compute monthly returns\n\t#****************************************************************** \n\t# find month ends\n\tmonth.ends = endpoints(data, 'months')\n\t\tmonth.ends = month.ends[month.ends > 0]\n\n\tprices = Cl(data)[month.ends]\n\tret = prices / mlag(prices) - 1\n\t\tret = ret[-1]\n\n\tret.by.month = create.monthly.table(ret)\t\n\t\n\t#*****************************************************************\n\t# Plot\n\t#****************************************************************** \n\tdata_list = lapply(apply(ret.by.month, 2, list), '[[', 1)\n\tgroup.seasonality(data_list, paste(ticker, 'Monthly', join(format(range(index(data)), '%d-%b-%Y'), ' to\\n')))\n\n} \n\n#' @export \ngroup.seasonality <- function\n(\n\tdata_list,\t# data list for each group\n\tsmain,\n\t...\t\t\n) \n{\n\t#*****************************************************************\n\t# Compute group stats\n\t#****************************************************************** \n\tout = compute.stats( data_list,\n\t\tlist(Sharpe=function(x) mean(x,na.rm=T)/sd(x,na.rm=T),\n\t\t\t'% Positive'=function(x) sum(x > 0,na.rm=T)/sum(!is.na(x)),\n\t\t\tMin=function(x) min(x,na.rm=T),\n\t\t\tMax=function(x) max(x,na.rm=T),\n\t\t\tAvg=function(x) mean(x,na.rm=T),\n\t\t\tMed=function(x) median(x,na.rm=T),\n\t\t\tStDev=function(x) sd(x,na.rm=T)\n\t\t\t)\n\t\t)\n\t\n\t#*****************************************************************\n\t# Plot\n\t#****************************************************************** \n\tlayout(mat=matrix(1:4, 2, 2, byrow=FALSE)) \t\n\tpar(mar=c(4, 3, 2, 2))\n\tcol = spl('lightgray,red')\n\t\t\n\tstats.names = spl('Sharpe,% Positive,Min,Avg')\n\tfor(i in stats.names) {\n\t\tbarplot(100*out[i,], names.arg = colnames(out), \n\t\t\tcol=iif(out[i,] > 0, col[1], col[2]), \n\t\t\tmain=iif(i == stats.names[1], paste(smain,' ', i, sep=''), i), \n\t\t\tborder = 'darkgray',las=2, ...)\n\t\tgrid(NA,NULL)\n\t\tabline(h=0, col='black')\t\t\n\t}\t\t\t\t\n}\t\n\n\n\n\n\n\n#############################################################################\n# Time seasonally for given periods\n#' @export \n###############################################################################\ntime.seasonality <- function\n(\n\tdata,\t\t\t# xts time series data\n\tperiod.starts,\t# locations\n\tperiod.len,\t\t# number of trading days to examine\n\tticker\n) \n{\n\tnperiods = len(period.starts)\n\tdates = index(data)\n\t\tndates = len(dates)\n\n\t#*****************************************************************\n\t# Compute returns, construct trading.days matrix\n\t#****************************************************************** \n\tprices = Cl(data)\n\tret = prices / mlag(prices) - 1\t\t\n\t\tret = c( as.double(ret), rep(NA, period.len))\n\n\t# 1:period.len by period.starts matrix\n\ttrading.days = sapply(period.starts, function(i) ret[i : (i + period.len - 1)])\n\t\t\n\t#*****************************************************************\n\t# Compute stats\n\t#****************************************************************** \t\n\t# exclude periods that have insufficient data\n\tperiods.index = 1:nperiods\n\t\ttemp = count(trading.days)\n\tperiods.index = periods.index[temp > 0.9 * median(temp)]\n\t\n\t\n\t# last period\n\tlast.period = trading.days[, nperiods]\n\t\tlast.period = 100 * ( cumprod(1 + last.period) - 1 )\n\n\t# average period\n\tavg.period = apply(trading.days[, periods.index], 1, mean, na.rm=T)\n\t\tavg.period = 100 * ( cumprod(1 + avg.period) - 1 )\n\t\t\n\t# ranges\t\t\t\t\n\ttemp = 100*(apply(1 + trading.days[, periods.index], 2, cumprod) - 1)\t\n\tquantiles = apply(temp, 1, quantile, probs = c(75, 25)/100, na.rm=T)\t\t\n\t\n\t#*****************************************************************\n\t# Create Plot\n\t#****************************************************************** \t\t\n\tcols = spl('blue,red,gray')\n\t\t\n\tpar(mar=c(4,4,2,1))\n\tplot(avg.period, type='n', xaxt = 'n', xlim=c(1,period.len),\n\t\tylim=range(avg.period, last.period, quantiles, na.rm=T),\n\t\tmain = ticker, xlab = 'Trading Days', ylab = 'Avg % Profit/Loss')\n\t\t\t\t\n\tgrid()\n\taxis(1, 1:period.len)\t\t\n\t\t\n\tlines(quantiles[1,], type='l', lwd=2, col=cols[3])\n\tlines(quantiles[2,], type='l', lwd=2, col=cols[3])\n\t\t\n\tlines(last.period, type='b', lwd=2, col=cols[2], bg=cols[2], pch=24)\n\tlines(avg.period, type='b', lwd=2, col=cols[1], bg=cols[1], pch=22)\n\t\t\n\tfirst.year = format(dates[period.starts][periods.index[1]], '%Y')\n\tlast.year = format(dates[period.starts][last(periods.index)], '%Y')\n\tlast.period.start.date = format(dates[period.starts[nperiods]], '%d %b %Y')\n\tlast.period.end.date = format(dates[ndates], '%d %b %Y')\n\t\t\t\n\tif( (period.starts[nperiods] + period.len - 1) < ndates ) {\n\t\tlast.period.end.date = format(dates[period.starts[nperiods] + period.len - 1], '%d %b %Y')\n\t}\n\t\t\n\tplota.legend(c(paste('Avgerage for', first.year, '-', last.year),\n\t\t\tpaste(last.period.start.date, '-', last.period.end.date),\n\t\t\t'Top 25% / Bot 25%'), cols)\t\n}\n\n\n\n\n#############################################################################\n# Find and Plot Classical Techical Patterns\n#' @export \n#############################################################################\nplot.patterns <- function\n(\n\tdata,\t# xts time series data\n\tn,\t\t# lookback period to search for the patterns\n\tticker,\t\n\tpatterns = pattern.db()\t# database with patterns\n) \n{\n\t#*****************************************************************\n\t# Find Extrema\n\t#****************************************************************** \n\tload.packages('sm') \n\t\n\tsample = last(data, n)\t\n\t\n\tobj = find.extrema( Cl(sample) )\t\n\t\tmhat = obj$mhat\n\t\tmhat.extrema.loc = obj$mhat.extrema.loc\n\t\tdata.extrema.loc = obj$data.extrema.loc\n\t\tn.index = len(data.extrema.loc)\n\n\t#*****************************************************************\n\t# Plot\t\n\t#****************************************************************** \n\t\tplota.control$col.border = 'gray'\n\tplota(sample, type='hl',col='gray')\t\n\t\tplota.lines(mhat, col='magenta', lwd=2)\t\t\t\n\t\tplota.lines(sample, col='blue')\t\t\t\t\n\t\t\n\tif(n.index > 0) {\n\t\tplota.lines(sample[data.extrema.loc], type='p', col='blue', lwd=3, pch=19)\t\t\n\t\tout = find.patterns(obj, patterns = patterns, silent=F, plot=T) \n\t}\n\t\t\t\n\tplota.legend(c(paste(ticker, join(format(range(index(sample)), '%d%b%Y'), ' - ')),\n\t\t\t\t'Close,Kernel,Pattern(s)'), \n\t\t\t\t'gray,blue,magenta,orange')\t\t\t\t\n\t\t\t\t\n}\n\n\n#############################################################################\n# Find maxima and minima using Kernel estimate\n#' @export \n#############################################################################\nfind.extrema <- function(\n\tx\t# time series\n) \n{\n\tif(is.xts(x)) {\n\t\ty = as.vector( Cl(x) )\n\t} else {\n\t\ty = x\n\t}\t\t\n\tn = len(y)\n\tt = 1:n\n\t\n\t# Fit kernel\n\t# stat.epfl.ch/files/content/sites/stat/files/users/MdC/notes_3.pdf\n\th = h.select(t, y, method = 'cv')\n\t\ttemp = sm.regression(t, y, h=h, display = 'none')\n\tmhat = approx(temp$eval.points, temp$estimate, t, method='linear')$y\n\n\t# page 15\n\t# find locations of local maxima and minima in mhat\n\ttemp = diff(sign(diff(mhat)))\n\tloc = which( temp != 0 ) + 1\n\t\tloc.dir = -sign(temp[(loc - 1)])\n\t\n\t# check\n\t# temp = cbind(mhat[(loc - 1)],mhat[(loc)],mhat[(loc + 1)])\n\t# cbind(round(temp,2), loc.dir, apply(temp, 1, which.max), apply(temp, 1, which.min))\n\t\n\t\t\n\t# page 16\n\t# find locations of local maxima and minima in original data with in +1/-1 local maxima and minima in mhat\n\ttemp = c( y[1], y, y[n] )\n\ttemp = cbind(temp[loc], temp[(loc + 1)], temp[(loc + 2)])\n\t\tmax.index = loc + apply(temp, 1, which.max) - 2\n\t\tmin.index = loc + apply(temp, 1, which.min) - 2\n\tdata.loc = iif(loc.dir > 0, max.index, min.index)\n\tdata.loc = iif(data.loc < 1, 1, iif(data.loc > n, n, data.loc))\n\n\tif(is.xts(x)) mhat = make.xts(mhat, index(x))\n\t\n\treturn(list(data = y, mhat = mhat, extrema.dir = loc.dir,\n\t\tmhat.extrema.loc = loc, data.extrema.loc = data.loc))\n}\n\n\n#############################################################################\n# Find Classical Techincal patterns\n#' @export \n#############################################################################\nfind.patterns <- function\n(\n\tobj, \t# extrema points\n\tpatterns = pattern.db(), \n\tsilent=T, \n\tplot=T\n) \n{\n\tdata = obj$data\n\tmhat = obj$mhat\n\textrema.dir = obj$extrema.dir\n\tdata.extrema.loc = obj$data.extrema.loc\n\tn.index = len(data.extrema.loc)\n\n\tif(is.xts(mhat)) {\n\t\tdates = index4xts(obj$mhat)\n\t} else {\n\t\tdates = 1:len(data)\n\t}\t\t\n\t\n\t# Semi-transparent orange color\n\tcol = col.add.alpha('orange', alpha=150)\n\t\n\t\t\n\tout = out.rownames = c()\n\t\n\t# search for patterns\n\tfor(i in 1:n.index) {\n\t\n\t\tfor(pattern in patterns) {\n\t\t\n\t\t\t# check same sign\n\t\t\tif( pattern$start * extrema.dir[i] > 0 ) {\n\t\t\t\n\t\t\t\t# check that there is suffcient number of extrema to complete pattern\n\t\t\t\tif( i + pattern$len - 1 <= n.index ) {\n\t\t\t\t\n\t\t\t\t\t# create enviroment to check pattern: E1,E2,...,En; t1,t2,...,tn\n\t\t\t\t\tenvir.data = c(data[data.extrema.loc][i:(i + pattern$len - 1)], \n\t\t\t\t\t\t\t\t\tdata.extrema.loc[i:(i + pattern$len - 1)])\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\tnames(envir.data) = c(paste('E', 1:pattern$len, sep=''), \n\t\t\t\t\t\t\t\t\t\t\t\tpaste('t', 1:pattern$len, sep=''))\n\t\t\t\t\tenvir.data = as.list(envir.data)\t\t\t\t\t\n\t\t\t\t\t\n\t\t\t\t\t# double top/bottom patterns require all extrema [we will exclude the first point(E1/t1)]\n\t\t\t\t\t#envir.data$E = data[data.extrema.loc][i:n.index]\n\t\t\t\t\tenvir.data$E = data[data.extrema.loc][-c(1:i)]\n\t\t\t\t\tenvir.data$t = data.extrema.loc[-c(1:i)]\n\t\t\t\t\t\n\t\t\t\t\t# check if pattern was found\n\t\t\t\t\tif( eval(pattern$formula, envir = envir.data) ) {\n\t\t\t\t\t\tif(!silent) cat('Found', pattern$name, 'at', i, '\\n')\n\t\t\t\t\t\t\n\t\t\t\t\t\tif(plot & !is.null(pattern$plot)) {\t\t\t\t\t\t\n\t\t\t\t\t\t\ttemp = dates[data.extrema.loc[i:(i + pattern$len - 1)]]\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\tnames(temp) = paste('d', 1:pattern$len, sep='')\n\t\t\t\t\t\t\tenvir.data = c( envir.data, temp )\n\t\t\t\t\t\t\tenvir.data$d = dates[data.extrema.loc[-c(1:i)]]\n\t\t\t\t\t\t\tenvir.data$col = col\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\teval(pattern$plot, envir = envir.data)\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\t\t\t\t\t\t# record \n\t\t\t\t\t\tout.rownames = c(out.rownames, pattern$name)\n\t\t\t\t\t\tout = rbind(out, c(data.extrema.loc[i], \n\t\t\t\t\t\t\t\t\t\t\tiif(is.null(pattern$last.point),\n\t\t\t\t\t\t\t\t\t\t\t\tdata.extrema.loc[(i + pattern$len - 1)], \n\t\t\t\t\t\t\t\t\t\t\t\teval(pattern$last.point, envir = envir.data)\n\t\t\t\t\t\t\t\t\t\t\t\t)))\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\t\t\n\t\t}\t\n\t}\n\t\n\tif(len(out)>0) {\n\t\tcolnames(out) = spl('start,end')\n\t\trownames(out) = out.rownames\n\t}\n\treturn(out)\n}\n\n\n#############################################################################\n# Find historical patterns in the data over a rolling window\n#' @export \n#############################################################################\nfind.all.patterns.window <- function() \n{\n\t#*****************************************************************\n\t# Load historical data\n\t#****************************************************************** \n\tload.packages('quantmod')\n\tticker = 'SPY'\n\t\n\tdata = getSymbols(ticker, src = 'yahoo', from = '1970-01-01', auto.assign = F)\n\t\tdata = adjustOHLC(data, use.Adjusted=T)\n\n\tdata = data['2010::']\n\t#*****************************************************************\n\t# Search for all patterns over a rolling window\n\t#****************************************************************** \n\tload.packages('sm') \n\thistory = as.vector(coredata(Cl(data)))\n\twindow.len = 90\n\tpatterns = pattern.db()\n\t\n\tfound.patterns = c()\n\t\n\tfor(t in window.len : (len(history)-1)) {\n\t\tsample = history[(t - window.len + 1):t]\t\t\n\t\tobj = find.extrema( sample )\t\n\t\t\n\t\tif(len(obj$data.extrema.loc) > 0) {\n\t\t\tout = find.patterns(obj, patterns = patterns, silent=F, plot=F) \n\t\t\t\n\t\t\tif(len(out)>0) found.patterns = rbind(found.patterns,cbind(t,out,t-window.len+out))\t\t\t\n\t\t}\n\t\tif( t %% 10 == 0) cat(t, 'out of', len(history), '\\n')\n\t}\n\tcolnames(found.patterns) = spl('t,start,end,tstart,tend')\n\t\n\t#*****************************************************************\n\t# Examine found patterns\n\t#****************************************************************** \t\n\t# check what patterns are not found\n\tsetdiff(unique(names(patterns)), unique(rownames(found.patterns)))\n\n\t# number of matches for each pattern\t\n\tfrequency = tapply(rep(1,nrow(found.patterns)), rownames(found.patterns), sum)\n\tbarplot(frequency)\n\t\n\t# determine starting Time for a pattern\n\tindex = which(rownames(found.patterns)=='HS')\n\tfound.patterns[ index[1:10],]\t\t\t\n\t\n\t# plot\n\tpattern.index = index[1]\n\tt = found.patterns[pattern.index, 't'];\t\n\tplot.patterns(data[1:t,], window.len, ticker, patterns)\t\n\n\t\t\n\t# plot start/end of this pattern\n\tsample = data[(t - window.len + 1):t]\t\t\n\t\tstart.pattern = found.patterns[pattern.index, 'start']\n\t\tend.pattern = found.patterns[pattern.index, 'end']\t\t\n\tabline(v = index(sample)[start.pattern]);\n\tabline(v = index(sample)[end.pattern]);\n\t\n\tindex(sample)[start.pattern]\t\n\tindex(data[(t - window.len + start.pattern),])\n\t\n}\n\n\n#############################################################################\n# Compute conditional returns for each pattern over a rolling window\n#############################################################################\nbt.patterns.test <- function() \n{\n\t#*****************************************************************\n\t# Load historical data\n\t#****************************************************************** \n\tload.packages('quantmod')\n\tticker = 'SPY'\n\t\n\tdata = getSymbols(ticker, src = 'yahoo', from = '1970-01-01', auto.assign = F)\n\t\tdata = adjustOHLC(data, use.Adjusted=T)\n\n\t#data = data['2010::']\n\n\t#*****************************************************************\n\t# Setup\n\t#****************************************************************** \n\t# page 14-15, L = 35 and d = 3, rolling the length of the window at L + d,\n\t# The parameter d controls for the fact that in practice we do not observe a\n\t# realization of a given pattern as soon as it has completed. Instead, we assume\n\t# that there may be a lag between the pattern completion and the time\n\t# of pattern detection. To account for this lag, we require that the final extremum\n\t# that completes a pattern occurs on day t + L - 1; hence d is the number\n\t# of days following the completion of a pattern that must pass before the pattern\n\t# is detected.\t\n\t#In particular, we compute postpattern returns starting from the end of trading\n\t#day t + L + d, that is, one day after the pattern has completed. For\n\t#example, if we determine that a head-and-shoulder pattern has completed\n\t# on day t + L - 1 (having used prices from time t through time t + L + d - 1),\n\t#we compute the conditional one-day gross return as Z1=Yt+L+d+1/Yt+L+d.\t\n\t\n\t#*****************************************************************\n\t# Search for all patterns over a rolling window\n\t#****************************************************************** \n\tload.packages('sm') \n\thistory = as.vector(coredata(Cl(data)))\n\t\n\twindow.L = 35\n\twindow.d = 3\n\twindow.len = window.L + window.d\n\n\tpatterns = pattern.db()\n\t\n\tfound.patterns = c()\n\t\n\tfor(t in window.len : (len(history)-1)) {\n\t\tret = history[(t+1)]/history[t]-1\n\t\t\n\t\tsample = history[(t - window.len + 1):t]\t\t\n\t\tobj = find.extrema( sample )\t\n\t\t\n\t\tif(len(obj$data.extrema.loc) > 0) {\n\t\t\tout = find.patterns(obj, patterns = patterns, silent=F, plot=F) \n\t\t\t\n\t\t\tif(len(out)>0) found.patterns = rbind(found.patterns,cbind(t,out,t-window.len+out, ret))\n\t\t}\n\t\tif( t %% 10 == 0) cat(t, 'out of', len(history), '\\n')\n\t}\n\tcolnames(found.patterns) = spl('t,start,end,tstart,tend,ret')\n\t\n\t#*****************************************************************\n\t# Clean found patterns\n\t#****************************************************************** \t\n\t# remove patterns that finished after window.L\n\tfound.patterns = found.patterns[found.patterns[,'end'] <= window.L,]\n\t\t\n\t# remove the patterns found multiple times, only keep first one\n\tpattern.names = unique(rownames(found.patterns))\n\tall.patterns = c()\n\tfor(name in pattern.names) {\n\t\tindex = which(rownames(found.patterns) == name)\n\t\ttemp = NA * found.patterns[index,]\n\t\t\n\t\ti.count = 0\n\t\ti.start = 1\n\t\twhile(i.start < len(index)) {\n\t\t\ti.count = i.count + 1\n\t\t\ttemp[i.count,] = found.patterns[index[i.start],]\n\t\t\tsubindex = which(found.patterns[index,'tstart'] > temp[i.count,'tend'])\t\t\t\n\t\t\t\t\t\t\n\t\t\tif(len(subindex) > 0) {\n\t\t\t\ti.start = subindex[1]\n\t\t\t} else break\t\t\n\t\t} \n\t\tall.patterns = rbind(all.patterns, temp[1:i.count,])\t\t\n\t}\n\t\n\t#*****************************************************************\n\t# Plot\n\t#****************************************************************** \t\npng(filename = 'plot1.png', width = 600, height = 500, units = 'px', pointsize = 12, bg = 'white')\t\n\t# number of matches for each pattern\t\n\tfrequency = tapply(rep(1,nrow(all.patterns)), rownames(all.patterns), sum)\n\tlayout(1)\n\tbarplot.with.labels(frequency/100, 'Frequency for each Pattern')\ndev.off()\n\t\n\n\t\npng(filename = 'plot2.png', width = 600, height = 500, units = 'px', pointsize = 12, bg = 'white')\t\n\t# pattern seasonality\n\tall.patterns[,'ret'] = history[(all.patterns[,'t']+20)] / history[all.patterns[,'t']] - 1\n\tdata_list = tapply(all.patterns[,'ret'], rownames(all.patterns), list)\n\tgroup.seasonality(data_list, '20 days after Pattern')\ndev.off()\t\n\n\npng(filename = 'plot3.png', width = 600, height = 500, units = 'px', pointsize = 12, bg = 'white')\t\n\t# time pattern seasonality\n\tlayout(1)\n\tname = 'BBOT'\n\tindex = which(rownames(all.patterns) == name)\t\n\ttime.seasonality(data, all.patterns[index,'t'], 20, name)\t\ndev.off()\n\n\n\n\n\n\t#t.test(out[,'ret'])$p.value\n\t#tapply(out[,'ret'], rownames(out), function(x) t.test(x)$p.value)\n\t\n}\n\n\n\n###############################################################################\n# Pattern Matching\n#\n# Based on Foundations of Technical Analysis: Computational Algorithms, Statistical Inference, and Empirical Implementation\n# by A.W. LO, H. MAMAYSKY, J. WANG\n###############################################################################\n# http://thepatternsite.com/\n#' @export \n###############################################################################\npattern.db <- function() \n{\n\t# page 12\n\tpatterns = list()\n\n\t#*****************************************************************\n\t# You can reference E1,E2,...,En and t1,t2,...,tn in pattern formula\n\t#****************************************************************** \t\n\t# Head-and-shoulders (HS)\n\t#****************************************************************** \t\n\tpattern = list()\n\tpattern$len = 5\n\tpattern$start = 'max'\n\tpattern$formula = expression(\n\t\t# E3 > E1, E3 > E5\n\t\tE3 > E1 &\n\t\tE3 > E5 &\n\t\t\n\t\t# E1 and E5 are within 1.5 percent of their average\n\t\tabs(E1 - (E1+E5)/2) < 1.5/100 * (E1+E5)/2 &\n\t\tabs(E5 - (E1+E5)/2) < 1.5/100 * (E1+E5)/2 &\n\t\t\n\t\t# E2 and E4 are within 1.5 percent of their average\n\t\tabs(E2 - (E2+E4)/2) < 1.5/100 * (E2+E4)/2 &\n\t\tabs(E4 - (E2+E4)/2) < 1.5/100 * (E2+E4)/2\n\t\t)\n\tpattern$plot = expression({\n\t\tlines(c(d1,d2,d3,d4,d5), c(E1,E2,E3,E4,E5), lwd=10, col=col)\n\t\t\ttext(d3, E3, 'HS', adj=c(0.5,-0.5), xpd=TRUE)\t\t\n\t\t})\t\t\t\t\t\t\t\t\n\tpatterns$HS = pattern\t\t\n\n\t#*****************************************************************\n\t# Inverted Head-and-shoulders (IHS)\n\t#****************************************************************** \t\n\tpattern = list()\n\tpattern$len = 5\n\tpattern$start = 'min'\n\tpattern$formula = expression(\n\t\t# E3 < E1, E3 < E5\n\t\tE3 < E1 &\n\t\tE3 < E5 &\n\t\t\n\t\t# E1 and E5 are within 1.5 percent of their average\n\t\tabs(E1 - (E1+E5)/2) < 1.5/100 * (E1+E5)/2 &\n\t\tabs(E5 - (E1+E5)/2) < 1.5/100 * (E1+E5)/2 &\n\t\t\n\t\t# E2 and E4 are within 1.5 percent of their average\n\t\tabs(E2 - (E2+E4)/2) < 1.5/100 * (E2+E4)/2 &\n\t\tabs(E4 - (E2+E4)/2) < 1.5/100 * (E2+E4)/2\n\t\t)\n\tpattern$plot = expression({\n\t\tlines(c(d1,d2,d3,d4,d5), c(E1,E2,E3,E4,E5), lwd=10, col=col)\n\t\t\ttext(d3, E3, 'IHS', adj=c(0.5,1), xpd=TRUE)\t\t\n\t\t})\t\t\t\t\t\t\n\tpatterns$IHS = pattern\t\t\n\t\n\t#*****************************************************************\n\t# Broadening tops (BTOP)\n\t#****************************************************************** \t\t\n\tpattern = list()\n\tpattern$len = 5\n\tpattern$start = 'max'\n\tpattern$formula = expression(\n\t\t# E1 < E3 < E5\n\t\tE1 < E3 &\n\t\tE3 < E5 &\t\t\n\t\tE2 > E4\n\t\t)\n\tpattern$plot = expression({\n\t\tbeta = ols(cbind(1,c(t1,t3,t5)),c(E1,E3,E5))$coefficients\n\t\tlines(c(d1,d3,d5), beta[1] + beta[2]*c(t1,t3,t5), lwd=10, col=col)\t\n\t\tlines(c(d2,d4), c(E2,E4), lwd=10, col=col)\n\t\t\ttext(d3, min(E2,E4), 'BTOP', adj=c(0.5,1), xpd=TRUE)\n\t\t})\t\t\t\t\n\tpatterns$BTOP = pattern\t\t\n\t\t\n\t#*****************************************************************\n\t# Broadening bottoms (BBOT)\n\t#****************************************************************** \t\t\n\tpattern = list()\n\tpattern$len = 5\n\tpattern$start = 'min'\n\tpattern$formula = expression(\n\t\t# E1 > E3 > E5\n\t\tE1 > E3 &\n\t\tE3 > E5 &\t\t\n\t\tE2 < E4\n\t\t)\t\t\n\tpattern$plot = expression({\n\t\tbeta = ols(cbind(1,c(t1,t3,t5)),c(E1,E3,E5))$coefficients\n\t\tlines(c(d1,d3,d5), beta[1] + beta[2]*c(t1,t3,t5), lwd=10, col=col)\t\n\t\tlines(c(d2,d4), c(E2,E4), lwd=10, col=col)\n\t\t\ttext(d3, max(E2,E4), 'BBOT', adj=c(0.5,0), xpd=TRUE)\n\t\t})\t\t\n\tpatterns$BBOT = pattern\t\t\n\n\t#*****************************************************************\n\t# Triangle tops (TTOP)\n\t#****************************************************************** \t\t\n\tpattern = list()\n\tpattern$len = 5\n\tpattern$start = 'max'\n\tpattern$formula = expression(\n\t\t# E1 > E3 > E5\n\t\tE1 > E3 &\n\t\tE3 > E5 &\t\t\n\t\tE2 < E4\n\t\t)\n\tpattern$plot = expression({\n\t\tbeta = ols(cbind(1,c(t1,t3,t5)),c(E1,E3,E5))$coefficients\n\t\tlines(c(d1,d3,d5), beta[1] + beta[2]*c(t1,t3,t5), lwd=10, col=col)\n\t\tlines(c(d2,d4), c(E2,E4), lwd=10, col=col)\n\t\t\ttext(d3, min(E2,E4), 'TTOP', adj=c(0.5,1), xpd=TRUE)\n\t\t})\t\t\t\t\t\t\n\tpatterns$TTOP = pattern\t\t\n\t\n\t#*****************************************************************\n\t# Triangle bottoms (TBOT)\n\t#****************************************************************** \t\t\n\tpattern = list()\n\tpattern$len = 5\n\tpattern$start = 'min'\n\tpattern$formula = expression(\n\t\t# E1 < E3 < E5\n\t\tE1 < E3 &\n\t\tE3 < E5 &\t\t\n\t\tE2 > E4\n\t\t)\n\tpattern$plot = expression({\n\t\tbeta = ols(cbind(1,c(t1,t3,t5)),c(E1,E3,E5))$coefficients\t\t\n\t\tlines(c(d1,d3,d5), beta[1] + beta[2]*c(t1,t3,t5), lwd=10, col=col)\n\t\tlines(c(d2,d4), c(E2,E4), lwd=10, col=col)\n\t\t\ttext(d3, max(E2,E4), 'TBOT', adj=c(0.5,0), xpd=TRUE)\n\t\t})\t\t\t\t\n\tpatterns$TBOT = pattern\t\t\n\t\n\t#*****************************************************************\n\t# Rectangle tops (RTOP)\n\t#****************************************************************** \t\t\n\tpattern = list()\n\tpattern$len = 5\n\tpattern$start = 'max'\n\tpattern$formula = expression({\n\t\tavg.top = (E1+E3+E5)/3\n\t\tavg.bop = (E2+E4)/2\n\t\t\n\t\t# tops E1,E3,E5 are within 0.75 percent of their average\n\t\tabs(E1 - avg.top) < 0.75/100 * avg.top &\n\t\tabs(E3 - avg.top) < 0.75/100 * avg.top &\n\t\tabs(E5 - avg.top) < 0.75/100 * avg.top &\n\t\t\n\t\t# bottoms E2,E4 are within 0.75 percent of their average\n\t\tabs(E2 - avg.bop) < 0.75/100 * avg.bop &\n\t\tabs(E4 - avg.bop) < 0.75/100 * avg.bop &\n\t\t\t\t\n\t\t# lowest top > highest bottom\n\t\tmin(E1,E3,E5) > max(E2,E4)\n\t\t})\n\tpattern$plot = expression({\n\t\tavg.top = (E1+E3+E5)/3\n\t\tavg.bop = (E2+E4)/2\n\n\t\tlines(c(d1,d3,d5), rep(avg.top,3), lwd=10, col=col)\n\t\tlines(c(d2,d4), rep(avg.bop,2), lwd=10, col=col)\n\t\t\ttext(d3, min(E2,E4), 'RTOP', adj=c(0.5,-0.5), xpd=TRUE)\n\t\t})\t\t\t\t\t\t\n\tpatterns$RTOP = pattern\t\t\n\t\n\t#*****************************************************************\n\t# Rectangle bottoms (RBOT)\n\t#****************************************************************** \t\t\n\tpattern = list()\n\tpattern$len = 5\n\tpattern$start = 'min'\n\tpattern$formula = expression({\n\t\tavg.top = (E2+E4)/2\n\t\tavg.bop = (E1+E3+E5)/3\n\t\n\t\t# tops E2,E4 are within 0.75 percent of their average\n\t\tabs(E2 - avg.top) < 0.75/100 * avg.top &\n\t\tabs(E4 - avg.top) < 0.75/100 * avg.top &\n\t\t\n\t\t# bottoms E1,E3,E5 are within 0.75 percent of their average\t\t\n\t\tabs(E1 - avg.bop) < 0.75/100 * avg.bop &\n\t\tabs(E3 - avg.bop) < 0.75/100 * avg.bop &\n\t\tabs(E5 - avg.bop) < 0.75/100 * avg.bop &\n\t\t\t\t\n\t\t# lowest top > highest bottom\n\t\tmin(E2,E4) > max(E1,E3,E5)\n\t\t})\n\tpattern$plot = expression({\n\t\tavg.top = (E2+E4)/2\n\t\tavg.bop = (E1+E3+E5)/3\n\t\n\t\tlines(c(d1,d3,d5), rep(avg.bop,3), lwd=10, col=col)\n\t\tlines(c(d2,d4), rep(avg.top,2), lwd=10, col=col)\n\t\t\ttext(d3, max(E2,E4), 'RBOT', adj=c(0.5,0), xpd=TRUE)\n\t\t})\t\t\t\t\t\t\n\tpatterns$RBOT = pattern\t\t\n\t\t\n\t#*****************************************************************\n\t# Analyzing Chart Patterns: Double Top And Double Bottom\n\t# http://www.investopedia.com/university/charts/charts4.asp\n\t#*****************************************************************\n\t# Double tops (DTOP), note in E and t first one is excluded\n\t#****************************************************************** \t\t\n\tpattern = list()\n\tpattern$len = 3\n\tpattern$start = 'max'\n\tpattern$formula = expression({\n\t\t# Ea = max(E), ta = t[which.max(E)]\n\t\tsecond.top = max(E)\n\t\tsecond.top.t = t[which.max(E)]\n\t\tavg = (E1 + second.top)/2\n\n\t\t# E1 and Ea are within 1.5 percent of their average\n\t\tabs(E1 - avg) < 1.5/100 * avg &\n\t\tabs(second.top - avg) < 1.5/100 * avg &\n\t\t\n\t\t# ta - t1 > 22\n\t\tsecond.top.t - t1 > 22\n\t\t})\n\tpattern$plot = expression({\n\t\tsecond.top = max(E)\n\t\tsecond.top.d = d[which.max(E)]\n\t\tavg = (E1 + second.top)/2\n\t\t\n\t\tpoints(c(d1, second.top.d), c(E1, second.top), pch=2, lwd=2) \n\t\tlines(c(d1, second.top.d), rep(avg, 2), lwd=10, col=col)\n\t\t\ttext(d2, avg, 'DTOP', adj=c(0.5,-0.5), xpd=TRUE)\n\t\t})\n\tpattern$last.point = expression(t[which.max(E)])\n\tpatterns$DTOP = pattern\t\t\n\n\t#*****************************************************************\n\t# Double bottoms (DBOT)\n\t#****************************************************************** \t\t\n\tpattern = list()\n\tpattern$len = 3\n\tpattern$start = 'min'\n\tpattern$formula = expression(\n\t\t# E1 and Ea = min(E) are within 1.5 percent of their average\n\t\tabs(E1 - (E1+min(E))/2) < 1.5/100 * (E1+min(E))/2 &\n\t\tabs(max(E[-1]) - (E1+min(E))/2) < 1.5/100 * (E1+min(E))/2 &\n\t\t\n\t\t# ta - t1 > 22, ta = t[which.min(E)]\n\t\tt[which.min(E)] - t1 > 22\n\t\t)\n\tpattern$plot = expression({\n\t\tsecond.bot = min(E)\n\t\tsecond.bot.d = d[which.min(E)]\n\t\tavg = (E1 + second.bot)/2\n\t\t\n\t\tpoints(c(d1, second.bot.d), c(E1, second.bot), pch=2, lwd=2) \n\t\tlines(c(d1, second.bot.d), rep(avg, 2), lwd=10, col=col)\n\t\t\ttext(d2, avg, 'DBOT', adj=c(0.5,1), xpd=TRUE)\n\t\t})\t\n\tpattern$last.point = expression(t[which.min(E)])\n\tpatterns$DBOT = pattern\t\t\n\t\n\t\n\t# add name and convert start to +1/-1\n\tfor(i in 1:len(patterns)) {\n\t\tpatterns[[i]]$name = names(patterns)[i]\n\t\tpatterns[[i]]$start = iif(patterns[[i]]$start == 'max', 1, -1)\t\n\t}\n\n\treturn(patterns)\t\n}\n\n\n\n\n", "meta": {"hexsha": "4c09bc820de191d8b5639a36df2f218c7af3697a", "size": 30972, "ext": "r", "lang": "R", "max_stars_repo_path": "patterns.matching/SIT/rfinance2012.r", "max_stars_repo_name": "wisonhang/Shiny_report", "max_stars_repo_head_hexsha": "bed828a4c3d88f37ba1cd16f31354541693f64fc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "patterns.matching/SIT/rfinance2012.r", "max_issues_repo_name": "wisonhang/Shiny_report", "max_issues_repo_head_hexsha": "bed828a4c3d88f37ba1cd16f31354541693f64fc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "patterns.matching/SIT/rfinance2012.r", "max_forks_repo_name": "wisonhang/Shiny_report", "max_forks_repo_head_hexsha": "bed828a4c3d88f37ba1cd16f31354541693f64fc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.7053854277, "max_line_length": 130, "alphanum_fraction": 0.4949954798, "num_tokens": 8752, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5813031051514762, "lm_q2_score": 0.6859494614282923, "lm_q1q2_score": 0.39874455190524905}} {"text": "REBOL [\n Title: \"Functions for converting and exchanging decimal values\"\n File: %decimal.r\n Author: \"Eric Long\"\n Email: kgd03011@nifty.ne.jp\n Co-Authors: [\"Larry Palmiter\" \"Gerald Goertzel\" \"Oldes\"]\n Date: 7-Jan-2012\n Category: [math util 4]\n Version: 1.0.1\n History: [\n 1.0.0 15-Feb-2000 \"Original Eric's version\"\n 1.0.1 7-Jan-2012 \"Added real/to-native32 and real/from-native32 functions\"\n ]\n Purpose: {\n Contains functions for the manipulation of decimal values,\n packaged into the REAL object. These provide full support for\n native binary floating-point file IO, compatible with C,\n FORTRAN, etc. REBOL decimal and money values may also be saved\n and loaded with no roundoff error. This package is necessary\n because the standard REBOL representation of decimal values\n may round off one or two significant digits, and the rounding\n of money values is an even greater source of error.\n\n This script contains two more objects, IEEE and EMPIRICAL,\n which provide several functions useful for exploring how\n decimal values are represented as double floating point numbers,\n and for testing the inexactness of the REBOL comparison functions.\n }\n Dependencies: [\n {The following require %format.r to properly format the output,\n though they will work without it. %format.r should be loaded\n before this script.}\n\n real/form\n real/show/decimal\n IEEE/rebtest\n empirical/rebtest\n\n {please download: } http://www.rebol.org/utility/format.r\n ]\n]\n\ncomment { =============== REAL ===============\n\nREAL is an object that packages several functions useful for examining,\nsaving, exporting and importing decimal values:\n\nMain Interface Functions\nFORM Returns precise decimal representation (requires format.r).\nSHOW Returns a string showing the bits in the IEEE representation.\nTO-NATIVE Converts a decimal value into a native IEEE binary\nFROM-NATIVE Converts an 8-byte native binary into a decimal value.\nSAVE Saves a value with all decimal values converted.\nLOAD Loads a value and restores 8-byte binaries to decimals.\nWRITE Writes a block of decimal values to a file in native form.\nREAD Reads a file containing a series of decimal values expressed\n in native form.\n\nHelper Functions\nSPLIT Returns a block with the three components of the IEEE\n double floating point representation of a decimal value.\nCONVERT Converts all decimal values to native binaries, leaves other\n values untouched.\nRESTORE Restores 8-byte binaries to decimal values.\nTO-BIN Returns a binary string representation or a numeric value.\nFROM-BIN Returns the integer represented by string of 1's and 0's.\nTO-MATRIX Converts a flat block into nested blocks of any depth.\n\n}\n\nreal: make object! [\n\ncomment { =============== REAL/FORM ===============\n\nNOTE: Please see FULL-FORM in format.r for details.\n\n}\n\n; Set the word FORM in the context of this object:\n; either to the function FULL-FORM if available, or else to the global FORM.\n\nform: either value? 'full-form [:full-form][get in system/words 'form]\n\ncomment { =============== REAL/SHOW ===============\n\nEXAMPLES:\n\n>> real/show 2\n== {0 10000000000 0000000000000000000000000000000000000000000000000000}\n>> real/show 3\n== {0 10000000000 1000000000000000000000000000000000000000000000000000}\n>> real/show 3.5\n== {0 10000000000 1100000000000000000000000000000000000000000000000000}\n>> real/show 4\n== {0 10000000001 0000000000000000000000000000000000000000000000000000}\n>> real/show/decimal 3.5\n== \"0 1024 3377699720527872\" ; requires format.r\n\n>> real/show ieee/max-real\n== {0 11111111110 1111111111111111111111111111111111111111111111111111}\n\n}\n\nshow: func [\n \"return an IEEE-compatible string representation in binary\"\n x [number!]\n /decimal \"return a decimal representation\"\n /local out sign exponent fraction\n][\n set [sign exponent fraction] split x\n out: copy \" \"\n either decimal [\n append out form fraction\n insert next out form exponent\n insert out sign\n ][\n append out to-bin/length fraction 52\n insert next out to-bin/length exponent 11\n insert out sign\n ]\n out\n]\n\ncomment { =============== REAL/TO-NATIVE REAL/FROM-NATIVE ===============\n\nEXAMPLES:\n\n>> real/to-native pi\n== #{400921FB54442D18}\n>> real/to-native/rev pi\n== #{182D4454FB210940} ; configuration used in PC's\n>> real/from-native real/to-native pi\n== 3.14159265358979\n>> pi - real/from-native real/to-native pi\n== 0 ; converts back to exact value\n}\n\nto-native: func [\n \"convert a numerical value into native binary format\"\n x [number!]\n /rev \"reverse binary output\"\n /local out sign exponent fraction\n][\n set [sign exponent fraction] split x\n out: copy #{}\n loop 6 [\n insert out to char! byte: fraction // 256\n fraction: fraction - byte / 256\n ]\n insert out to char! exponent // 16 * 16 + fraction\n insert out to char! exponent / 16 + (128 * sign)\n return either rev [head reverse out][out]\n]\nto-native32: func [\n \"convert a numerical value into native binary format\"\n x [number!]\n /rev \"reverse binary output\"\n /local out sign exponent fraction\n][\n set [sign exponent fraction] split32 x\n out: copy #{}\n loop 2 [\n insert out to char! byte: fraction // 256\n fraction: fraction - byte / 256\n ]\n insert out to char! exponent * 128 // 256 + fraction\n insert out to char! exponent / 2 + (128 * sign)\n return either rev [head reverse out][out]\n]\nfrom-native: func [\n {convert a binary native into a decimal value - also accepts a binary\n string representation in the format returned by REAL/SHOW}\n in [binary! string!]\n /rev \"binary input in reverse order\"\n /local sign exponent fraction\n][\n in: copy in\n either binary? in [\n if rev [reverse in]\n sign: either zero? to integer! (first in) / 128 [1][-1]\n exponent: (first in) // 128 * 16 + to integer! (second in) / 16\n fraction: to decimal! (second in) // 16\n in: skip in 2\n loop 6 [\n fraction: fraction * 256 + first in\n in: next in\n ]\n ][\n set [sign exponent fraction] parse in none\n sign: either sign = \"0\" [1][-1]\n exponent: from-bin exponent\n fraction: from-bin fraction\n ]\n sign * either zero? exponent [\n 2 ** -1074 * fraction\n ][\n 2 ** (exponent - 1023) * (2 ** -52 * fraction + 1)\n ]\n]\nfrom-native32: func [\n {convert a binary native into a decimal value - also accepts a binary\n string representation in the format returned by REAL/SHOW}\n in [binary! string!]\n /rev \"binary input in reverse order\"\n /local sign exponent fraction\n][\n in: copy in\n either binary? in [\n if rev [reverse in]\n sign: either zero? to integer! (first in) / 128 [1][-1]\n exponent: ((first in) and 127) * 2 + to integer! (second in) / 128\n fraction: to decimal! (second in) // 128\n in: skip in 2\n loop 2 [\n fraction: fraction * 256 + first in\n in: next in\n ]\n ][\n set [sign exponent fraction] parse in none\n sign: either sign = \"0\" [1][-1]\n exponent: from-bin exponent\n fraction: from-bin fraction\n ]\n sign * either zero? exponent [\n 2 ** -149 * fraction\n ][\n 2 ** (exponent - 127) * (2 ** -23 * fraction + 1)\n ]\n]\ncomment { =============== REAL/SAVE REAL/LOAD ===============\n\nREAL/SAVE and REAL/LOAD are meant to be completely compatible\nwith the standard functions SAVE and LOAD, except that there\nwill be no roundoff error from saving and loading decimal\nor money values.\n\nEXAMPLE:\n\n>> amount: [100 * $1.504]\n== [100 * $1.50]\n\n>> save %test-x.dat amount\n>> do load %test-x.dat\n== $150.00 ; large round-off error\n\n>> real/save %test-y.dat amount\n>> do real/load %test-y.dat\n== $150.40 ; no error\n}\n\nsave: func [\n {Saves a value with all decimals converted to binary natives}\n where [file! url!] \"Where to save it.\"\n value \"Value to save.\"\n /header \"Save it with a header\"\n header-data [block! object!] \"Header block or object\"\n][\n either header [\n system/words/save/header where convert :value convert header-data\n ][\n system/words/save where convert :value\n ]\n]\n\nload: func [\n {Loads a value and converts binary natives to decimals}\n source [file! url! string! any-block!]\n /header \"Includes REBOL header object if present\"\n /next {Load the next value only.\n Return block with value and new position.}\n /local lp\n][\n lp: copy 'system/words/load\n foreach item [header next][\n if get item [insert tail :lp item]\n ]\n restore lp source\n]\n\ncomment { =============== REAL/WRITE REAL/READ ===============\n\nNOTE: REAL/WRITE and REAL/READ are meant for writing and reading\n decimal values in native binary format. REAL/WRITE accepts\n a single numerical value or a block of numerical values that\n may be nested to any depth, but the return value of REAL/READ\n is always a flat block.\n\nEXAMPLES:\n\n>> b1: [] for x 1 16 1 [append b1 square-root x]\n== [1 1.4142135623731 1.73205080756888 2 2.23606797749979 ...\n>> real/write %test.bin b1\n16 decimal values written\n\n>> bb1: real/read %test.bin\n== [1 1.4142135623731 1.73205080756888 2 2.23606797749979 ...\n>> b1/7 - probe bb1/7\n2.64575131106459 ; square root of 7\n== 0 ; is restored exactly\n\n>> b2: real/to-matrix b1 4 ; convert to 4x4 matrix\n== [[1 1.4142135623731 1.73205080756888 2] [2.23606797749979 ...\n>> real/write %test.bin b2\n16 decimal values written ; the same values are written,\n>> bb2: real/read %test.bin ; and read back into a flat block\n== [1 1.4142135623731 1.73205080756888 2 2.23606797749979 ...\n}\n\nwrite: func [\n {Writes a (nested) block of decimal values\n to a file in native binary format}\n f [file!] \"file to write to\"\n b [block! number!] \"number or block of numbers\"\n /rev \"reverse bytes if needed\"\n /append \"append to file\"\n /local out elem p to-do\n][\n out: copy #{}\n to-do: copy []\n insert to-do b\n nat: to path! either rev [[to-native rev]][[to-native]]\n while [ not tail? to-do ] [\n either block? first to-do [\n change/part to-do first to-do 1\n ][\n insert tail out nat first to-do\n remove to-do\n ]\n ]\n either append [\n system/words/write/binary/append f out\n ][\n system/words/write/binary f out\n ]\n print [(length? out) / 8 \"decimal values written\"]\n]\n\nread: func [\n {Returns a block of numbers read in from a binary data file}\n f \"file name of binary file\"\n /rev \"reverse bytes if needed\"\n /local tmp out from l\n][\n tmp: system/words/read/binary f\n l: (length? tmp) / 8\n if not zero? l - to integer! l\n [make error! \"read-native: bad file size\"]\n out: make block! l\n from: make path! either rev [[from-native rev]][[from-native]]\n loop l [\n insert tail out from copy/part tmp 8\n tmp: skip tmp 8\n ]\n out\n]\n\n\ncomment { =============== REAL/SPLIT ===============\n\nSPLIT calculates the three components of the IEEE representation of a\ndouble floating point value. These are the actual values used by the CPU\nin numerical calculations.\n\n>> set [sign exponent fraction] real/split pi\n== [0 1024 2.57063812465794E+15]\n>> (-1 ** sign) * (2 ** (exponent - 1023)) * (1 + (fraction * (2 ** -52)))\n== 3.14159265358979\n\nNumbers smaller than 2 ** -1022 (denormals, which have an exponent\ncomponent of zero) use a different formula:\n\n>> set [sign exponent fraction] real/split probe 2 ** -1030\n8.69169475979376E-311\n== [0 0 17592186044416]\n>> (-1 ** sign) * (2 ** -1074) * fraction\n== 8.69169475979376E-311\n}\n\nsplit: func [\n \"Returns block containing three components of double floating point value\"\n x [number!] /local sign exponent fraction\n][\n sign: either negative? x [x: (- x) 1][0]\n\n either zero? x [exponent: 0 fraction: 0][\n\n either zero? 1024 - exponent: to integer! log-2 x [exponent: 1023][\n if positive? (2 ** exponent) - x [exponent: exponent - 1]\n ]\n fraction: x / (2 ** exponent)\n\n either positive? exponent: exponent + 1023 [\n fraction: fraction - 1 ; drop the first bit for normals\n fraction: fraction * (2 ** 52) ; make the remaining fraction an\n ; \"integer\"\n ][\n fraction: 2 ** (51 + exponent) * fraction ; denormals\n exponent: 0\n ]\n ]\n reduce [sign exponent fraction]\n]\n\nsplit32: func [\n \"Returns block containing three components of double floating point value\"\n x [number!] /local sign exponent fraction\n][\n sign: either negative? x [x: (- x) 1][0]\n\n either zero? x [exponent: 0 fraction: 0][\n\n either zero? 128 - exponent: to integer! log-2 x [exponent: 127][\n if positive? (2 ** exponent) - x [exponent: exponent - 1]\n ]\n fraction: x / (2 ** exponent)\n\n either positive? exponent: exponent + 127 [\n fraction: fraction - 1 ; drop the first bit for normals\n fraction: fraction * (2 ** 23) ; make the remaining fraction an\n ; \"integer\"\n ][\n fraction: 2 ** (22 + exponent) * fraction ; denormals\n exponent: 0\n ]\n fraction: to integer! fraction + .5\n ]\n reduce [sign exponent fraction]\n]\ncomment { =============== REAL/CONVERT REAL/RESTORE ===============\n\nThese functions are principally meant to be used by REAL/SAVE and\nREAL/LOAD. REAL/CONVERT accepts a value of any SAVE-able datatype,\nconverts all decimal values to native binaries, and returns the\nresult. The argument value is unaffected. REAL/RESTORE does the\nreverse of REAL/CONVERT, restoring all of the original decimal\nvalues. This allows decimal values to be saved with no roundoff error.\n\nSince all object and any-block values are copied, the result of\nconverting and restoring may not be identical to the original value.\nThe result will be good enough, however, to allow saving and\nloading of values compatible with the behavior of the standard\nfunctions SAVE and LOAD, and without any roundoff error.\n\nEXAMPLE:\n\n>> circle-area: func [r [number!]] compose [(pi) * r * r]\n>> probe obj1: make object! compose/deep [\n[ a: [(pi) (exp 1)] b: (EU$1.00 * pi) c: real/to-native (pi)\n[ f: :circle-area ]\n\nmake object! [\n a: [3.14159265358979 2.71828182845905]\n b: EU$3.14\n c: #{400921FB54442D18}\n f: func [r [number!]][3.14159265358979 * r * r]\n]\n\n>> probe obj2: real/convert obj1\n\nmake object! [\na: [#{400921FB54442D18} #{4005BF0A8B145769}]\nb: (EU$1.00 * #{400921FB54442D18}) ; money value converted to paren\nc: ['escape #{400921FB54442D18}] ; pre-existing 8-byte binary is escaped\nf: func [r [number!]][#{400921FB54442D18} * r * r]\n]\n>> probe obj3: real/restore obj2\n\nmake object! [\na: [3.14159265358979 2.71828182845905]\nb: EU$3.14\nc: #{400921FB54442D18}\nf: func [r [number!]][3.14159265358979 * r * r]\n]\n\n>> obj3/a/1 - pi ; decimal values are exactly restored\n== 0\n>> (obj3/f 4) - circle-area 4 ; restored function gives same answer\n== 0\n\n}\n\nconvert: func [\n {returns (copy of) B with all decimals converted to binary natives}\n value \"value to convert\"\n /local r\n][\n if function? :value [\n return func load mold third :value convert second :value\n ]\n if object? :value [\n r: make value []\n foreach word next first r [\n set in r word convert get in r word\n ]\n return r\n ]\n if any-block? :value [\n r: copy :value\n while [not tail? :r] [\n change/only :r convert first :r\n r: next :r\n ]\n return head :r\n ]\n if money? :value [\n return to paren! compose [(value / value/2) * (to-native value/2)]\n ]\n if all [\n binary? :value\n 8 = length? value\n ][ ; return an \"escaped\" form\n return compose ['escape (value)]\n ]\n if :value = first ['escape] [\n return ['escape 'escape]\n ]\n either decimal? :value [to-native value][:value]\n]\n\nrestore: func [\n {returns (copy of) B with all binary natives converted to decimals}\n value \"value to convert\"\n /local r item\n][\n if function? :value [\n return func load mold third :value restore second :value\n ]\n if object? :value [\n r: make value []\n foreach word next first r [ ; cycle through all words except first\n set in r word restore get in r word\n ]\n return r\n ]\n if any-block? :value [\n if all [\n paren? :value\n 3 = length? :value\n money? first :value\n binary? item: pick :value 3\n ][ ; restore a money value\n change at :value 3 from-native item\n return value\n ]\n if all [\n block? :value\n 2 = length? value\n (first value) = (first ['escape])\n ][\n return second value ; return the \"escaped\" value\n ]\n r: copy :value\n while [not tail? :r] [\n change/only :r restore first :r\n r: next :r\n ]\n return head :r\n ]\n either all [\n binary? :value\n 8 = length? value\n ][from-native value][:value]\n]\n\ncomment { =============== TO-BIN FROM-BIN ===============\n\nNOTE: used by REAL/SHOW and REAL/FROM-NATIVE\n\n}\n\nto-bin: func [\n {return a binary string representation of N}\n n [number!] \"number to show in binary (integer value from 0 to 2 ** 53)\"\n /length l \"length of string desired\"\n /local r v\n][\n if not l [l: 1]\n either negative? n - 1 [r: copy \"0\"][\n r: copy \"\"\n v: 2 ** to integer! log-2 n\n if negative? n - v [v: v / 2] ; in case LOG-2 rounds up\n while [ v >= 1 ] [\n insert tail r either negative? n - v [\"0\"][n: n - v \"1\"]\n v: v / 2\n ]\n ]\n head insert/dup r \"0\" (l - length? r)\n]\n\nfrom-bin: func [\n {convert a binary string representation into a numeric value}\n b [string!]\n /local x bitval\n][\n bitval: 1.0\n b: tail b\n x: 0\n while [ not head? b ] [\n b: back b\n if #\"1\" = first b [x: x + bitval]\n bitval: bitval * 2\n ]\n x\n]\n\n\ncomment { =============== TO-MATRIX ===============\n\nEXAMPLE:\n\n>> to-matrix [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16] 4\n== [[1 2 3 4] [5 6 7 8] [9 10 11 12] [13 14 15 16]]\n>> to-matrix [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16] [2 4]\n== [[[1 2 3 4] [5 6 7 8]] [[9 10 11 12] [13 14 15 16]]]\n\n}\n\nto-matrix: func [\n {Returns a matrix constructed from the values of B}\n b [block!]\n row-length [number! block!]\n /local out number-rows\n][\n if number? row-length [row-length: reduce [row-length]]\n reverse row-length\n number-rows: length? b\n foreach l row-length [\n number-rows: number-rows / l\n if not zero? number-rows - to integer! number-rows\n [make error! \"to-matrix: bad dimensions\"]\n out: make block! number-rows\n loop number-rows [\n insert/only tail out copy/part b l\n b: skip b l\n ]\n b: out\n ]\n out\n]\n\n] ; end REAL\n\n\ncomment { =============== IEEE ===============\n\nIEEE is an object that contains:\n\nREBTEST A function that tests the sensitivity of the REBOL EQUAL?\n comparison function.\nGET-NEXT A function that makes the minimum increment to a decimal value.\nGET-LAST A function that makes the maximum decrement to a decimal value.\nMAX-REAL The largest decimal value.\nMIN-NORM The smallest positive normalized decimal.\nMIN-REAL The smallest positive decimal value.\nEPS The minimum increment to 1 (smallest x such that (x+1)>1).\n\nAll of the increments and other values in IEEE are calculated based on\nIEEE Std 754 (International Electrical and Electronic Engineering society).\n\nREBTEST points out the inexactness of the REBOL comparison functions (as of\nversion 2.2), but note that it is easy to get exact comparisons by using\nZERO? NEGATIVE? and POSITIVE? to test the results of subtraction:\n\n>> x: .1\n== 0.1\n>> y: ieee/get-next .1 ; make minimum increment to .1\n== 0.1\n>> y - x\n== 1.38777878078145E-17 ; Y is greater than X ...\n>> equal? x y\n== true ; inexact\n>> zero? x - y\n== false ; exact\n>> greater? y x\n== false\n>> positive? y - x\n== true\n>> lesser? x y\n== false\n>> negative? x - y\n== true\n\n; Example of rebtest (format.r not loaded so we get REBOL display values)\n; Let's use 2 ** 53 as the target. All positive integers from 1 to 2 ** 53\n; are exact in binary form. All doubles greater than 2 ** 52 are integers.\n; The doubles from 2 ** 52 thru 2 ** 53 are consecutive integers.\n; The first column shows the result of REBOL's test for equality of the target\n; to (target + increment). The 2nd column shows REBOL display value and the\n; 3rd column shows the increment.\n\n>> ieee/rebtest 2 ** 53 ; the exact value is 9007199254740992\ntarget 9.00719925474099E+15 ; REBOL display rounds to 15 sig. digits\npositive increments\nt=t+i target+increment increment\ntrue 9.00719925474099E+15 2 ; positive increments are of size 2\ntrue 9.007199254741E+15 4 ; REBOL display value changes\ntrue 9.007199254741E+15 6 ; REBOL equality test is wrong\ntrue 9.007199254741E+15 8\ntrue 9.007199254741E+15 10\ntrue 9.007199254741E+15 12\ntrue 9.00719925474101E+15 14 ; REBOL display changes again\ntrue 9.00719925474101E+15 16 ; but equality test is still wrong\nfalse 9.00719925474101E+15 18 ; equality test correct once we add 18\nfalse 9.00719925474101E+15 20\nnegative increments\nt=t+i target+increment increment\nfalse 9.00719925474099E+15 -1 ; negative increments are of size 1\nfalse 9.00719925474099E+15 -2\nfalse 9.00719925474099E+15 -3\nfalse 9.00719925474099E+15 -4\nfalse 9.00719925474099E+15 -5\nfalse 9.00719925474099E+15 -6 ; REBOL equality test OK for all inc.\nfalse 9.00719925474099E+15 -7\nfalse 9.00719925474098E+15 -8 ; REBOL display changes\nfalse 9.00719925474098E+15 -9\nfalse 9.00719925474098E+15 -10\n\n}\n\nIEEE: make object! [\n\ncomment { =============== IEEE/REBTEST ===============\n\nREBTEST makes ten successive minimum increments and decrements to the\ntarget value, and tests whether EQUAL? returns TRUE when comparing\nthe results to the original value. In all cases EQUAL? should return\nfalse.\n\n}\n\nrebtest: func [\n {displays 21 adjacent doubles centered on x}\n x [number!] \"target value\"\n /local y\n][\n print [\"target\" x ]\n print \"positive increments\"\n print [\"t=t+i\" \"target+increment\" \"increment\"]\n y: x\n loop 10 [\n if all [positive? y zero? y - max-real][\n print [\"\" \"+Inf\"]\n break\n ]\n y: get-next y\n print [equal? x y y y - x]\n ]\n print \"negative increments\"\n print [\"t=t+i\" \"target+increment\" \"increment\"]\n y: x\n loop 10 [\n if all [negative? y zero? y + max-real][\n print [\"\" \"-Inf\"]\n break\n ]\n y: get-last y\n print [equal? x y y y - x]\n ]\n]\n\nget-next: func [\n {returns next double after x}\n x [number!] \"input value\"\n /local exp inc\n][\n if zero? x [return 2 ** -1074]\n if negative? x [return - get-last (- x)]\n either zero? 1024 - exp: to-integer log-2 x [exp: 1023][\n if positive? (2 ** exp) - x [exp: exp - 1]\n ]\n inc: 2 ** (exp - 52) ; local machine precision\n if exp < -1021 [inc: 2 ** -1074] ; handle denormals\n x + inc\n]\n\nget-last: func [\n {returns next double before x}\n x [number!] \"input value\"\n /local exp inc\n][\n if zero? x [return - (2 ** -1074)]\n if negative? x [return - get-next (- x)]\n either zero? 1024 - exp: to-integer log-2 x [exp: 1023][\n if not negative? (2 ** exp) - x [exp: exp - 1]\n ]\n inc: 2 ** (exp - 52) ; local machine precision\n if exp < -1021 [inc: 2 ** -1074] ; handle denormals\n x - inc\n]\n\nmax-real: 2 ** 1023 * (2 - (2 ** -52)) ; maximum decimal value\n\nmin-norm: 2 ** -1022 ; minimum normalized positive value\n\nmin-real: 2 ** -1074 ; minimum positive decimal value\n\neps: 2 ** -52 ; machine epsilon (smallest x such that (x+1)>1)\n\n; if possible, set PRINT locally to a function providing formatted output\n\nprint: either value? 'format [\n func [line][\n system/words/print format/full reduce line [#8..3 #24.16.1 #12.2.1]\n ]\n][\n get in system/words 'print\n]\n\n] ; end IEEE\n\ncomment { =============== EMPIRICAL ===============\n\nEMPIRICAL is equivalent to IEEE, but whereas the values in IEEE are\ncalculated based on the IEEE standard, the values in EMPIRICAL are\nobtained through an empirical algorithm. The function CMP-SENS does\nthis by actually trying a series of increments to the target value,\nuntil the smallest value is identified that results in a different\nvalue when added to the target.\n\n}\n\nempirical: make object! [\n\ncmp-sens: func [\n {find smallest effective increment for TARGET.\n NOTE: this is less than the resulting increment}\n target [number!]\n /exact {results for exact comparison - default is use EQUAL?}\n /below \"return decrement (default is increment)\"\n /local diff upper lower last-diff eqf operation no-effect\n][\n eqf: either exact [func[x y][zero? x - y]][:equal?]\n operation: either below [ :subtract ][ :add ]\n last-diff: upper: max 2 ** -30 abs target * (2 ** -30)\n lower: 0\n diff: upper + lower / 2\n while [ not zero? last-diff - diff ] [\n last-diff: diff\n if error? try [\n no-effect: eqf target operation target diff\n ][\n no-effect: none\n ]\n either no-effect [\n lower: diff\n diff: diff + upper / 2\n ][\n upper: diff\n diff: diff + lower / 2\n ]\n ]\n return either none? no-effect [none][upper]\n]\n\nrebtest: func [\n {compare sensitivity of REBOL comparison operators against\n actual increment value}\n target [number!]\n /local inc rebsense factor\n][\n if inc: cmp-sens/exact target [ ; get effective increment\n inc: target + inc - target ; get resulting increment\n if rebsense: cmp-sens target [\n rebsense: target + rebsense - target\n if 1e10 < factor: rebsense / inc [factor: form factor]\n ]\n ]\n print [\"Increments:\" \"Smallest\" \"NOT EQUAL?\" \"Factor\"]\n print [\"Positive:\" inc rebsense factor]\n factor: none\n if inc: cmp-sens/below/exact target [\n inc: target - inc - target\n if rebsense: cmp-sens/below target [\n rebsense: target - rebsense - target\n if 1e10 < factor: rebsense / inc [factor: form factor]\n ]\n ]\n print [\"Negative:\" inc rebsense factor]\n]\n\nget-next: func [\n {make the smallest possible increment to a double}\n target [number!]\n /count n \"number of times to do this\"\n][\n if not n [n: 1]\n loop n [\n target: target + cmp-sens/exact target\n ]\n]\n\nget-last: func [\n {make the smallest possible decrement to a double}\n target [number!]\n /count n \"number of times to do this\"\n][\n if not n [n: 1]\n loop n [\n target: target - cmp-sens/below/exact target\n ]\n]\n\nmax-real: func [\n {returns the highest numerical value on the system}\n /local x lower upper factor last-factor\n][\n x: 2.0\n loop 100000 [\n if error? try [x: x * 2][break]\n ]\n lower: 1\n upper: 2\n last-factor: 0\n loop 100000 [\n if zero? last-factor - factor: lower + upper / 2 [break]\n either error? try [x * factor] [upper: factor][lower: factor]\n last-factor: factor\n ]\n x * lower\n]\n\nmin-real: get-next 0\n\neps: (get-next 1) - 1\n\nprint: either value? 'format [\n func [\n {print out a formatted line if FORMAT is available}\n line\n ][\n system/words/print format/full reduce line\n [#-12 #12.2.1 #12.2.1 #8]\n ]\n][\n get in system/words 'print\n]\n\n] ; end empirical\n\n\n", "meta": {"hexsha": "2f33e5416f6152326184d9edde435dcf78d9324c", "size": 28687, "ext": "r", "lang": "R", "max_stars_repo_path": "projects/decimal/latest/decimal.r", "max_stars_repo_name": "Oldes/rs", "max_stars_repo_head_hexsha": "d96d7ba96e9fd2a6ac998ed3be98212feb21df6e", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2015-02-02T10:08:01.000Z", "max_stars_repo_stars_event_max_datetime": "2018-03-30T13:43:53.000Z", "max_issues_repo_path": "projects/decimal/latest/decimal.r", "max_issues_repo_name": "Oldes/rs", "max_issues_repo_head_hexsha": "d96d7ba96e9fd2a6ac998ed3be98212feb21df6e", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "projects/decimal/latest/decimal.r", "max_forks_repo_name": "Oldes/rs", "max_forks_repo_head_hexsha": "d96d7ba96e9fd2a6ac998ed3be98212feb21df6e", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.48565356, "max_line_length": 82, "alphanum_fraction": 0.608847213, "num_tokens": 7993, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621764862150634, "lm_q2_score": 0.709019146082187, "lm_q1q2_score": 0.3985938922036886}} {"text": "# Function for calculate phytosociological table\n# Version: 1.2.0\n# https://github.com/MarioJose/r-functions/tree/master/phyto\n\nphyto <- function(x, filter = NULL, area = NULL, criteria = NULL, measure = NULL, incDead = TRUE, nmDead = \"Dead\", diversity = TRUE, evenness = TRUE){\n # x must be data frame with: plot, family, specie, diameter, (height).\n # It must be in this order, but not necessarily with this names. Height is\n # optional\n \n # Checking input\n # ++++++++++++++\n \n if(!is.data.frame(x)){\n stop(\"'x' must be a data frame\")\n } else {\n if(dim(x)[2] < 4 | dim(x)[2] > 5){\n stop(\"Your data frame must have at least 4 columns with the follow data at the same order: 'plot', 'family', 'specie', 'diameter'. The column 'height' is optional\")\n }\n }\n \n if(is.null(filter)){\n stop(\"You must inform the filter to summarization: 'plot', 'family', 'genus', 'specie'\")\n } else {\n if(!(filter %in% c(\"plot\", \"family\", \"genus\", \"specie\"))){\n stop(\"You must inform one of the follow option to filter: 'plot', 'family', 'genus', 'specie'\")\n }\n }\n \n if(is.null(area)){\n stop(\"You must inform the area sampled\")\n }\n \n if(is.null(criteria)){\n stop(\"You must inform the diameter criteria for individual inclusion\")\n }\n\n if(is.null(measure)){\n stop(\"You must inform the measure: \\\"d\\\" = diameter; \\\"c\\\" = circumference\")\n } else {\n if(!(measure %in% c(\"d\",\"c\"))){\n stop(\"You must inform one of the follow option to measure: \\\"d\\\" = diameter; \\\"c\\\"c = circumference\")\n }\n }\n \n # Convert family and species column to character\n x[ ,2] <- as.character(x[ ,2])\n x[ ,3] <- as.character(x[ ,3])\n \n # Remove dead individuals (column 'specie')\n if(!incDead){\n didx <- grep(nmDead , x[ ,3])\n x <- x[-didx, ]\n print(paste(\"Removed\", length(didx), \"individual named as\", nmDead))\n }\n\n\n # Functions\n # +++++++++\n \n # Split multiple diameter or height and return diameter of total basal area of\n # each individual or mean height of each individual\n splitMultiple <- function(x, m){\n \n if(!is.numeric(x)) tmp <- as.numeric(unlist(strsplit(x , \"+\", TRUE)))\n else tmp <- x\n\n # Expression used in conversion\n # area = (pi*diameter^2)/4\n # area = (circumference^2)/(4*pi)\n # diameter = sqrt((4*area)/pi)\n \n # Return diameter of total basal area\n if(m == \"d\") out <- sqrt(4 * sum((pi * (tmp ^ 2)) / 4) / pi)\n\n # Convert circumference and return diameter of total basal area\n if(m == \"c\") out <- sqrt(4 * sum((tmp ^ 2) / (4 * pi)) / pi)\n\n # Return mean of height\n if(m == \"h\") out <- mean(tmp)\n \n return(out)\n }\n \n # Shannon and Simpson diversity index\n shannon_fn <- function(x){\n p <- x / sum(x)\n H <- -sum(p * log(p)) \n # Variance as Hutcheson (1970)\n varH <- ((sum(p * (log(p)^2)) - sum(p * log(p))^2) / sum(x)) + ((length(x) - 1) / (2 * (length(x)^2)))\n \n return(c(H = H, varH = varH))\n }\n \n simpson_fn <- function(x, var = FALSE){\n # As Simpson (1949)\n N <- sum(x)\n p <- x / N\n D <- sum(x * (x - 1)) / (N * (N - 1))\n varD <- ( 4*N*(N - 1)*(N - 2)*sum(p^3) + 2*N*(N - 1)*sum(p^2) - 2*N*(N - 1)*(2*N - 3)*(sum(p^2)^2) ) / (N*(N - 1))^2\n # if N be very large, approximately \n #varD <- (4/N) * ( (sum(p^3)) - (sum(p^2))^2 );\n \n return(c(D = D, varD = varD))\n }\n \n # Evar and E1/D evenness index\n evenness_fn <- function(x){\n # As Smith & Wilson (1996)\n\n mulog <- sum(log(x)) / length(x)\n # 0 = minimum eveness\n Evar <- 1 - (2 / pi) * atan( sum((log(x) - mulog)^2) / length(x) )\n E1D <- (1 / simpson_fn(x)[[\"D\"]]) / length(x)\n \n return(c(Evar = Evar, E1D = E1D))\n }\n\n \n # Checking data\n # +++++++++++++\n \n # Columns names\n colnames(x) <- c(\"plot\", \"family\", \"specie\", \"diameter\", \"height\")[1:dim(x)[2]]\n \n # Create column with genus\n x$genus <- sapply(x$specie, function(x) strsplit(x, \" \")[[1]][1])\n \n # Order data frame\n x <- x[, c(1:2, dim(x)[2], 3:(dim(x)[2] - 1))] \n \n # Standardize measure to diameter. Split multiples measures and return \n # diameter of total basal area to individual\n if(is.character(x$diameter) | is.factor(x$diameter))\n x$diameter <- sapply(as.character(x$diameter), splitMultiple, m = measure)\n else if(measure == \"c\") x$diameter <- x$diameter / pi\n \n # Standardize height. Split multiples measures and return mean of height to\n # individual\n if(dim(x)[2] == 6)\n if(is.character(x$height) | is.factor(x$height))\n x$height <- sapply(as.character(x$height), splitMultiple, m = \"h\")\n \n # Filter by inclusion criteria\n cidx <- x$diameter >= criteria\n x <- x[cidx, ]\n \n if(dim(x)[1] < 1) stop(\"Your criteria removed all individuals\")\n else print(paste(\"Removed\", length(cidx) - sum(cidx), \"individual(s) by criteria\", criteria))\n \n \n # Calculate parameters \n # ++++++++++++++++++++\n \n # Create output data frame\n out <- aggregate(list(nInd = x$specie), by = list(c1 = x[ ,filter]), FUN = length)\n colnames(out) <- c(filter, \"nInd\")\n \n # Add families\n if(filter %in% c(\"genus\", \"specie\")){\n tf <- aggregate(list(nInd = x[ ,filter]), by = list(family = x$family, filter = x[ ,filter]), FUN = length)\n out$family <- tf$family[match(out[ ,filter], tf$filter)]\n out <- out[ ,c(\"family\", filter, \"nInd\")]\n }\n \n if(filter == \"plot\"){\n # Number of families per plot\n out[ ,\"nFamilies\"] <- aggregate(x$family, by = list(x$plot), FUN = function(x){length(unique(x))})$x\n \n # Number of genera per plot\n out[ ,\"nGenera\"] <- aggregate(x$genus, by = list(x$plot), FUN = function(x){length(unique(x))})$x\n \n # Number of species per plot\n out[ ,\"nSpecies\"] <- aggregate(x$specie, by = list(x$plot), FUN = function(x){length(unique(x))})$x\n \n if(diversity){\n out[ ,c(\"H\", \"varH\")] <- aggregate(x$specie, by = list(x$plot), FUN = function(x){shannon_fn(table(as.character(x)))})[[2]]\n out[ ,c(\"D\", \"varD\")] <- aggregate(x$specie, by = list(x$plot), FUN = function(x){simpson_fn(table(as.character(x)))})[[2]]\n }\n \n if(evenness)\n out[ ,c(\"Evar\",\"E1D\")] <- aggregate(x$specie, by = list(x$plot), FUN = function(x){evenness_fn(table(as.character(x)))})[[2]]\n \n }\n \n if(filter == \"family\"){\n # Number of genera per family\n out[ ,\"nGenera\"] <- aggregate(x$genus, by = list(x$family), FUN = function(x){length(unique(x))})$x\n \n # Number of species per family\n out[ ,\"nSpecies\"] <- aggregate(x$specie, by = list(x$family), FUN = function(x){length(unique(x))})$x\n }\n\n if(filter == \"genus\"){\n # Number of species per genus\n out[ ,\"nSpecies\"] <- aggregate(x$specie, by = list(x$genus), FUN = function(x){length(unique(x))})$x\n }\n \n # Convert diameter measure from centimetres to meters\n x$diameter <- x$diameter / 100\n out[ ,\"tBasalArea\"] <- aggregate(x$diameter, by = list(x[ ,filter]), FUN = function(x){sum((pi * (x^2)) / 4)})$x\n \n if(filter != \"plot\"){\n out[ ,\"AbsDens\"] <- out$nInd / area\n out[ ,\"RelDens\"] <- (out$nInd / sum(out$nInd)) * 100\n \n # Species or genera by plot\n tmp <- aggregate(list(nInd = x[ ,filter]), by = list(filter = x[ ,filter], plot=x$plot), FUN = length)\n out[ ,\"nPlot\"] <- aggregate(tmp$filter, by = list(tmp$filter), FUN = length)$x\n out[ ,\"AbsFreq\"] <- (out[ ,\"nPlot\"] / length(unique(x$plot))) * 100\n out[ ,\"RelFreq\"] <- (out$AbsFreq / sum(out$AbsFreq)) * 100\n \n out[ ,\"AbsDom\"] <- out[ ,\"tBasalArea\"] / area\n out[ ,\"RelDom\"] <- (out[ ,\"tBasalArea\"] / sum(out[ ,\"tBasalArea\"])) * 100\n \n out[ ,\"IVI\"] <- out$RelDens + out$RelFreq + out$RelDom\n out[ ,\"CVI\"] <- out$RelDens + out$RelDom\n }\n \n if(length(x[1, ]) == 6){\n out[ ,\"meanHeight\"] <- aggregate(x[ ,6], by = list(x[ ,filter]), FUN = mean)$x\n out[ ,\"sdHeight\"] <- aggregate(x[ ,6], by = list(x[ ,filter]), FUN = sd)$x\n }\n \n return(out)\n}\n", "meta": {"hexsha": "eea8b6ea8276388628bf43c78bda5f10f6a06ae0", "size": 7827, "ext": "r", "lang": "R", "max_stars_repo_path": "phyto/phyto.r", "max_stars_repo_name": "MarioJose/r-functions", "max_stars_repo_head_hexsha": "a6b2693bd8151769cc799e81bbcc10654a85123e", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2017-06-07T23:19:46.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-14T11:54:46.000Z", "max_issues_repo_path": "phyto/phyto.r", "max_issues_repo_name": "MarioJose/r-functions", "max_issues_repo_head_hexsha": "a6b2693bd8151769cc799e81bbcc10654a85123e", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "phyto/phyto.r", "max_forks_repo_name": "MarioJose/r-functions", "max_forks_repo_head_hexsha": "a6b2693bd8151769cc799e81bbcc10654a85123e", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.6327433628, "max_line_length": 170, "alphanum_fraction": 0.5736552958, "num_tokens": 2506, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708562, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.39843936696671844}} {"text": "# Internal function that uses the implementation of Telfer written by Gary Powney\n\ntelfer_func <- function (taxa_data, iterations = 10, useIterations = TRUE, minSite = 5){\n \n # Check we have two time periods\n TPs <- sort(unique(taxa_data$time_period))\n if(length(unique(taxa_data$time_period)) != 2) stop('There are not two time periods in the data')\n \n # subset data to one object for each time perod\n T1 <- unique(taxa_data[taxa_data$time_period == TPs[1], c('taxa', 'site')])\n T2 <- unique(taxa_data[taxa_data$time_period == TPs[2], c('taxa', 'site')])\n \n # remove gridcells that are only found in one time period\n T1cells <- unique(T1$site)\n T2cells <- unique(T2$site)\n allGood <- T1cells[T1cells %in% T2cells]\n T1 <- T1[T1$site %in% allGood,]\n T2 <- T2[T2$site %in% allGood,]\n \n ### Identify the number of sites each taxa occupies in each time period. ###\n T1_range <- data.frame(taxa = names(table(T1$taxa)), T1Nsites = as.numeric(table(T1$taxa)))\n T2_range <- data.frame(taxa = names(table(T2$taxa)), T2Nsites = as.numeric(table(T2$taxa)))\n \n ### Remove taxa which have less than minSite grid cells in first period ###\n T1_range_good <- T1_range[T1_range$T1Nsites >= minSite,]\n if(nrow(T1_range_good) == 0) stop(paste('No taxa satisfy the minSite criteria when comparing time',\n 'period', TPs[1], 'and', TPs[2]))\n \n ### Link the two tables by taxa ###\n spp_table <- merge(T1_range_good, T2_range, by = 'taxa')\n \n ### Identify the simple difference between the two time periods ###\n spp_table$range_change <- spp_table$T2Nsites - spp_table$T1Nsites \n\n ### convert the grid cell number to proportion of total number of cells surveyed ###\n total.cells <- length(allGood)\n \n # To avoid the problems associated with 0 proportions they were calculated as (x + 0.5) / (n + 1).\n spp_table$T1_range_prop <- (spp_table$T1Nsites + 0.5) / (total.cells + 1)\t\n spp_table$T2_range_prop <- (spp_table$T2Nsites + 0.5) / (total.cells + 1)\n \n \n spp_table$T1_logit_range <- log(spp_table$T1_range_prop / (1 - spp_table$T1_range_prop)) # logit transform the proportions\n spp_table$T2_logit_range <- log(spp_table$T2_range_prop / (1 - spp_table$T2_range_prop))\t# logit transform the proportions\n \n ### To account for non constant variance we must do the following steps to create a variable to weight the final regression ###\n row.names(spp_table) <- spp_table$taxa # name rows helps make sense of the model output\n m1 <- lm(T2_logit_range ~ T1_logit_range, data = spp_table) \t# linear regression of two time periods\n\n if(!useIterations){\n \n spp_table$change_index <- rstandard(m1)\n final_output_table <- spp_table[,c(1:3,9)]\n return(list(final_output_table, spp_table))\n \n } else if(useIterations){\n \n spp_table$sq_residual_m1 <- resid(m1)^2 # square the residuals\n spp_table$fitted_proportions <- ilt(m1$fitted) # exponential function, overwrite fitted values to fitted proportions\n \n total.cell.1 <- total.cells + 1\t\t\t\t\t\t\t\t# total grid cells surveyed + 1 \n \n spp_table$NP_test <- 1 / (total.cell.1 * spp_table$fitted_proportions * \n (1 - spp_table$fitted_proportions))\t# 1 / [NP (1 - P)] in telfer paper\n \n # second model which is the squared residuals of m1 on 1/[NP (1-P)]\n m2 <- lm(sq_residual_m1 ~ NP_test, data = spp_table)\n \n # second model which is the squared residuals of m1 on 1/[NP (1-P)]\n c_ <- coef(m2)[1] # take the intercept of m2 \n d_ <- coef(m2)[2] # take the slope of m2\n \n V_ <- NULL\t\t\t\t\t\t\t\t\t\t\t\t# prepare variance vector\n rep_loop <- 1:(iterations-1)\t\t# repeat the process \n C_all <- c_\t\t\t\t\t\t\t\t\t\t\t\t# prepare c vector\n D_all <- d_\t\t\t\t\t\t\t\t\t\t\t\t# prepare d vector\n V_all <- V_\t\t\t\t\t\t\t\t\t\t\t\t# prepare variance vector\n \n \n for (i in rep_loop){ \t\t\t\t\t\t\t\n \n # c_ + d_ should not be in brackets as they were in a previous version\n V_ <- c_ + d_ / (total.cell.1 * spp_table$fitted_proportions * (1 - spp_table$fitted_proportions))\t# work out the variance (modification of the binomial proportion variance structure)\n \n # take the inverse of variance squared.\n inv_sq_V <- 1 / (V_^2)\t\t\t\t\t\t\t\t\t\t\n \n # run the new model weighting by the inverse variance identifeid above.\n error <- try(m4 <- lm(sq_residual_m1 ~ NP_test, weights = inv_sq_V, data = spp_table), silent = TRUE)\n if(class(error) == 'try-error') stop('Model failed in iteration, too little data?')\n \n c_ <- coef(m4)[1] # take the intercept of the new model\n d_ <- coef(m4)[2] # take the slope of the new model\n \n C_all <- c(C_all,c_) # build a vector with all of the new intercepts\n D_all <- c(D_all,d_) # build a vector with all of the new slopes\n V_all <- c(V_all,V_) # build a vector with all of the new inverse variances squared\n \n }\n \n ## final model to take the residuals from\n # take the reciprocal of the \"settled\" variance (Telfer et al 2002)\n spp_table$recip_V <- 1 / V_ \t\t\t\t\t\t\t\t\t\t\n # use the reciprocal of the \"settled\" variance as weight for the final model.\n m1 <- lm(T2_logit_range ~ T1_logit_range, weights = spp_table$recip_V, data = spp_table)\n # take the standardised residuals from the model.\n # For each taxa, the standardised residual from the fitted regression line provides\n # the index of relative change in range size. A taxa with a negative change index has\n # been recorded in relatively fewer grid cells in the later period, whereas a taxa with\n # a positive change index has been recorded in relatively more. \n spp_table$change_index <- rstandard(m1)\t\t\t\t\t\t\t\t\n final_output_table <- spp_table[,c(1:3,13)]\t\n\n return(list(final_output_table, spp_table))\n \n }\n\n}\n", "meta": {"hexsha": "23d05f585e61faccb5c037305000477b48ca80e4", "size": 5785, "ext": "r", "lang": "R", "max_stars_repo_path": "R/telfer_func.r", "max_stars_repo_name": "03rcooke/sparta", "max_stars_repo_head_hexsha": "8c93821965ff94a5bc9c01e6d0518ef70e30e1b9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2015-06-08T14:32:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T08:16:30.000Z", "max_issues_repo_path": "R/telfer_func.r", "max_issues_repo_name": "03rcooke/sparta", "max_issues_repo_head_hexsha": "8c93821965ff94a5bc9c01e6d0518ef70e30e1b9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 200, "max_issues_repo_issues_event_min_datetime": "2015-10-26T16:17:39.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-22T12:04:59.000Z", "max_forks_repo_path": "R/telfer_func.r", "max_forks_repo_name": "AugustT/sparta", "max_forks_repo_head_hexsha": "84594eeaaca02954ac05d058e5cc6eedb2fb3918", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19, "max_forks_repo_forks_event_min_datetime": "2015-10-26T16:18:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-21T13:50:07.000Z", "avg_line_length": 48.6134453782, "max_line_length": 189, "alphanum_fraction": 0.6649956785, "num_tokens": 1616, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548511303338, "lm_q2_score": 0.6113819732941511, "lm_q1q2_score": 0.39822661419878147}} {"text": "\n\n\n####ZIGDM_EM usage\n\n####library(DMBC)\n####library(Rlab)\n\n#' @export\n#'\n\n\n####First step: generate pi\nBernoulli <- function(c.est, row) {\n\n #pi = exp(c.est %*% row)/(1+exp(c.est %*% row))\n pi = 0\n Delta = rbern(dim(c.est)[1], pi)\n return (Delta)\n}\n\n\n####Second step: generate Z\nZvalue_Generator <- function(Delta,Test_result, row2, row3) {\n\n Beta_mean = exp(Test_result$alpha.est %*% row2)/(1+exp(Test_result$alpha.est %*% row2))\n Beta_dispersion = exp(Test_result$beta.est %*% row3)/(1+exp(Test_result$beta.est %*% row3))\n Data_Matrix = cbind(as.matrix(Delta),Beta_mean,Beta_dispersion)\n\n test = apply(Data_Matrix, 1, RandomGenerate_beta)\n return(test)\n}\n\nRandomGenerate_beta <- function(input) {\n delta = input[1]\n beta_mean =input[2]\n beta_dispersion = input[3]\n\n if (delta ==1) {\n Z = 0\n }else{\n shape1= beta_mean*(1/beta_dispersion)-beta_mean\n shape2 = (1-beta_mean)*(1/beta_dispersion -1)\n Z = rbeta(1, shape1, shape2, ncp = 0)\n }\n return(Z)\n }\n\n####Third step: generate p for multinormail distribution\nmultinormial_P <- function(Z) {\n P= list()\n P[1] = Z[1]\n if(length(Z)>1) {\n for (j in 2:length(Z)) {\n multiply =1\n for(k in 1:(j-1)) {\n multiply = multiply*(1-Z[k])\n }\n P[j] = Z[j]*multiply\n }\n }\n P= unlist(P)\n return(P)\n}\n\n\n\n\n\n\n################ Run below functions before calling\n## The function ZIGDM.EM.PAR2 estimates three sets of regression coefficients \"c\", \"alpha\", and \"beta\" in the ZIGDM regression model.\n\n## Input\n# Y: taxa count matrix.\n# Xc, Xa, Xb: design matrices for probability of absence model, mean model and dispersion model, respectively. The first column should contain \"1\" for the intercept. For intercept only model, the three matrices are simply contain vectors of 1.\n# c0: initial values for regression coefficients \"c\" organized in a matrix (dim: K x d, K+1 is the #taxa (i.e. K+1 = ncol(Y)), d is the number of columns in the corresponding design matrix)\n# alpha0: initial values for regression coefficients \"alpha\" organized in a matrix (dim: K x d)\n# beta0: initial values for regression coefficients \"beta\" organized in a matrix (dim: K x d)\n# tol: convergence tolerance\n# max.iter: maximum number of iterations\n\n## output\n# c.est: regression coefficient for the probability of absence organized in a matrix. The probabilities of absence for all the taxa in sample i can then be calculated as exp(c.est %*% Xc[i,])/(1+exp(c.est %*% Xc[i,]))\n# alpha.est: regression coefficient for the Beta mean parameter organized in a matrix. The Beta means for all the taxa in sample i can then be calculated as exp(alpha.est %*% Xa[i,])/(1+exp(alpha.est %*% Xa[i,]))\n# beta.est: regression coefficient for the Beta dispersion parameter organized in a matrix. The Beta dispersions for all the taxa in sample i can then be calculated as exp(beta.est %*% Xb[i,])/(1+exp(beta.est %*% Xb[i,]))\n\n\n## Two important remarks:\n## 1. Sort the taxa as Y = Y[,order( colSums(Y), decreasing = TRUE )] before run the analysis\n## 2. If you don't want to have zero-inflation on a certain subset of taxa, just set the elements of the corresponding columns in c0 to -Inf.\n## So to fit the GDM model, all elements in c0 matrix should be set to -Inf\n\nZIGDM.EM.PAR2 <- function(Y, Xc, Xa, Xb, c0, alpha0, beta0, tol=0.0001, max.iter=1000){\n Y = Y[,order( colSums(Y), decreasing = TRUE )]\n CONV = 0\n CONV.iter = max.iter\n n = nrow(Y)\n K = ncol(Y)-1\n dc = ncol(Xc)\n da = ncol(Xa)\n db = ncol(Xb)\n\n c.last = c0; alpha.last = alpha0; beta.last = beta0;\n c.now = c0; alpha.now = alpha0; beta.now = beta0;\n\n Del.R = matrix(NA, n, K)\n A.R = matrix(NA, n, K)\n B.R = matrix(NA, n, K)\n\n for(l in 1:max.iter){\n\n # E-step\n\n # print(paste(\"====== \", l, \"th ======\", sep=\"\"))\n for(i in 1:n){\n\n tmp = exp(c.last %*% Xc[i,])\n tmp[is.na(tmp)] = 0\n pv = as.numeric( tmp/(1+tmp) )\n pv[is.infinite(tmp) & tmp>0] =1 # positive inf\n\n tmp = exp(alpha.last %*% Xa[i,])\n mv = as.numeric( tmp/(1+tmp) )\n tmp = exp(beta.last %*% Xb[i,])\n sv = as.numeric( tmp/(1+tmp) )\n\n av = (1/sv - 1) * mv\n bv = (1/sv - 1) * (1-mv)\n\n par.post = rP.Y.par(pv, av, bv, Y[i,])\n\n Del.R[i, ] = par.post$pv.post\n tmp = par.post$av.post + par.post$bv.post\n #A.R[i, ] = digamma(par.post$av.post) - digamma(tmp)\n #B.R[i, ] = digamma(par.post$bv.post) - digamma(tmp)\n\n A.R[i, ] = as.matrix(digamma(par.post$av.post) - digamma(tmp))\n B.R[i, ] = as.matrix(digamma(par.post$bv.post) - digamma(tmp))\n\n }\n\n\n\n # M-step\n for(j in 1:K){\n\n if( !is.infinite(c.last[j,1]) ){\n c.now[j, ] = Logit.optim(Del.R[,j], Xc, c.last[j, ])\n }\n\n tmp = Beta.optim.PAR2(Del.R[,j], A.R[,j], B.R[,j], Xa, Xb, alpha.last[j, ], beta.last[j, ])\n alpha.now[j, ] = tmp[1:da]; beta.now[j, ] = tmp[-(1:da)]\n\n }\n\n\n diff = 0\n if( sum(!is.infinite(c.now))>0 ){\n\n diff = diff + sum(abs(c.now[!is.infinite(c.now)]-c.last[!is.infinite(c.now)]))\n\n }\n\n diff = diff + sum(abs(alpha.now-alpha.last))\n diff = diff + sum(abs(beta.now-beta.last))\n if( diff < tol ){\n\n CONV = 1; CONV.iter = l;\n break;\n\n }else{\n\n c.last = c.now; alpha.last = alpha.now; beta.last = beta.now;\n }\n\n }\n\n return(list(c.est = c.now, alpha.est = alpha.now, beta.est = beta.now, CONV=CONV, CONV.iter = CONV.iter))\n\n}\n\n\n\nrP.Y.par <- function(pv, av, bv, Y){\n\n K = length(Y)-1\n N = sum(Y)\n\n pv.post = rep(0, K)\n\n av.prim = av + Y[1:K]\n bv.prim = bv\n for(j in 1:K){\n bv.prim[j] = bv.prim[j] + (N - sum(Y[1:j]))\n\n if(Y[j]==0){\n\n if(beta(av[j], bv[j])==0){\n\n pv.post[j] = pv[j]/(pv[j] + (1-pv[j]))\n\n }else{\n tmp = pv[j] + (1-pv[j])*beta(as.numeric(av.prim[j]), bv.prim[j])/beta(av[j], bv[j])\n #tmp = pv[j] + (1-pv[j])*beta(av.prim[j], bv.prim[j])/beta(av[j], bv[j])\n if(tmp==0){\n pv.post[j] = 1\n }else{\n pv.post[j] = pv[j]/tmp\n }\n\n }\n\n\n }\n\n }\n\n return(list(pv.post = pv.post, av.post = av.prim, bv.post = bv.prim))\n}\n\nlbeta2 <- function(a,b){\n a[a<0] = 0\n b[b<0] = 0\n return(lbeta(a,b))\n}\n\nLogit.neg.loglik <- function(par, data){\n\n tmp = as.numeric( exp( data$X %*% par ) )\n p = tmp/(1+tmp)\n tmp = data$Del * log(p) + (1-data$Del) * log(1-p)\n index = which(p==0 | p==1)\n if(length(index)>0){\n tmp[index] = 0\n }\n\n return( -sum( tmp) )\n\n}\n\nLogit.neg.score <- function(par, data){\n\n tmp = as.numeric( exp( data$X %*% par ) )\n p = tmp/(1+tmp)\n return( -colSums( (data$Del - p) * data$X ) )\n\n}\n\nLogit.optim <- function(Del, X, c.ini){\n\n Logit.par.ini = c.ini\n Logit.data = list(Del=Del, X=X)\n\n return( optim(par=Logit.par.ini, fn=Logit.neg.loglik, gr=Logit.neg.score, data = Logit.data, method=\"BFGS\")$par)\n\n\n}\n\n\n\nBeta.neg.loglik.PAR2 <- function(par, data){\n\n da = ncol(data$Xa)\n alpha = par[1:da]\n beta = par[-(1:da)]\n\n\n tmp = as.numeric( exp( data$Xa %*% alpha) )\n mu.tmp = as.numeric( tmp/(1+tmp) )\n\n tmp = as.numeric( exp( data$Xb %*% beta) )\n sigma.tmp = as.numeric( tmp/(1+tmp) )\n\n a = (1/sigma.tmp - 1) * mu.tmp\n b = (1/sigma.tmp - 1) * (1-mu.tmp)\n a[a<0] = 0\n b[b<0] = 0\n\n return( -sum( (1-data$Del) * ( -lbeta2(a,b) + data$A * (a-1) + data$B *(b-1) ) ) )\n\n}\n\nBeta.neg.score.PAR2 <- function(par, data){\n\n da = ncol(data$Xa)\n alpha = par[1:da]\n beta = par[-(1:da)]\n\n tmp.a = as.numeric( exp( data$Xa %*% alpha) )\n mu.tmp = as.numeric( tmp.a/(1+tmp.a) )\n\n tmp.b = as.numeric( exp( data$Xb %*% beta) )\n sigma.tmp = as.numeric( tmp.b/(1+tmp.b) )\n\n a = (1/sigma.tmp - 1) * mu.tmp\n b = (1/sigma.tmp - 1) * (1-mu.tmp)\n a[a<0] = 0\n b[b<0] = 0\n\n a.a = (1/tmp.b) * mu.tmp * (1/(1+tmp.a))\n a.b = -(1/tmp.b) * mu.tmp\n b.a = - a.a\n b.b = -(1/tmp.b) * (1/(1+tmp.a))\n\n one = (1-data$Del)*(digamma(a+b)-digamma(a) + data$A)\n two = (1-data$Del)*(digamma(a+b)-digamma(b) + data$B)\n\n return( -c( colSums( (one*a.a + two*b.a) * data$Xa ), colSums( (one*a.b + two*b.b) * data$Xb ) ) )\n}\n\nBeta.optim.PAR2 <- function(Del, A, B, Xa, Xb, alpha.ini, beta.ini){\n\n Beta.par.ini = c(alpha.ini, beta.ini)\n Beta.data = list(Del=Del, A=A, B=B, Xa=Xa, Xb=Xb)\n\n return( optim(par=Beta.par.ini, fn=Beta.neg.loglik.PAR2, gr=Beta.neg.score.PAR2, data = Beta.data, method=\"BFGS\")$par)\n\n}\n\n", "meta": {"hexsha": "5f9d990a4f1a0660a3bcda0d13cb7cca4ee3c386", "size": 8268, "ext": "r", "lang": "R", "max_stars_repo_path": "R/ZIGDM.r", "max_stars_repo_name": "qunfengdong/BioMarkerClassifier", "max_stars_repo_head_hexsha": "06acc16d28de665119be76c529d7d07ad3ddfcf6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/ZIGDM.r", "max_issues_repo_name": "qunfengdong/BioMarkerClassifier", "max_issues_repo_head_hexsha": "06acc16d28de665119be76c529d7d07ad3ddfcf6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/ZIGDM.r", "max_forks_repo_name": "qunfengdong/BioMarkerClassifier", "max_forks_repo_head_hexsha": "06acc16d28de665119be76c529d7d07ad3ddfcf6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 25.7570093458, "max_line_length": 243, "alphanum_fraction": 0.5798258345, "num_tokens": 2899, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7490872243177517, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.39792215503211925}} {"text": "score <- function(input) {\n var0 <- exp(subroutine0(input))\n var1 <- exp(subroutine1(input))\n var2 <- exp(subroutine2(input))\n var3 <- ((var0) + (var1)) + (var2)\n return(c((var0) / (var3), (var1) / (var3), (var2) / (var3)))\n}\nsubroutine0 <- function(input) {\n return(((0.5) + (subroutine3(input))) + (subroutine4(input)))\n}\nsubroutine1 <- function(input) {\n return(((0.5) + (subroutine5(input))) + (subroutine6(input)))\n}\nsubroutine2 <- function(input) {\n return(((0.5) + (subroutine7(input))) + (subroutine8(input)))\n}\nsubroutine3 <- function(input) {\n if ((input[3]) >= (2.45000005)) {\n var0 <- -0.0733167157\n } else {\n var0 <- 0.143414631\n }\n return(var0)\n}\nsubroutine4 <- function(input) {\n if ((input[3]) >= (2.45000005)) {\n var0 <- -0.0706516728\n } else {\n var0 <- 0.125176534\n }\n return(var0)\n}\nsubroutine5 <- function(input) {\n if ((input[3]) >= (2.45000005)) {\n if ((input[4]) >= (1.75)) {\n var0 <- -0.0668393895\n } else {\n var0 <- 0.123041473\n }\n } else {\n var0 <- -0.0717073306\n }\n return(var0)\n}\nsubroutine6 <- function(input) {\n if ((input[3]) >= (2.45000005)) {\n if ((input[4]) >= (1.75)) {\n var0 <- -0.0642274022\n } else {\n var0 <- 0.10819874\n }\n } else {\n var0 <- -0.069036141\n }\n return(var0)\n}\nsubroutine7 <- function(input) {\n if ((input[4]) >= (1.6500001)) {\n var0 <- 0.13432835\n } else {\n if ((input[3]) >= (4.94999981)) {\n var0 <- 0.0724137947\n } else {\n var0 <- -0.0732467622\n }\n }\n return(var0)\n}\nsubroutine8 <- function(input) {\n if ((input[4]) >= (1.6500001)) {\n var0 <- 0.117797568\n } else {\n if ((input[3]) >= (4.94999981)) {\n var0 <- 0.0702545047\n } else {\n var0 <- -0.0706570372\n }\n }\n return(var0)\n}\n", "meta": {"hexsha": "c512fd8a8caa9fca6b435f97a958de4f252cf1e7", "size": 1955, "ext": "r", "lang": "R", "max_stars_repo_path": "generated_code_examples/r/classification/xgboost.r", "max_stars_repo_name": "yarix/m2cgen", "max_stars_repo_head_hexsha": "f1aa01e4c70a6d1a8893e27bfbe3c36fcb1e8546", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-05-28T06:59:21.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-28T06:59:21.000Z", "max_issues_repo_path": "generated_code_examples/r/classification/xgboost.r", "max_issues_repo_name": "yarix/m2cgen", "max_issues_repo_head_hexsha": "f1aa01e4c70a6d1a8893e27bfbe3c36fcb1e8546", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "generated_code_examples/r/classification/xgboost.r", "max_forks_repo_name": "yarix/m2cgen", "max_forks_repo_head_hexsha": "f1aa01e4c70a6d1a8893e27bfbe3c36fcb1e8546", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 24.1358024691, "max_line_length": 65, "alphanum_fraction": 0.4895140665, "num_tokens": 660, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7025300573952052, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.39764503401806717}} {"text": "#Title: Estimate fitting decay curve\r\n#Auther: Naoto Imamachi\r\n#ver: 1.0.0\r\n#Date: 2015-10-08\r\n\r\n###Estimate_normalization_factor_function###\r\nBridgeRHalfLifeCalcModel3 <- function(filename = \"BridgeR_4_Normalized_expression_dataset.txt\", group, hour, InforColumn = 4, CutoffRelExp = 0.1, CutoffDataPoint = 3, OutputFile = \"BridgeR_5B_HalfLife_calculation_3model.txt\"){\r\n ###Prepare_file_infor###\r\n time_points <- length(hour)\r\n group_number <- length(group)\r\n input_file <- fread(filename, header=T)\r\n output_file <- OutputFile\r\n \r\n ###print_header###\r\n cat(\"\",file=output_file)\r\n hour_label <- NULL\r\n for(a in 1:group_number){\r\n if(!is.null(hour_label)){\r\n cat(\"\\t\", file=output_file, append=T)\r\n }\r\n hour_label <- NULL\r\n for(x in hour){\r\n hour_label <- append(hour_label, paste(\"T\", x, \"_\", a, sep=\"\"))\r\n }\r\n infor_st <- 1 + (a - 1)*(time_points + InforColumn)\r\n infor_ed <- (InforColumn)*a + (a - 1)*time_points\r\n infor <- colnames(input_file)[infor_st:infor_ed]\r\n cat(infor,hour_label, sep=\"\\t\", file=output_file, append=T)\r\n cat(\"\\t\", sep=\"\", file=output_file, append=T)\r\n cat(\"status\",\"model1\",\"cor1\",\"a_1\",\"half1_1\",\"half1_2\",\"AIC1\",\"model2\",\"cor2\",\"a_2\",\"b_2\",\"half2\",\r\n \"AIC2\",\"model3\",\"cor3\",\"a_3\",\"b_3\",\"c_3\",\"half3\",\"AIC3\",\"selected_model\",\"Selected_R2\",\"Selected_HalfLife\",sep=\"\\t\",file=output_file, append=T)\r\n }\r\n cat(\"\\n\", sep=\"\", file=output_file, append=T)\r\n \r\n ###calc_RNA_half_lives###\r\n gene_number <- length(input_file[[1]])\r\n for(x in 1:gene_number){\r\n data <- as.vector(as.matrix(input_file[x,]))\r\n for(a in 1:group_number){\r\n if(a != 1){\r\n cat(\"\\t\", sep=\"\", file=output_file, append=T)\r\n }\r\n infor_st <- 1 + (a - 1)*(time_points + InforColumn)\r\n infor_ed <- (InforColumn)*a + (a - 1)*time_points\r\n exp_st <- infor_ed + 1\r\n exp_ed <- infor_ed + time_points\r\n \r\n #Write_gene_infor\r\n gene_infor <- data[infor_st:infor_ed]\r\n cat(gene_infor, sep=\"\\t\", file=output_file, append=T)\r\n cat(\"\\t\", file=output_file, append=T)\r\n \r\n #Write_time_point_data\r\n exp <- as.numeric(data[exp_st:exp_ed])\r\n cat(exp, sep=\"\\t\", file=output_file, append=T)\r\n cat(\"\\t\", file=output_file, append=T)\r\n \r\n #make_hour-exp_dataframe\r\n time_point_exp <- data.frame(hour,exp)\r\n time_point_exp <- time_point_exp[time_point_exp$exp >= CutoffRelExp, ]\r\n data_point <- length(time_point_exp$exp)\r\n \r\n if(!is.null(time_point_exp)){\r\n if(data_point >= CutoffDataPoint){\r\n cat(\"ok\",\"\\t\",sep=\"\",file=output_file,append=T)\r\n \r\n ###Model1: f(t) = exp(-a * t)###\r\n optim1 <- function(x){\r\n mRNA_exp <- exp(-x * time_point_exp$hour)\r\n sum((time_point_exp$exp - mRNA_exp)^2)\r\n }\r\n \r\n out1 <- optim(1,optim1)\r\n min1 <- out1$value\r\n a_1 <- out1$par[1]\r\n half1_1 <- log(2) / a_1\r\n \r\n model1_pred <- function(x){\r\n mRNA_exp <- exp(-x * time_point_exp$hour)\r\n (cor(mRNA_exp, time_point_exp$exp, method=\"pearson\"))^2\r\n }\r\n \r\n cor1 <- model1_pred(a_1)\r\n \r\n model1_half <- function(x){\r\n mRNA_half <- exp(-a_1 * x)\r\n (mRNA_half - 0.5)^2\r\n }\r\n \r\n out1 <- optim(1,model1_half)\r\n half1_2 <- out1$par\r\n mRNA_pred <- exp(-a_1 * time_point_exp$hour)\r\n s2 <- sum((time_point_exp$exp - mRNA_pred)^2) / data_point\r\n AIC1 <- data_point * log(s2) + (2 * 0)\r\n \r\n cat(min1,cor1,a_1,half1_1,half1_2,AIC1,sep=\"\\t\",file=output_file,append=T)\r\n cat(\"\\t\",file=output_file,append=T)\r\n ############################################\r\n \r\n ###Model2: f(t) = (1 - b)exp(-a * t) + b###\r\n optim2 <- function(x){\r\n mRNA_exp <- (1.0 - x[2]) * exp(-x[1] * time_point_exp$hour) + x[2]\r\n sum((time_point_exp$exp - mRNA_exp)^2)\r\n }\r\n \r\n out2 <- optim(c(1,0),optim2)\r\n min2 <- out2$value\r\n a_2 <- out2$par[1]\r\n b_2 <- out2$par[2]\r\n \r\n model2_pred <- function(a,b){\r\n mRNA_exp <- (1.0 - b) * exp(-a * time_point_exp$hour) + b\r\n (cor(mRNA_exp, time_point_exp$exp, method=\"pearson\"))^2\r\n }\r\n \r\n cor2 <- model2_pred(a_2, b_2)\r\n \r\n model2_half <- function(x){\r\n mRNA_half <- (1.0 - b_2) * exp(-a_2 * x) + b_2\r\n (mRNA_half - 0.5)^2\r\n }\r\n \r\n out2 <- optim(1,model2_half)\r\n half2 <- out2$par\r\n \r\n if(b_2 >= 0.5){\r\n half2 <- Inf\r\n }\r\n \r\n mRNA_pred <- (1.0 - b_2) * exp(-a_2 * time_point_exp$hour) + b_2\r\n s2 <- sum((time_point_exp$exp - mRNA_pred)^2) / data_point\r\n AIC2 <- data_point * log(s2) + (2 * 1)\r\n \r\n cat(min2,cor2,a_2,b_2,half2,AIC2,sep=\"\\t\",file=output_file,append=T)\r\n cat(\"\\t\",file=output_file,append=T)\r\n ############################################################\r\n \r\n ###Model3: f(t) = c * exp(-a * t) + (1 - c) * exp(-b * t)###\r\n optim3 <- function(x){\r\n mRNA_exp <- x[3] * exp(-x[1] * time_point_exp$hour) + (1.0 - x[3]) * exp(-x[2] * time_point_exp$hour)\r\n sum((time_point_exp$exp - mRNA_exp)^2)\r\n }\r\n \r\n out3 <- optim(c(1,1,0.1),optim3)\r\n min3 <- out3$value\r\n a_3 <- out3$par[1]\r\n b_3 <- out3$par[2]\r\n c_3 <- out3$par[3]\r\n \r\n model3_pred <- function(a,b,c){\r\n mRNA_exp <- c * exp(-a * time_point_exp$hour) + (1.0 - c) * exp(- b * time_point_exp$hour)\r\n (cor(mRNA_exp, time_point_exp$exp, method=\"pearson\"))^2\r\n }\r\n \r\n cor3 <- model3_pred(a_3,b_3,c_3)\r\n \r\n model3_half <- function(x){\r\n mRNA_half <- c_3 * exp(-a_3 * x) + (1.0 - c_3) * exp(-b_3 * x)\r\n (mRNA_half - 0.5)^2\r\n }\r\n \r\n out3 <- optim(1,model3_half)\r\n half3 <- out3$par\r\n mRNA_pred <- c_3 * exp(-a_3 * time_point_exp$hour) + (1.0 - c_3) * exp(-b_3 * time_point_exp$hour)\r\n s2 <- sum((time_point_exp$exp - mRNA_pred)^2) / data_point\r\n AIC3 <- data_point * log(s2) + (2 * 2)\r\n \r\n cat(min3,cor3,a_3,b_3,c_3,half3,AIC3,sep=\"\\t\",file=output_file,append=T)\r\n cat(\"\\t\",file=output_file,append=T)\r\n ############################################################\r\n \r\n half_table <- data.frame(half=c(as.numeric(half1_2),as.numeric(half2),as.numeric(half3)),AIC=c(as.numeric(AIC1),as.numeric(AIC2),as.numeric(AIC3)))\r\n AIC_list <- order(half_table$AIC)\r\n #selected_half <- half_table$half[min_AIC_index]\r\n \r\n AIC_flg <- 0\r\n for(min_AIC_index in AIC_list){\r\n ###Model1###\r\n if(min_AIC_index == 1){\r\n selected_half <- half1_2\r\n if(selected_half > 24){\r\n selected_half <- 24\r\n }\r\n if(a_1 > 0){\r\n cat(\"model1\",cor1,selected_half,sep=\"\\t\",file=output_file,append=T)\r\n AIC_flg <- 1\r\n break\r\n }\r\n }\r\n ###Model2###\r\n if(min_AIC_index == 2){\r\n selected_half <- half2\r\n if(selected_half == \"Inf\"){\r\n selected_half <- 24\r\n }else if(selected_half > 24){\r\n selected_half <- 24\r\n }\r\n if(a_2 > 0 && b_2 > 0 && b_2 < 1){\r\n cat(\"model2\",cor2,selected_half,sep=\"\\t\",file=output_file,append=T)\r\n AIC_flg <- 1\r\n break\r\n }\r\n }\r\n ###Model3###\r\n if(min_AIC_index == 3){\r\n selected_half <- half3\r\n if(selected_half > 24){\r\n selected_half <- 24\r\n }\r\n if(a_3 > 0 && b_3 > 0 && c_3 > 0 && c_3 < 1){\r\n cat(\"model3\",cor3,selected_half,sep=\"\\t\",file=output_file,append=T)\r\n AIC_flg <- 1\r\n break\r\n }\r\n }\r\n }\r\n \r\n if(AIC_flg == 0){\r\n if(a_1 < 0){\r\n cat(\"model1\",cor1,24,sep=\"\\t\",file=output_file,append=T)\r\n next\r\n }else{\r\n cat(\"no_good_model\",\"NA\",24,sep=\"\\t\",file=output_file,append=T)\r\n next\r\n }\r\n }\r\n\r\n }else{\r\n cat(\"few_data\",\"NA\",\"NA\",\"NA\",\"NA\",\"NA\",\"NA\",\"NA\",\"NA\",\"NA\",\"NA\",\"NA\",\r\n \"NA\",\"NA\",\"NA\",\"NA\",\"NA\",\"NA\",\"NA\",\"NA\",\"NA\",\"NA\",\"NA\", sep=\"\\t\", file=output_file, append=T)\r\n }\r\n }else{\r\n cat(\"low_expresion\",\"NA\",\"NA\",\"NA\",\"NA\",\"NA\",\"NA\",\"NA\",\"NA\",\"NA\",\"NA\",\"NA\",\r\n \"NA\",\"NA\",\"NA\",\"NA\",\"NA\",\"NA\",\"NA\",\"NA\",\"NA\",\"NA\",\"NA\", sep=\"\\t\", file=output_file, append=T)\r\n }\r\n }\r\n cat(\"\\n\", file=output_file, append=T)\r\n }\r\n}\r\n\r\n", "meta": {"hexsha": "7117b970991175da16a150e9e6ca2d32d14d9ce8", "size": 11312, "ext": "r", "lang": "R", "max_stars_repo_path": "R/X5_estimate_fitting_decay_curve_3model.r", "max_stars_repo_name": "ChristophRau/BridgeR", "max_stars_repo_head_hexsha": "d4d68826bc2fc210b409ff3345047def4fd7ede0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-04-10T15:03:45.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-10T15:03:45.000Z", "max_issues_repo_path": "R/X5_estimate_fitting_decay_curve_3model.r", "max_issues_repo_name": "ChristophRau/BridgeR", "max_issues_repo_head_hexsha": "d4d68826bc2fc210b409ff3345047def4fd7ede0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/X5_estimate_fitting_decay_curve_3model.r", "max_forks_repo_name": "ChristophRau/BridgeR", "max_forks_repo_head_hexsha": "d4d68826bc2fc210b409ff3345047def4fd7ede0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-03-11T14:15:15.000Z", "max_forks_repo_forks_event_max_datetime": "2021-03-11T14:15:15.000Z", "avg_line_length": 46.9377593361, "max_line_length": 227, "alphanum_fraction": 0.3851661952, "num_tokens": 2639, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581626286834, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.39731588064982337}} {"text": "pp.fit2 <- function (xdat, threshold, npy = 365, ydat = NULL, mul = NULL, sigl = NULL, shl = NULL, mulink = identity, siglink = identity, shlink = identity, muinit = NULL, siginit = NULL, shinit = NULL, show = TRUE, method = \"Nelder-Mead\", maxit = 10000, ndeps = 1e-3, exceedancesOnly = TRUE, nBlocks = NULL, propMissingByBlock = 0, ydatByBlock = NULL, thresholdByBlock = NULL, ...) \n{\n # modification of pp.fit() from ismev by C. Paciorek\n # differences from pp.fit()\n # (1) modifies default initial values to be calculated only using exceedances, and modifies initial values for log link\n # (2) allows NA in data, adjusting intensity function calculation in likelihood to account for missing values\n # (3) allows user to provide only the exceedances for computational efficiency; in this case, for nonstationary models, the covariates must not vary within block (e.g., year) as the likelihood needs to calculate the intensity measure appropriate for every timepoint at which an observation is possible. The covariate values, proportion of missing values, and threshold for each block must be supplied when these are relevant\n # (4) returns data values and location, scale and shape values only for the exceedances\n # (5) adds 'flag' output that indicates if MLE or standard errors may not be legitimate\n # (6) allows one to change the default step size of the finite difference approximation to the gradient in the optimization\n\n # Note that this function operates in two fashions. First (exceedancesOnly = FALSE) it replicates pp.fit() but allows for missing data. In this case the data, threshold values, and covariates supplied should be given for every timepoint. Missing values are not allowed in the covariates or the threshold values as these are need for calculation of the intensity function in the likelihood. In this case, information about the blocks is ignored. Second (exceedancesOnly = TRUE), it allows one to improve computational efficiency by providing only the exceedances. In this case, the user is required to provide nBlocks and should provide propMissingByBlock, ydatByBlock, and thresholdByBlock as appropriate. When only exceedances are supplied there should be no missing values in xdat.\n\n # for strict accuracy, one should specify npy to be equal to the total number of observation units in the number of blocks to be considered for analysis divided by the number of blocks; e.g., the total number of days in the years of the analysis divided by the number of years; note that blocks in general should be equal size for the parameter estimates and return values to be meaningful across multiple blocks, but slight deviations from, e.g., leap years should have limited effects\n\n # probably want to have sc and threshold checks for all timepoints not just exceedances, unlike in pp.fit(); for now I'm keeping the checks just for the exceedances, as in pp.fit()\n \n # note possible errors in pp.fit checking of legitimacy of parameters in terms of obs/thresholds not outside domain of distribution\n \n # add upper.tail? no, probably not; but if so give msg that says: provide me the maxima of negative data and that this will handle the results correctly?\n \n z <- list()\n npmu <- length(mul) + 1\n npsc <- length(sigl) + 1\n npsh <- length(shl) + 1\n\n z$trans <- FALSE \n if (is.function(threshold)) \n stop(\"`threshold' cannot be a function\")\n \n covars = FALSE\n if(!is.null(mul) || !is.null(sigl) || !is.null(shl))\n covars = TRUE # \n\n if(covars || length(threshold) > 1)\n z$trans <- TRUE # nonstationary model\n \n if(exceedancesOnly & is.null(nBlocks))\n stop(\"number of blocks (e.g., years) (nBlocks) is required for calculation of the likelihood when only exceedances are supplied\")\n\n if(exceedancesOnly){ # check that nBlocks matches dimensionality of byBlock objects\n nBlocksError = FALSE\n if(length(propMissingByBlock) > 1 && length(propMissingByBlock) != nBlocks)\n nBlocksError = TRUE\n if(!is.null(ydatByBlock) && nrow(ydatByBlock) != nBlocks)\n nBlocksError = TRUE\n if(!is.null(thresholdByBlock) && length(thresholdByBlock) != nBlocks)\n nBlocksError = TRUE\n if(nBlocksError)\n stop(\"number of blocks indicated by nBlocks and one of {propMissingByBlock, ydatByBlock, thresholdByBlock} are in conflict\")\n }\n\n if(exceedancesOnly && covars && is.null(ydatByBlock))\n stop(\"nonstationary modeling when providing only exceedances requires ydatByBlock to calculate the intensity function portion of the likelihood\")\n \n if(exceedancesOnly && is.null(thresholdByBlock)){\n if(length(threshold) > 1){\n stop(\"require thresholdByBlock when threshold varies and only exceedances are supplied\")\n } else{\n thresholdByBlock <- rep(threshold, nBlocks)\n }\n }\n\n if(exceedancesOnly && length(propMissingByBlock) == 1)\n propMissingByBlock = rep(propMissingByBlock, nBlocks)\n \n n <- length(xdat)\n if(exceedancesOnly){\n ny <- nBlocks # code below uses 'ny' since this is used in original pp.fit\n # nyEff <- sum(1-propMissingByBlock)\n } else{\n ny <- n/npy\n nyEff <- sum(!is.na(xdat))/npy\n }\n\n if(n == 1)\n stop(\"fitting will not be done correctly with a single observation or single exceedance\")\n\n u <- threshold\n if(length(threshold) == 1)\n u <- rep(threshold, n)\n if(length(u) > 1 & length(u) != n)\n stop(\"number of threshold values should match number of observations, unless threshold does not vary\")\n\n uInd <- !is.na(xdat) & xdat > u # indicator of exceedances\n xdatu <- xdat[uInd] \n u[is.na(xdat)] = NA # sets things up so that intensity is not calculated when data are missing\n nu <- length(xdatu)\n in2 <- sqrt(6 * var(xdatu))/pi # modified from pp.fit to make use only of exceedances\n in1 <- mean(xdatu) - 0.57722 * in2 # modified from pp.fit to make use only of exceedances\n\n if(identical(mulink, exp))\n in1 = log(in1)\n if(!identical(mulink, exp) && !identical(mulink, identity))\n warning(\"Default initial value for location is on incorrect scale; please supply your own.\")\n if(identical(siglink, exp))\n in2 = log(in2)\n if(!identical(siglink, exp) && !identical(siglink, identity))\n warning(\"Default initial value for scale is on incorrect scale; please supply your own.\")\n shinit.default = 0.1\n if(identical(shlink, exp))\n shinit.default = log(shinit.default)\n if(!identical(shlink, exp) && !identical(shlink, identity))\n warning(\"Default initial value for shape is on incorrect scale; please supply your own.\")\n\n if(is.null(mul)) {\n mumat <- as.matrix(rep(1, n))\n if(is.null(muinit)) \n muinit <- in1\n mumatByBlock <- matrix(rep(1, ny), nc = 1)\n } else {\n mumat <- cbind(rep(1, n), ydat[ , mul])\n mumatByBlock <- cbind(rep(1, ny), ydatByBlock[, mul])\n if(is.null(muinit)) \n muinit <- c(in1, rep(0, length(mul)))\n }\n if(is.null(sigl)) {\n sigmat <- as.matrix(rep(1, n))\n if(is.null(siginit)) \n siginit <- in2\n sigmatByBlock <- matrix(rep(1, ny), nc = 1)\n } else {\n sigmat <- cbind(rep(1, n), ydat[ , sigl])\n sigmatByBlock <- cbind(rep(1, ny), ydatByBlock[, sigl])\n if(is.null(siginit)) \n siginit <- c(in2, rep(0, length(sigl)))\n }\n if(is.null(shl)) {\n shmat <- as.matrix(rep(1, n))\n if(is.null(shinit)) \n shinit <- shinit.default\n shmatByBlock <- matrix(rep(1, ny), nc = 1)\n } else {\n shmat <- cbind(rep(1, n), ydat[ , shl])\n shmatByBlock <- cbind(rep(1, ny), ydatByBlock[, shl])\n if(is.null(shinit)) \n shinit <- c(shinit.default, rep(0, length(shl)))\n }\n init <- c(muinit, siginit, shinit)\n z$model <- list(mul, sigl, shl)\n z$link <- deparse(substitute(c(mulink, siglink, shlink)))\n z$threshold <- threshold\n z$npy <- npy\n z$nexc <- nu\n z$data <- xdatu\n\n pp.lik <- function(a) {\n mu <- c(mulink(mumat %*% (a[1:npmu])))\n sc <- c(siglink(sigmat %*% (a[seq(npmu + 1, length = npsc)])))\n xi <- c(shlink(shmat %*% (a[seq(npmu + npsc + 1, length = npsh)])))\n if(exceedancesOnly){ # calculate parameters for each block for use in intensity function in likelihood\n muByBlock <- c(mulink(mumatByBlock %*% (a[1:npmu])))\n scByBlock <- c(siglink(sigmatByBlock %*% (a[seq(npmu + 1, length = npsc)])))\n xiByBlock <- c(shlink(shmatByBlock %*% (a[seq(npmu + npsc + 1, length = npsh)])))\n }\n\n # basic logic of the checks below is that the quantities that are exponentiated in (7.9) of Coles (p. 134) should be positive - i.e., for all exceedances and for all threshold values for all timepoints\n \n if(min(sc[uInd]) <= 0 || (exceedancesOnly && min(scByBlock) <= 0)) \n return(10^6) # note that pp.fit() only checks min(sc[uInd]) <=0, but presumably the scale should be positive for all potential observations\n \n # check that thresholds do not exceed the bounds of the distribution; pp.fit() does this only for the threshold values corresponding to the exceedances, but it's not clear why this shouldn't be checked for all timepoints\n if (min((1 + xi * (u - mu)/sc)[uInd]) <= 0) \n return(10^6)\n if(exceedancesOnly && min(1 + (xiByBlock * (thresholdByBlock - muByBlock))/scByBlock) <= 0)\n return(10^6)\n \n y <- (xdatu - mu[uInd])/sc[uInd]\n y <- 1 + xi[uInd] * y\n if(min(y) <= 0){ # check that exceedances do not exceed the bounds of the distribution; note that pp.fit() checks all observations, even those below the threshold, for reasons that are unclear\n l <- 10^6;\n } else{\n l <- sum(log(sc[uInd])) + sum(log(y) * (1/xi[uInd] + 1)) # PP density of the exceedances\n if(exceedancesOnly){ # calculate intensity function for all timepoints; using sum gives parameter estimates that correspond to GEV modeling of single block extrema (this is equivalent to multiplying by ny as in Coles (2001, p. 133) but ignoring the intensity values corresponding to the missing values)\n l <- l + sum( (1 - propMissingByBlock) * (1 + (xiByBlock * (thresholdByBlock - muByBlock))/scByBlock)^(-1/xiByBlock))\n } else{\n l <- l + nyEff * mean((1 + (xi * (u - mu))/sc)^(-1/xi), na.rm = TRUE) # need scaled mean if per-time-point intensity so that parameters correspond GEV modeling of single block extrema\n }\n }\n return(l)\n }\n x <- optim(init, pp.lik, hessian = TRUE, method = method, \n control = list(maxit = maxit, ndeps = rep(ndeps, length = length(init)), ...))\n # calculate parameters only for the exceedances, unlike pp.fit()\n mu <- mulink(c(mumat[uInd, , drop = FALSE] %*% (x$par[1:npmu])))\n sc <- siglink(c(sigmat[uInd, , drop = FALSE] %*% (x$par[seq(npmu + 1, length = npsc)])))\n xi <- shlink(c(shmat[uInd, , drop = FALSE] %*% (x$par[seq(npmu + npsc + 1, length = npsh)])))\n z$conv <- x$convergence\n z$nllh <- x$value\n z$vals <- cbind(mu, sc, xi, u[uInd])\n z$gpd <- apply(z$vals, 1, ppp, npy) \n if(z$trans) {\n z$data <- as.vector((1 + (xi * (xdatu - u[uInd]))/z$gpd[2, ])^(-1/xi))\n }\n z$mle <- x$par\n z$cov <- solve(x$hessian)\n z$se <- sqrt(diag(z$cov))\n if(show) {\n if(z$trans) \n print(z[c(2, 3)])\n if(length(z[[4]]) == 1) \n print(z[4])\n print(z[c(5, 6, 8)])\n if(!z$conv) \n print(z[c(9, 12, 14)])\n }\n z$flag = 0\n if(sum(is.na(c(z$mle, z$se))) || min(xi) < -1 || min(z$se) < 1e-5){\n z$flag = 1\n warning(\"MLEs and standard errors may not be reliable; please check convergence, estimates, standard errors, and input data.\")\n }\n class(z) <- \"pp.fit\"\n invisible(z)\n}\n", "meta": {"hexsha": "ebb94b0e7fcccc9c0a726436af755a7a919b0f26", "size": 11413, "ext": "r", "lang": "R", "max_stars_repo_path": "operators/PeaksOverThreshold/r_src/pp.fit2.r", "max_stars_repo_name": "ahota/visit_ospray", "max_stars_repo_head_hexsha": "d80b2e18ff5654d04bfb56ae4d6f42e45f87c9b9", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "operators/PeaksOverThreshold/r_src/pp.fit2.r", "max_issues_repo_name": "ahota/visit_ospray", "max_issues_repo_head_hexsha": "d80b2e18ff5654d04bfb56ae4d6f42e45f87c9b9", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "operators/PeaksOverThreshold/r_src/pp.fit2.r", "max_forks_repo_name": "ahota/visit_ospray", "max_forks_repo_head_hexsha": "d80b2e18ff5654d04bfb56ae4d6f42e45f87c9b9", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 53.0837209302, "max_line_length": 788, "alphanum_fraction": 0.6758082888, "num_tokens": 3303, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.8006920020959544, "lm_q2_score": 0.49609382947091946, "lm_q1q2_score": 0.39721836154651946}} {"text": "# Function for generating NOEC distributions for each species taking into account trophic levels\r\n# \r\n# Yields a matrix with dimensions number of species * number of iterations in the simulation\r\n# \r\n# Arguments: - DP : matrix of endpoints\r\n# - UFt : matrix of uncertainty factors for the exposure time\r\n# - UFdd : matrix of uncertainty factors for the dose-descriptor\r\n# - SIM : number of iterations in the simulation\r\n# - CV.DP : coefficient of variation for the interlaboratory variation\r\n# - CV.UF : coefficient of variation for the use of non-substance-specific\r\n# uncertainty factors \r\n# - TrophLevel : Trophic levels of each species. 1 for primary producers, 2 for herbivores and 3 for carnivores\r\n# - Troph.Perc.Typ : Typical fractions in which each trophic level is represented in freshwater communities. \r\n# \r\n# Date of last modification: 03.07.2019\r\n# \r\n# Associated publication: Systematic consideration of parameter uncertainty and variability in\r\n# probabilistic species sensitivity distributions\r\n# \r\n# Authors: Henning Wigger, Delphine Kawecki, Bernd Nowack and Veronique Adam\r\n# \r\n# Institute: Empa, Swiss Federal Laboratories for Materials Science and Technology,\r\n# Technology and Society Laboratory, Lerchenfeldstrasse 5, 9014 St. Gallen, Switzerland\r\n# \r\n# submitted to Integrated Environmental Assessment and Management in July 2019\r\n\r\n# -------------------------------------------------------------------------------------------------\r\n\r\n\r\n\r\ndo.pSSD.troph <- function(DP,\r\n UFt,\r\n UFdd,\r\n SIM,\r\n CV.DP,\r\n CV.UF,\r\n TrophLevel,\r\n Troph.Perc.Typ = c(0.65, 0.25, 0.1)){\r\n \r\n # test if there is no data available for one species\r\n if(any(apply(DP,2,function(x) length(which(!is.na(x)))) == 0)){\r\n warning(\"No data is available for one or more species, it/they won't contribute to the PSSD calculation.\")\r\n # find which species has no data\r\n ind.sp.rem <- which(apply(DP, 2, function(x) length(which(!is.na(x)))) == 0)\r\n # remove those columns\r\n DP <- DP[,-ind.sp.rem]\r\n UFt <- UFt[,-ind.sp.rem]\r\n UFdd <- UFdd[,-ind.sp.rem]\r\n }\r\n \r\n # Create the step distributions (or triangular or trapezoidal) for each species\r\n # Create an empty matrix in which step distributions will be compiled\r\n NOEC_comb <- matrix(NA, ncol(DP), SIM,\r\n dimnames = list(colnames(DP), NULL))\r\n \r\n # Fill in the matrix. If there is only one data point, NOEC stays the same. If there are\r\n # 2 endpoints, a uniform distribution is produced. If there are more than 2 endpoints, a step\r\n # distribution is produced. One line is for one species.\r\n require(trapezoid)\r\n require(mc2d)\r\n \r\n # store the corrected endpoints\r\n corr.endpoints <- DP/(UFdd*UFt)\r\n sort.endpoints <- apply(corr.endpoints, 2, sort)\r\n \r\n for (sp in colnames(DP)){\r\n \r\n # store the indices of the minimal and maximal data point\r\n ind.min <- which.min(corr.endpoints[,sp])\r\n ind.max <- which.max(corr.endpoints[,sp])\r\n \r\n # calculate the theoretical minimum and maximum of the distribution we are looking for\r\n sp.min <- corr.endpoints[ind.min,sp]*(1-(sqrt((CV.DP/2.45)^2 + (CV.UF/2.45)^2 + (CV.UF/2.45)^2)*2.45))\r\n sp.max <- corr.endpoints[ind.max,sp]*(1+(sqrt((CV.DP/2.45)^2 + (CV.UF/2.45)^2 + (CV.UF/2.45)^2)*2.45))\r\n \r\n # For species with one unique data point, NOEC stays the same:\r\n if(length(unique(sort.endpoints[[sp]])) == 1){\r\n NOEC_comb[sp,] <- rtrunc(\"rtriang\", min = sp.min, \r\n mode = sort.endpoints[[sp]][1],\r\n max = sp.max,\r\n n = SIM, linf = 0)\r\n \r\n \r\n # For species with two endpoints:\r\n } else if(length(sort.endpoints[[sp]]) == 2){\r\n # Create a trapezoidal distribution including both endpoints\r\n NOEC_comb[sp,] <- rtrunc(\"rtrapezoid\", SIM,\r\n mode1 = sort.endpoints[[sp]][1],\r\n mode2 = sort.endpoints[[sp]][2],\r\n min = sp.min, max = sp.max,\r\n linf = 0)\r\n \r\n \r\n # For species with three endpoints or more:\r\n } else {\r\n \r\n \r\n # Sample from this step distribution for each species\r\n NOEC_comb[sp,] <- rmore(values = sort.endpoints[[sp]], max = sp.max, min = sp.min, N = SIM, linf = 0)\r\n \r\n } \r\n }\r\n \r\n # Sample species with typical proportions representative of a typical community (if terrestrial or marine, Troph.Perc need to be changed)\r\n Nb_Troph <- c(length(which(TrophLevel == 1)),\r\n length(which(TrophLevel == 2)),\r\n length(which(TrophLevel == 3)))\r\n # calculate the shares of the different trophic levels in the data\r\n Troph.Perc.Data <- Nb_Troph/ncol(DP)\r\n \r\n \r\n # identify the trophic level that will be unchanged\r\n if(length(which(Troph.Perc.Data < Troph.Perc.Typ)) == 1){\r\n lev.fix <- which(Troph.Perc.Data < Troph.Perc.Typ)\r\n } else {\r\n lev.fix <- which.max((Troph.Perc.Typ - Troph.Perc.Data)/Troph.Perc.Typ)\r\n }\r\n \r\n # create an empty vector to contain the corrected number of species for the species being corrected\r\n Nb_points <- rep(NA,3)\r\n # create an empty list with an element per trophic level\r\n NOEC_lev <- vector(\"list\", 3)\r\n \r\n for(lev in 1:3){\r\n \r\n # for fix level, take as such\r\n if(lev == lev.fix){\r\n Nb_points[lev] <- Nb_Troph[lev.fix]\r\n \r\n # identify species corresponding to level lev\r\n ind.sp <- which(TrophLevel == lev) # vector of all indices for which the species level is the fixed one\r\n # store in list\r\n NOEC_lev[[lev]] <- NOEC_comb[ind.sp,]\r\n \r\n } else {\r\n \r\n # change the remaining levels\r\n Nb_points[lev] <- round(Nb_Troph[lev.fix] * Troph.Perc.Typ[lev] / Troph.Perc.Data[lev.fix]) # Nouveau nombre de lignes\r\n \r\n ind.sp <- which(TrophLevel == lev) # vector of all indices of the level\r\n # store in temporary matrix the NOEC distributions of all species of the level\r\n temp <- NOEC_comb[ind.sp,] \r\n \r\n NOEC_lev[[lev]] <- matrix(NA, Nb_points[lev],SIM)\r\n for(i in 1:SIM){\r\n NOEC_lev[[lev]][,i] <- sample(temp[,i], Nb_points[lev])\r\n }\r\n }\r\n \r\n }\r\n \r\n # combine that stuff\r\n NOEC_TrophCorr <- do.call(rbind,NOEC_lev)\r\n \r\n # return the whole matrix\r\n return(NOEC_TrophCorr)\r\n \r\n}\r\n", "meta": {"hexsha": "61c84da057cedb9f1d1475fe6b075b59bd26c084", "size": 6670, "ext": "r", "lang": "R", "max_stars_repo_path": "do.pssd.troph.r", "max_stars_repo_name": "empa-tsl/PSSDplus", "max_stars_repo_head_hexsha": "c212b2c22195f5325312be64d62a7bbdb427b674", "max_stars_repo_licenses": ["AAL"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-01-14T08:39:42.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-06T13:09:08.000Z", "max_issues_repo_path": "do.pssd.troph.r", "max_issues_repo_name": "empa-tsl/PSSDplus", "max_issues_repo_head_hexsha": "c212b2c22195f5325312be64d62a7bbdb427b674", "max_issues_repo_licenses": ["AAL"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "do.pssd.troph.r", "max_forks_repo_name": "empa-tsl/PSSDplus", "max_forks_repo_head_hexsha": "c212b2c22195f5325312be64d62a7bbdb427b674", "max_forks_repo_licenses": ["AAL"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-12-11T03:49:49.000Z", "max_forks_repo_forks_event_max_datetime": "2021-12-11T03:49:49.000Z", "avg_line_length": 41.9496855346, "max_line_length": 140, "alphanum_fraction": 0.5872563718, "num_tokens": 1688, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8128673269042767, "lm_q2_score": 0.48828339529583464, "lm_q1q2_score": 0.39690961830586935}} {"text": "#!/usr/bin/Rscript\n# version 20130821\n\narg <- commandArgs(trailingOnly=TRUE)\n\n\nmcmc_BiSSE <- function(\n\tinfile1, # tree\n\tinfile2, # trait table\n\twd=\"default\",\n\tTDI=0,\n\tout_file_stem=\"default\",\n\trho0=1,\n\trho1=1,\n\tBD_model_0=1,\n\tBD_model_1=1,\n\tTrait_model=0,\n\tlink_speciation=0,\n\tlink_extinction=0,\n\tlink_trait=0,\n\tprior_r=5,\n\tprior_a=1,\n\tprior_b=1,\n\tprior_q=1,\n\ttrees=1,\n\tIT=20000,\n\tsampling_freq=100,\n\tprint_freq=100,\n\tburnin=1000,\n\twin_1=0.5,\n\twin_2=0.25,\n\twin_3=0.05,\n\tcategories=10,\n\tbeta_shape=0.3,\n\tpath_lib=\"default\"\n\t) {\t# end args\t\n\t\n\tif (wd==\"default\"){\n\t\twd=dirname(infile1)\n\t\t}else{setwd(wd)}\n\t\n\tif (out_file_stem==\"default\"){\n\t\tst=basename(infile2)\n\t\tout_file= paste(st,\"_BiSSEBMA.log\", sep=\"\")\n\t\t}else{out_file= paste(out_file_stem,\".log\", sep=\"\")}\n\t\t\t\n\tif (path_lib==\"default\") {\n\t\tlibrary(diversitree)\n\t\t}else{library(diversitree, , lib.loc=path_lib)}\n\n\toptions(warn=-1) # hide warnings\n\t\t\n\trhos=c(rho0, rho1) #sampling fractions for state 0 and 1\n\t#out_file=\"boh.log\" #!!change in each analysis\n\t#TDI=0 # 0 parameter estimation, 1 TD integration (not real estimates)\n\t#trees=5 # one tree for TDI is advised\n\n\t#burnin=0 # run test to check the proportion\n\t#sampling_freq=25\n\t#print_freq=10\n\t#IT=200 # mcmc iterations (per tree)\n\t#categories=20\n\t\n\n\tuse_exp=1 # 0: uniform priors; 1: exponential priors (extinction fraction has always uniform prior 0-1)\n\tM=c(5,5,1,1,5,5) # max parameter values (if uniform priors)\n\t# if exp no limit (max =1000)\n\tif (prior_r>0){M[1:2]=1000}\t\n\tif (prior_q>0){M[5:6]=1000}\t\n\t#shape_prior=c(2,2,1,1) # shape parameters of exp prior (net diversification and q rates)\n\t#constraints=c() # constant sp. [2], ex. [4], q. [6] const sp + ex is 2,4\n\t#PB=c() # 3: pb clade 1, 4: pb clade 2, 5: q0->1 =0; 6: q1->0 =0 # pure birth / irreversible rate models\n\n\tPB=NULL\n\tif (BD_model_0==0){PB=append(PB,3)}\n\tif (BD_model_1==0){PB=append(PB,4)}\n\tif (Trait_model==1){PB=append(PB,6)}\n\tif (Trait_model==2){PB=append(PB,5)}\n\n\tconstraints=NULL\n\tif (link_speciation==1){constraints=append(constraints,2)}\n\tif (link_extinction==1){constraints=append(constraints,4)}\n\tif (link_trait==1) {constraints=append(constraints,6)}\n\n\n\tshape_prior=c(prior_r,prior_a,prior_b,prior_q)\n\twin_size=c(win_1,win_1,win_2,win_2,win_3,win_3)\n\t\n\tTree=read.nexus(file=infile1)\n\ttraits=read.csv(file=infile2, header=TRUE, sep=\"\\t\") #one single trait or create a vector\n\tstates<-traits[,2]\n\tnames(states)<-as.character(traits[,1])\n\n\tupdate_parameter <- function(i,d,M) {\n\t\tif (length(i)==1) {\n\t\t\tii=abs(i+(runif(length(i),0,1)-.5)*d)\n\t\t\tif (ii>M) {ii=abs((M-(ii-M)))}\n\t\t\tif (ii>M) {ii=i}\n\t\t\t}\n\t\tii}\n\tif (TDI>0)\t{\n\t\tK=categories-1.\n\t\tk=0:K # K+1 categories\n\t\tbeta=k/K\n\t\talpha=beta_shape # categories are beta distributed\n\t\ttemps=rev(beta^(1./alpha))\n\t} else{temps=c(1)} \n\n\texp_prior = function(value,l,Mv) {\n\t\tif (l>0){\n\t\t\tl=1./l\n\t\t\tlog(l)-l*(value)\n\t\t\t}else{log(1/Mv)}\n\t}\n\n\tbeta_prior = function(a,b,value){\n\t\tdbeta(value, a, b, log = TRUE)\n\t}\n\n\n\ttrue_iteration=1\n\tcat(sprintf(\"it\\tlikelihood\\tprior\\tacceptance\\tl0\\tl1\\tm0\\tm1\\tr0\\tr1\\ta0\\ta1\\tq0\\tq1\\ttemp\\ttree\\n\"), append=FALSE, file=out_file)\n\tcat(sprintf(\"it\\tlikelihood\\tprior\\tacc\\tl0\\tl1\\tm0\\tm1\\ttemp\\ttree\\n\"))\n\tfor (J in 1:length(temps)) { # Loop temperatures\n\t\ttemperature=temps[J]\n\t\td= win_size*(4 - 3*temperature)\n\n\t\tfor (t_index in 1:trees) { # loop trees\n\t\t\t\n\t\t\tif (class(Tree)==\"multiPhylo\"){current_tree=Tree[[J]]}\n\t\t\telse{current_tree=Tree}\n\t\t\t\n\t\t\tBISSE=make.bisse(current_tree, states, strict=F, sampling.f=rhos)\n\t\t\tpars=runif(min=.1,max=.5, 6) # initialize parameters\n\n\t\t\tif (temperature<1) {burnin=0}\n\t\t\tLIK=0 \n\t\t\tacc=0\n\t\t\tfor (iteration in 1:(IT+burnin)) { # MCMC loop\n\t\t\t\tif (iteration==1){ \n\t\t\t\t\tlikA = BISSE(pars)[1]\n\t\t\t\t\tparsA=pars}\n\t\t\t\tpars=parsA\n\t\t\t\tind=sample(1:6,1) \n\t\t\t\tpars[ind]=update_parameter(pars[ind],d[ind],M[ind])\n\t\t\t\tpars[PB]=0\n\t\t\t\tif (length(constraints)>0) {\n\t\t\t\t\tif (is.element(2, constraints) & is.element(4, constraints)) {pars[constraints] = pars[constraints-1]}\n\t\t\t\t\telse if (is.element(2, constraints)) {pars[2]=(pars[1]/(1-pars[3]))*(1-pars[4])}\n\t\t\t\t\telse if (is.element(4, constraints)) {pars[4]=pars[3]*pars[1]/(pars[2]-pars[3]*pars[2]+pars[3]*pars[1])}\t\t\t\n\t\t\t\t\tif (is.element(6, constraints)) {pars[6] = pars[5]}\n\t\t\t\t\t}\n\t\t\t\t#cat(\"pars:\", pars)\n\t\t\t\tl=pars[1:2]/(1-pars[3:4]) \n\t\t\t\tm=-pars[3:4]*pars[1:2]/(pars[3:4]-1) \n\t\t\t\t#lik=BISSE(c(l,m,pars[5:6]))[1]\n\t\t\n\t\t\t\t# CALC PRIORS # exponential\n\t\t\t\tif (use_exp==1) { \n\t\t\t\t\tprior=sum(exp_prior(pars[1:2],shape_prior[1],M[1:2])) + sum(exp_prior(pars[5:6],shape_prior[4],M[5:6])) + sum(beta_prior(shape_prior[2],shape_prior[3],pars[3:4]))\n\t\t\t\t} else{\n\t\t\t\t\tprior=sum(log(1/M))\n\t\t\t\t\tif (min(M-temp)<0) {prior = -Inf}\n\t\t\t\t\t} # uniform\n\n\t\t\t\t# CALC LIKELIHOOD\n\t\t\t\tif (prior> -Inf) {\n\t\t\t\t\tlik=try(BISSE(c(l,m,pars[5:6])))\n\t\t\t\t\tif (is.na(lik) | (class(lik) == \"try-error\" )) {lik=-Inf}\n\t\t\t\t\t} else{lik= -Inf}\n\n\t\t\t\tif (iteration==1){priorA=prior}\n\n\t\t\t\ttryCatch(\n\t\t\t\t{\n\t\t\t\tif ( (lik-likA)*temperature + (prior-priorA) >= log(runif(1,0,1)) ){\n\t\t\t\t\tlikA=lik\n\t\t\t\t\tpriorA=prior\n\t\t\t\t\tparsA=pars\n\t\t\t\t\tacc =acc + 1.\t\t\t\t\t\n\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t,error = function(e) NULL\n\t\t\t\t)\n\t\t\t\t\n\n\t\t\t\tif (iteration %% print_freq ==0) {cat(sprintf(\"%s\\t\", round(c(true_iteration, likA, priorA, parsA, temperature, t_index),2)), \"\\n\")}\n\t\t\t\n\t\t\t\tif (true_iteration %% sampling_freq ==0 & iteration>=burnin) {\n\t\t\t\t\tl=parsA[1:2]/(1-parsA[3:4])\n\t\t\t\t\tm=-parsA[3:4]*parsA[1:2]/(parsA[3:4]-1)\n\t\t\t\t\tLIK= LIK+likA\n\t\t\t\t\tcat(sprintf(\"%s\\t\", c(true_iteration, likA, priorA, acc/iteration, l, m, parsA, temperature, t_index)), \"\\n\", append=TRUE, file=out_file)\n\t\t\t\t}\n\n\t\t\t\tif (iteration>burnin) {true_iteration = true_iteration+1}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\n\t\n\tif (TDI>0)\t{\n\t\t\n\t\t\n\t\tout_marg= paste(out_file_stem,\"_marginal.txt\",sep=\"\")\n\t\t\n\t\td<-read.table(out_file, header=T) #, stringsAsFactors=F,sep=\"\\t\") #, row.names = NULL)\n\t\ttrapezia<-aggregate(d$lik, list(d$temp),FUN=\"mean\")\n\t\tstds<-aggregate(d$lik, list(d$temp),FUN=\"sd\")\n\n\t\tml=0\n\t\tfor (i in 1:(dim(trapezia)[[1]]-1)){\n\t\t\tml=ml+( (trapezia[i,2] + trapezia[(i+1),2])/2 * (trapezia[(i+1),1] - trapezia[(i),1]))\n\t\t}\n\t\tcat(\"\\nmean log likelihoods:\", trapezia[,2], file=out_marg, append=TRUE)\n\t\tcat(\"\\ntemperatures:\", unique(d$temp), file=out_marg, append=TRUE)\n\t\tcat(\"\\nstd(lnL):\", stds[,2], file=out_marg, append=TRUE)\n\t\tcat(\"\\n\\nLog Marginal Likelihood:\", ml, file=out_marg, append=TRUE)\n\t\n\n\t\tcat(\"\\n\\n Log Marginal Likelihood:\", ml)\n\t\tcat(\"\n The marginal likelihood can be used to compare different analyses and to perform model selection\n and hypothesis testing via Bayes factors. \n\n The marginal likelihood was saved to file:\", out_marg,\"\\n\\n\")\n\t\t}\n\t\n\t\tcat(\"\\n\")\n\t}\t\n\t\nmcmc_BiSSE( \n\tas.character(arg[1]), # infile1, # tree\n\tas.character(arg[2]), # infile2, # trait table\n\tas.character(arg[3]), # wd,\n\tas.integer(arg[4]), # TDI,\n as.character(arg[5]), # out_file,\n\tas.double(arg[6]),\t # rho0,\n\tas.double(arg[7]), # rho1,\n as.integer(arg[8]), # BD_model_0,\n as.integer(arg[9]), # BD_model_1,\n as.integer(arg[10]), # Trait_model,\n as.integer(arg[11]), # link_speciation,\n as.integer(arg[12]), # link_extinction,\n as.double(arg[13]), # link_trait,\n as.double(arg[14]), # prior_r,\n as.double(arg[15]), # prior_a,\n as.double(arg[16]), # prior_b,\n as.double(arg[17]), # prior_q,\n as.integer(arg[18]), # trees,\n as.integer(arg[19]), # iterations,\n as.integer(arg[20]), # sampling_freq,\n as.integer(arg[21]), # print_freq,\n as.integer(arg[22]), # burnin,\n as.double(arg[23]), # win_1,\n as.double(arg[24]), # win_2,\n as.double(arg[25]), # win_3,\n as.integer(arg[26]), # categories,\n as.double(arg[27]), # beta_shape\n\tas.character(arg[28])\t # path to diversitree library\n\t)\n\n", "meta": {"hexsha": "da1012a36e141ae2289d958077d6294316f9065e", "size": 7966, "ext": "r", "lang": "R", "max_stars_repo_path": "bayesrate/r_functions/BiSSEBMA.r", "max_stars_repo_name": "schnitzler-j/BayesRate", "max_stars_repo_head_hexsha": "86fb252df8589c89fce1c42699c69c5e2bbccb6f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2016-11-10T00:04:47.000Z", "max_stars_repo_stars_event_max_datetime": "2018-02-01T17:39:09.000Z", "max_issues_repo_path": "bayesrate/r_functions/BiSSEBMA.r", "max_issues_repo_name": "schnitzler-j/BayesRate", "max_issues_repo_head_hexsha": "86fb252df8589c89fce1c42699c69c5e2bbccb6f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bayesrate/r_functions/BiSSEBMA.r", "max_forks_repo_name": "schnitzler-j/BayesRate", "max_forks_repo_head_hexsha": "86fb252df8589c89fce1c42699c69c5e2bbccb6f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.288973384, "max_line_length": 167, "alphanum_fraction": 0.6104694954, "num_tokens": 2821, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.39606613803678226}} {"text": "\nfishery_model = function( p=NULL, DS=\"plot\", \n plotresults=TRUE, tag=\"default\", areas=c(\"cfanorth\", \"cfasouth\", \"cfa4x\"), \n vname=\"\", type=\"density\", res=NULL, fit=NULL, fn=NULL, aulabels=c(\"N-ENS\",\"S-ENS\",\"4X\"), save.plot=TRUE, ... ) {\n\n# sb = bio.snowcrab::fishery_model( DS=\"data_aggregated_timeseries\", p=p )\n\n\n if (tag==\"default\") {\n if (!is.null(p)) if (exists(\"tag\", p)) tag = p$tag\n }\n\n \n require( cmdstanr )\n\n\n if (DS==\"logistic_parameters\") {\n \n p = parameters_add(p, list(...)) # add passed args to parameter list, priority to args\n\n out = list()\n\n if (!exists(\"method\", out)) out$method = \"stan\" # \"jags\", etc.\n\n if (!exists(\"carstm_model_label\", p)) p$carstm_model_label = \"default\" \n\n if (!exists(\"outdir\", out)) out$outdir = file.path( p$modeldir, p$carstm_model_label, \"fishery_model_results\", tag )\n\n if (!exists(\"fnres\", out)) out$fnres = file.path( out$outdir, paste( \"logistics_model_results\", p$year.assessment, out$method, tag, \"RDS\", sep=\".\") )\n\n if (!exists(\"fnfit\", out)) out$fnfit = file.path( out$outdir, paste( \"logistics_model_fit\", p$year.assessment, out$method, tag, \"RDS\", sep=\".\") )\n \n dir.create( out$outdir, showWarnings = FALSE, recursive = TRUE )\n\n message( \"Results will be saved to:\", out$outdir)\n\n # observations\n if (!exists(\"standata\", out)) {\n out$standata = fishery_model( DS=\"data_aggregated_timeseries\", p=p )\n oo = apply( out$standata$IOA, 2, range, na.rm=TRUE )\n for (i in 1:ncol(oo)) {\n out$standata$IOA[,i] = (out$standata$IOA[,i] - oo[1,i] )/ diff(oo[,i]) # force median 0.5 with most data inside 0,1\n }\n # out$standata$IOA_min = apply( out$standata$IOA, 2, min, na.rm=TRUE ) \n }\n\n if (!exists(\"er\", out$standata)) out$standata$er = 0.2 # target exploitation rate\n if (!exists(\"U\", out$standata)) out$standata$U = ncol( out$standata$IOA) # number of regions\n if (!exists(\"N\", out$standata)) out$standata$N = nrow( out$standata$IOA) # no years with data\n if (!exists(\"M\", out$standata)) out$standata$M = 3 # no years for projections\n if (!exists(\"ty\", out$standata)) out$standata$ty = which(p$yrs == 2004) # index of the transition year (2004) between spring and fall surveys\n if (!exists(\"cfa4x\", out$standata)) out$standata$cfa4x = 3 # column index of cfa4x\n if (!exists(\"eps\", out$standata)) out$standata$eps = 1e-9 # small non-zero number\n\n out$standata$missing = ifelse( is.finite(out$standata$IOA), 0, 1)\n out$standata$missing_n = colSums(out$standata$missing)\n out$standata$missing_ntot = sum(out$standata$missing_n)\n\n # this must be done last\n out$standata$IOA[ which(!is.finite(out$standata$IOA)) ] = 0 # reset NAs to 0 as stan does not take NAs\n out$standata$CAT[ which(!is.finite(out$standata$CAT)) ] = out$standata$eps # remove NA's\n\n # priors\n if (!exists(\"Kmu\", out$standata)) out$standata$Kmu = c( 5.5, 65.0, 2.0 ) ## based upon prior historical analyses (when stmv and kriging were attempted)\n if (!exists(\"rmu\", out$standata)) out$standata$rmu = c( 1.0, 1.0, 1.0 ) ## biological constraint \n if (!exists(\"qmu\", out$standata)) out$standata$qmu = c( 1.0, 1.0, 1.0 ) ## based upon video observations q is close to 1 .. but sampling locations can of course cause bias (avoiding rocks and bedrock)\n\n if (!exists(\"Ksd\", out$standata)) out$standata$Ksd = c( 0.25, 0.25, 0.25 ) * out$standata$Kmu \n if (!exists(\"rsd\", out$standata)) out$standata$rsd = c( 0.1, 0.1, 0.1 ) * out$standata$rmu # smaller SD's to encourage solutions closer to prior means\n if (!exists(\"qsd\", out$standata)) out$standata$qsd = c( 0.1, 0.1, 0.1 ) * out$standata$qmu \n \n return(out)\n }\n\n\n if (DS==\"stan_surplus_production_2019_model\") {\n return( \"\n data {\n\n int N; // no. years\n int U; // no. regions\n int M; // no. years to project\n int ty;\n real er ;\n real eps ;\n vector[U] Ksd;\n vector[U] rsd;\n vector[U] Kmu ;\n vector[U] rmu ;\n vector[U] qmu ;\n vector[U] qsd ;\n matrix[N,U] CAT;\n matrix[N,U] IOA;\n matrix[N,U] missing;\n array[U] int missing_n;\n int missing_ntot;\n }\n\n transformed data {\n int MN;\n int N1;\n int NU;\n int Ndata;\n\n MN = M+N ;\n N1 = N+1;\n NU = N*U;\n Ndata = NU - missing_ntot; \n \n }\n\n parameters {\n vector [U] K;\n vector [U] r; // biologically should be ~ 1 \n vector [U] q; // multiplicative factor, unlikely to be >200%\n vector [U] qc; // offset .. unlikely to be off by > 50%\n vector [U] bosd; // observation error\n vector [U] bpsd; // process error\n vector [U] rem_sd; // catch error\n vector [U] b0;\n vector [missing_ntot] IOAmissing;\n matrix [M+N,U] bm; // permit overshoot bm max 1 \n }\n\n transformed parameters {\n matrix[N,U] Y; // index of abundance\n // copy parameters to a new variable (Y) with imputed missing values\n {\n int ii;\n ii = 0;\n for (j in 1:U) {\n for (i in 1:N) {\n Y[i,j] = IOA[i,j] ; // translation of a zscore to a positive internal scale \n if ( missing[i,j] == 1 ) {\n ii = ii+1;\n Y[i,j] = IOAmissing[ii];\n }\n }\n }\n }\n }\n\n model {\n\n // -------------------\n // priors for parameters\n K ~ normal( Kmu, Ksd ) ;\n r ~ normal( rmu, rsd ) ;\n b0 ~ beta( 8, 2 ) ; // starting b prior to first catch event\n bosd ~ cauchy( 0, 0.1 ) ; // slightly informative .. center of mass between (0,1)\n bpsd ~ cauchy( 0, 0.1 ) ;\n\n q ~ normal( qmu, qsd ) ; // i.e., Y:b scaling coeeficient\n qc ~ beta( 1, 100000 ) ; // i.e., Y:b offset constant ; plot(dbeta(seq(0,1,by=0.1), 1, 10 ) )\n\n // -------------------\n // biomass observation model\n // cfanorth(1) and cfasouth(2)\n // This is slightly complicated because a fall / spring survey correction is required:\n // B represents the total fishable biomass available in fishing year y\n // in fall surveys: Btot(t) = Bsurveyed(t) + removals(t)\n // in spring surveys: Btot(t) = Bsurveyed(t) + removals(t-1)\n // spring surveys from 1998 to 2003\n // this is conceptualized in the following time line:\n // '|' == start/end of each new fishing year\n // Sf = Survey in fall\n // Ss = Survey in spring\n // |...(t-2)...|.Ss..(t-1)...|...(t=2004)..Sf.|...(t+1).Sf..|...(t+2)..Sf.|...\n // Cfa 4X -- fall/winter fishery\n // Btot(t) = Bsurveyed(t) + removals(t) ## .. 2018-2019 -> 2018\n\n\n // spring surveys\n for (j in 1:2) {\n ( Y[1, j] / q[j] / K[j] ) + qc[j] ~ normal( ( ( fmax( bm[1,j] - CAT[1,j]/K[j] , eps) )) , bosd[j] ) ;\n for (i in 2:(ty-1) ){\n ( Y[i, j] / q[j] /K[j] ) + qc[j] ~ normal( ( ( fmax( bm[i,j] - CAT[i-1,j]/K[j] , eps) )), bosd[j] ) ;\n }\n }\n\n for (i in 1:(ty-1) ){\n ( Y[i, 3] / q[3]/K[3] ) + qc[3] ~ normal( ( ( fmax( bm[i,3] - CAT[i,3]/K[3] , eps) )) , bosd[3] ) ;\n }\n\n\n // transition year (ty)\n for (j in 1:2) {\n ( Y[ty,j] / q[j]/K[j] ) + qc[j] ~ normal( ( ( fmax( bm[ty,j] - (CAT[ty-1,j]/K[j] + CAT[ty,j]/K[j] ) / 2.0 , eps) ) ) , bosd[j] ) ; //NENS and SENS\n }\n ( Y[ty,3] / q[3]/ K[3] ) + qc[3] ~ normal( ( ( fmax( bm[ty,3] - CAT[ty,3]/K[3] , eps) ) ) , bosd[3] ) ; //SENS\n\n // fall surveys\n for (j in 1:3) {\n for (i in (ty+1):N) {\n ( Y[i,j] / q[j] / K[j] ) + qc[j] ~ normal( ( ( fmax( bm[i,j] - CAT[i,j]/K[j] , eps) ) ) , bosd[j] ) ; // fall surveys\n }\n }\n\n // -------------------\n // biomass process model\n // fmax .. force positive value .. initial conditions\n bm[1,] ~ normal( fmax(fmin(b0,0.99),eps), bpsd ) ;\n\n for (j in 1:U) {\n real o;\n for (i in 2:N) {\n o = r[j] * fmax( 1.0 - bm[i-1,j], eps ) ; \n bm[i,j] ~ normal( ( ( bm[i-1,j] * ( 1.0 + o ) - CAT[i-1,j]/K[j] )), bpsd[j] ) ;\n }\n for (i in N1:MN) {\n o = r[j] * fmax( 1.0 - bm[i-1,j], eps ) ; \n bm[i,j] ~ normal( ( ( bm[i-1,j] * ( 1.0 + o ) - er*bm[(i-1),j] )), bpsd[j] ) ;\n }\n }\n }\n\n generated quantities {\n vector[U] MSY;\n vector[U] BMSY;\n vector[U] FMSY;\n matrix[MN,U] B;\n matrix[MN,U] C;\n matrix[MN,U] F;\n vector[Ndata] log_lik;\n int n;\n\n // -------------------\n // fishing mortality\n // fall fisheries\n\n for (j in 1:U) {\n for (i in 1:N) {\n F[i,j] = -log( fmax( 1.0 - CAT[i,j]/K[j] / bm[i,j], eps) ) ;\n }\n for (i in N1:MN) {\n F[i,j] = -log( fmax( 1.0 - er * bm[i-1,j] / bm[i,j], eps) ) ;\n }\n }\n\n \n // -------------------\n // parameter estimates for output\n for (j in 1:U) {\n MSY[j] = r[j]* exp(K[j]) / 4 ; // maximum height of of the latent productivity (yield)\n BMSY[j] = exp(K[j])/2 ; // biomass at MSY\n FMSY[j] = 2.0 * MSY[j] / exp(K[j]) ; // fishing mortality at MSY\n }\n\n // recaled estimates\n for (j in 1:U) {\n for(i in 1:N) {\n B[i,j] = bm[i,j] * K[j] - CAT[i,j] ;\n C[i,j] = CAT[i,j] ;\n }\n\n for (i in N1:MN) {\n B[i,j] = (bm[i,j] - er*bm[(i-1),j]) * K[j] ;\n C[i,j] = er*bm[(i-1),j] * K[j] ;\n }\n\n }\n\n \n // for loo calcs (pointwise loglikelihoods)\n n=0;\n for (j in 1:U) {\n for (i in 1:N) {\n if ( missing[i,j] == 0 ) {\n n += 1;\n log_lik[n] = normal_lpdf( Y[i,j] | B[i,j], bosd[j] );\n } \n }\n }\n\n }\n\n\n \"\n )\n }\n\n\n\n if (DS==\"stan_surplus_production_2022_model_variation1_wider_qc_uniform\") {\n return( \"\n data {\n\n int N; // no. years\n int U; // no. regions\n int M; // no. years to project\n int ty;\n real er ;\n real eps ;\n vector[U] Ksd;\n vector[U] rsd;\n vector[U] Kmu ;\n vector[U] rmu ;\n vector[U] qmu ;\n vector[U] qsd ;\n matrix[N,U] CAT;\n matrix[N,U] IOA;\n matrix[N,U] missing;\n array[U] int missing_n;\n int missing_ntot;\n }\n\n transformed data {\n int MN;\n int N1;\n int NU;\n int Ndata;\n\n MN = M+N ;\n N1 = N+1;\n NU = N*U;\n Ndata = NU - missing_ntot; \n }\n\n parameters {\n vector [U] K;\n vector [U] r; // biologically should be ~ 1 \n vector [U] q; // multiplicative factor, unlikely to be >200%\n vector [U] qc; // offset .. unlikely to be off by > 50%\n vector [U] bosd; // observation error\n vector [U] bpsd; // process error\n vector [U] rem_sd; // catch error\n vector [U] b0;\n vector [missing_ntot] IOAmissing;\n matrix [M+N,U] bm; // force bm max 1 \n }\n\n transformed parameters {\n matrix[N,U] Y; // index of abundance\n // copy parameters to a new variable (Y) with imputed missing values\n {\n int ii;\n ii = 0;\n for (j in 1:U) {\n for (i in 1:N) {\n Y[i,j] = IOA[i,j] ; // translation of a zscore to a positive internal scale \n if ( missing[i,j] == 1 ) {\n ii = ii+1;\n Y[i,j] = IOAmissing[ii];\n }\n }\n }\n }\n\n }\n\n model {\n\n // -------------------\n // priors for parameters\n K ~ normal( Kmu, Ksd ) ;\n r ~ normal( rmu, rsd ) ;\n b0 ~ normal( 0.5, 0.1 ) ; // starting b prior to first catch event\n bosd ~ cauchy( 0, 0.1 ) ; // slightly informative .. center of mass between (0,1)\n bpsd ~ cauchy( 0, 0.1 ) ;\n\n q ~ normal( qmu, qsd ) ; // i.e., Y:b scaling coeeficient\n qc ~ uniform( -0.5, 0.5 ) ; // i.e., Y:b offset constant ; plot(dbeta(seq(0,1,by=0.1), 1, 2 ) )\n\n // -------------------\n // biomass observation model\n // cfanorth(1) and cfasouth(2)\n // This is slightly complicated because a fall / spring survey correction is required:\n // B represents the total fishable biomass available in fishing year y\n // in fall surveys: Btot(t) = Bsurveyed(t) + removals(t)\n // in spring surveys: Btot(t) = Bsurveyed(t) + removals(t-1)\n // spring surveys from 1998 to 2003\n // this is conceptualized in the following time line:\n // '|' == start/end of each new fishing year\n // Sf = Survey in fall\n // Ss = Survey in spring\n // |...(t-2)...|.Ss..(t-1)...|...(t=2004)..Sf.|...(t+1).Sf..|...(t+2)..Sf.|...\n // Cfa 4X -- fall/winter fishery\n // Btot(t) = Bsurveyed(t) + removals(t) ## .. 2018-2019 -> 2018\n\n\n // spring surveys\n for (j in 1:2) {\n ( Y[1, j] / q[j] ) + qc[j] ~ normal( ( ( fmax( bm[1,j] - CAT[1,j]/K[j] , eps) )) , bosd[j] ) ;\n for (i in 2:(ty-1) ){\n ( Y[i, j] / q[j] ) + qc[j] ~ normal( ( ( fmax( bm[i,j] - CAT[i-1,j]/K[j] , eps) )), bosd[j] ) ;\n }\n }\n\n for (i in 1:(ty-1) ){\n ( Y[i, 3] / q[3] ) + qc[3] ~ normal( ( ( fmax( bm[i,3] - CAT[i,3]/K[3] , eps) )) , bosd[3] ) ;\n }\n\n\n // transition year (ty)\n for (j in 1:2) {\n ( Y[ty,j] / q[j] ) + qc[j] ~ normal( ( ( fmax( bm[ty,j] - (CAT[ty-1,j]/K[j] + CAT[ty,j]/K[j] ) / 2.0 , eps) ) ) , bosd[j] ) ; //NENS and SENS\n }\n ( Y[ty,3] / q[3] ) + qc[3] ~ normal( ( ( fmax( bm[ty,3] - CAT[ty,3]/K[3] , eps) ) ) , bosd[3] ) ; //SENS\n\n // fall surveys\n for (j in 1:3) {\n for (i in (ty+1):N) {\n ( Y[i,j] / q[j] ) + qc[j] ~ normal( ( ( fmax( bm[i,j] - CAT[i,j]/K[j] , eps) ) ) , bosd[j] ) ; // fall surveys\n }\n }\n\n // -------------------\n // biomass process model\n // fmax .. force positive value .. initial conditions\n bm[1,] ~ normal( (b0), bpsd ) ;\n\n for (j in 1:U) {\n real o;\n for (i in 2:N) {\n o = r[j] * fmax( 1.0 - bm[i-1,j], eps ) ; \n bm[i,j] ~ normal( ( ( bm[i-1,j] * ( 1.0 + o ) - CAT[i-1,j]/K[j] )), bpsd[j] ) ;\n }\n for (i in N1:MN) {\n o = r[j] * fmax( 1.0 - bm[i-1,j], eps ) ; \n bm[i,j] ~ normal( ( ( bm[i-1,j] * ( 1.0 + o ) - er*bm[(i-1),j] )), bpsd[j] ) ;\n }\n }\n }\n\n generated quantities {\n vector[U] MSY;\n vector[U] BMSY;\n vector[U] FMSY;\n matrix[MN,U] B;\n matrix[MN,U] C;\n matrix[MN,U] F;\n vector[Ndata] log_lik;\n int n;\n\n // -------------------\n // fishing mortality\n // fall fisheries\n\n for (j in 1:U) {\n for (i in 1:N) {\n F[i,j] = -log( fmax( 1.0 - CAT[i,j]/K[j] / bm[i,j], eps) ) ;\n }\n for (i in N1:MN) {\n F[i,j] = -log( fmax( 1.0 - er * bm[i-1,j] / bm[i,j], eps) ) ;\n }\n }\n\n // -------------------\n // parameter estimates for output\n for (j in 1:U) {\n MSY[j] = r[j]* exp(K[j]) / 4 ; // maximum height of of the latent productivity (yield)\n BMSY[j] = exp(K[j])/2 ; // biomass at MSY\n FMSY[j] = 2.0 * MSY[j] / exp(K[j]) ; // fishing mortality at MSY\n }\n\n // recaled estimates\n for (j in 1:U) {\n for(i in 1:N) {\n B[i,j] = bm[i,j] * K[j] - CAT[i,j] ;\n C[i,j] = CAT[i,j] ;\n }\n\n for (i in N1:MN) {\n B[i,j] = (bm[i,j] - er*bm[(i-1),j]) * K[j] ;\n C[i,j] = er*bm[(i-1),j] * K[j] ;\n }\n\n }\n \n // for loo calcs (pointwise loglikelihoods)\n n=0;\n for (j in 1:U) {\n for (i in 1:N) {\n if ( missing[i,j] == 0 ) {\n n += 1;\n log_lik[n] = normal_lpdf( Y[i,j] | B[i,j], bosd[j] );\n } \n }\n }\n\n }\n \"\n )\n }\n\n\n\n if (DS==\"stan_surplus_production_2022_model_qc_uniform\") {\n return( \"\n data {\n\n int N; // no. years\n int U; // no. regions\n int M; // no. years to project\n int ty;\n real er ;\n real eps ;\n vector[U] Ksd;\n vector[U] rsd;\n vector[U] Kmu ;\n vector[U] rmu ;\n vector[U] qmu ;\n vector[U] qsd ;\n matrix[N,U] CAT;\n matrix[N,U] IOA;\n matrix[N,U] missing;\n array[U] int missing_n;\n int missing_ntot;\n }\n\n transformed data {\n int MN;\n int N1;\n int NU;\n int Ndata;\n\n MN = M+N ;\n N1 = N+1;\n NU = N*U;\n Ndata = NU - missing_ntot; \n }\n\n parameters {\n vector [U] K;\n vector [U] r; // biologically should be ~ 1 \n vector [U] q; // multiplicative factor, unlikely to be >200%\n vector [U] qc; // offset .. unlikely to be off by > 50%\n vector [U] bosd; // observation error\n vector [U] bpsd; // process error\n // vector [U] rem_sd; // catch error\n vector [U] b0;\n vector [missing_ntot] IOAmissing;\n matrix [M+N,U] bm; // force bm max 1 \n }\n\n transformed parameters {\n matrix[N,U] Y; // index of abundance\n // copy parameters to a new variable (Y) with imputed missing values\n {\n int ii;\n ii = 0;\n for (j in 1:U) {\n for (i in 1:N) {\n Y[i,j] = IOA[i,j] ; // translation of a zscore to a positive internal scale \n if ( missing[i,j] == 1 ) {\n ii = ii+1;\n Y[i,j] = IOAmissing[ii];\n }\n }\n }\n }\n\n }\n\n model {\n\n // -------------------\n // priors for parameters\n K ~ normal( Kmu, Ksd ) ;\n r ~ normal( rmu, rsd ) ;\n b0 ~ normal( 0.5, 0.1 ) ; // starting b prior to first catch event\n bosd ~ cauchy( 0, 0.1 ) ; // slightly informative .. center of mass between (0,1)\n bpsd ~ cauchy( 0, 0.1 ) ;\n\n q ~ normal( qmu, qsd ) ; // i.e., Y:b scaling coefficient\n qc ~ uniform( 0, 1 ) ; // i.e., Y:b offset constant ; \n\n // -------------------\n // biomass observation model\n // cfanorth(1) and cfasouth(2)\n // This is slightly complicated because a fall / spring survey correction is required:\n // B represents the total fishable biomass available in fishing year y\n // in fall surveys: Btot(t) = Bsurveyed(t) + removals(t)\n // in spring surveys: Btot(t) = Bsurveyed(t) + removals(t-1)\n // spring surveys from 1998 to 2003\n // this is conceptualized in the following time line:\n // '|' == start/end of each new fishing year\n // Sf = Survey in fall\n // Ss = Survey in spring\n // |...(t-2)...|.Ss..(t-1)...|...(t=2004)..Sf.|...(t+1).Sf..|...(t+2)..Sf.|...\n // Cfa 4X -- fall/winter fishery\n // Btot(t) = Bsurveyed(t) + removals(t) ## .. 2018-2019 -> 2018\n\n\n // spring surveys\n for (j in 1:2) {\n ( Y[1, j] / q[j] ) + qc[j] ~ normal( ( ( fmax( bm[1,j] - CAT[1,j]/K[j] , eps) )) , bosd[j] ) ;\n for (i in 2:(ty-1) ){\n ( Y[i, j] / q[j] ) + qc[j] ~ normal( ( ( fmax( bm[i,j] - CAT[i-1,j]/K[j] , eps) )), bosd[j] ) ;\n }\n }\n\n for (i in 1:(ty-1) ){\n ( Y[i, 3] / q[3] ) + qc[3] ~ normal( ( ( fmax( bm[i,3] - CAT[i,3]/K[3] , eps) )) , bosd[3] ) ;\n }\n\n\n // transition year (ty)\n for (j in 1:2) {\n ( Y[ty,j] / q[j] ) + qc[j] ~ normal( ( ( fmax( bm[ty,j] - (CAT[ty-1,j]/K[j] + CAT[ty,j]/K[j] ) / 2.0 , eps) ) ) , bosd[j] ) ; //NENS and SENS\n }\n ( Y[ty,3] / q[3] ) + qc[3] ~ normal( ( ( fmax( bm[ty,3] - CAT[ty,3]/K[3] , eps) ) ) , bosd[3] ) ; //SENS\n\n // fall surveys\n for (j in 1:3) {\n for (i in (ty+1):N) {\n ( Y[i,j] / q[j] ) + qc[j] ~ normal( ( ( fmax( bm[i,j] - CAT[i,j]/K[j] , eps) ) ) , bosd[j] ) ; // fall surveys\n }\n }\n\n // -------------------\n // biomass process model\n // fmax .. force positive value .. initial conditions\n bm[1,] ~ normal( (b0), bpsd ) ;\n\n for (j in 1:U) {\n real o;\n for (i in 2:N) {\n o = r[j] * fmax( 1.0 - bm[i-1,j], eps ) ; \n bm[i,j] ~ normal( ( ( bm[i-1,j] * ( 1.0 + o ) - CAT[i-1,j]/K[j] )), bpsd[j] ) ;\n }\n for (i in N1:MN) {\n o = r[j] * fmax( 1.0 - bm[i-1,j], eps ) ; \n bm[i,j] ~ normal( ( ( bm[i-1,j] * ( 1.0 + o ) - er*bm[(i-1),j] )), bpsd[j] ) ;\n }\n }\n }\n\n generated quantities {\n vector[U] MSY;\n vector[U] BMSY;\n vector[U] FMSY;\n matrix[MN,U] B;\n matrix[MN,U] C;\n matrix[MN,U] F;\n vector[Ndata] log_lik;\n int n;\n\n // -------------------\n // fishing mortality\n // fall fisheries\n\n for (j in 1:U) {\n for (i in 1:N) {\n F[i,j] = -log( fmax( 1.0 - CAT[i,j]/K[j] / bm[i,j], eps) ) ;\n }\n for (i in N1:MN) {\n F[i,j] = -log( fmax( 1.0 - er * bm[i-1,j] / bm[i,j], eps) ) ;\n }\n }\n\n // -------------------\n // parameter estimates for output\n for (j in 1:U) {\n MSY[j] = r[j]* exp(K[j]) / 4 ; // maximum height of of the latent productivity (yield)\n BMSY[j] = exp(K[j])/2 ; // biomass at MSY\n FMSY[j] = 2.0 * MSY[j] / exp(K[j]) ; // fishing mortality at MSY\n }\n\n // recaled estimates\n for (j in 1:U) {\n for(i in 1:N) {\n B[i,j] = bm[i,j] * K[j] - CAT[i,j] ;\n C[i,j] = CAT[i,j] ;\n }\n\n for (i in N1:MN) {\n B[i,j] = (bm[i,j] - er*bm[(i-1),j]) * K[j] ;\n C[i,j] = er*bm[(i-1),j] * K[j] ;\n }\n\n }\n \n // for loo calcs (pointwise loglikelihoods)\n n=0;\n for (j in 1:U) {\n for (i in 1:N) {\n if ( missing[i,j] == 0 ) {\n n += 1;\n log_lik[n] = normal_lpdf( Y[i,j] | B[i,j], bosd[j] );\n } \n }\n }\n\n }\n \"\n )\n }\n\n if (DS==\"stan_surplus_production_2022_model_variation1_wider_qc_normal\") {\n return( \"\n data {\n\n int N; // no. years\n int U; // no. regions\n int M; // no. years to project\n int ty;\n real er ;\n real eps ;\n vector[U] Ksd;\n vector[U] rsd;\n vector[U] Kmu ;\n vector[U] rmu ;\n vector[U] qmu ;\n vector[U] qsd ;\n matrix[N,U] CAT;\n matrix[N,U] IOA;\n matrix[N,U] missing;\n array[U] int missing_n;\n int missing_ntot;\n }\n\n transformed data {\n int MN;\n int N1;\n int NU;\n int Ndata;\n\n MN = M+N ;\n N1 = N+1;\n NU = N*U;\n Ndata = NU - missing_ntot; \n }\n\n parameters {\n vector [U] K;\n vector [U] r; // biologically should be ~ 1 \n vector [U] q; // multiplicative factor, unlikely to be >200%\n vector [U] qc; // offset .. unlikely to be off by > 50%\n vector [U] bosd; // observation error\n vector [U] bpsd; // process error\n vector [U] rem_sd; // catch error\n vector [U] b0;\n vector [missing_ntot] IOAmissing;\n matrix [M+N,U] bm; // force bm max 1 \n }\n\n transformed parameters {\n matrix[N,U] Y; // index of abundance\n // copy parameters to a new variable (Y) with imputed missing values\n {\n int ii;\n ii = 0;\n for (j in 1:U) {\n for (i in 1:N) {\n Y[i,j] = IOA[i,j] ; // translation of a zscore to a positive internal scale \n if ( missing[i,j] == 1 ) {\n ii = ii+1;\n Y[i,j] = IOAmissing[ii];\n }\n }\n }\n }\n\n }\n\n model {\n\n // -------------------\n // priors for parameters\n K ~ normal( Kmu, Ksd ) ;\n r ~ normal( rmu, rsd ) ;\n b0 ~ normal( 0.5, 0.1 ) ; // starting b prior to first catch event\n bosd ~ cauchy( 0, 0.1 ) ; // slightly informative .. center of mass between (0,1)\n bpsd ~ cauchy( 0, 0.1 ) ;\n\n q ~ normal( qmu, qsd ) ; // i.e., Y:b scaling coeeficient\n qc ~ normal( 0, 0.25 ) ; // i.e., Y:b offset constant ; plot(dbeta(seq(0,1,by=0.1), 1, 10 ) )\n\n // -------------------\n // biomass observation model\n // cfanorth(1) and cfasouth(2)\n // This is slightly complicated because a fall / spring survey correction is required:\n // B represents the total fishable biomass available in fishing year y\n // in fall surveys: Btot(t) = Bsurveyed(t) + removals(t)\n // in spring surveys: Btot(t) = Bsurveyed(t) + removals(t-1)\n // spring surveys from 1998 to 2003\n // this is conceptualized in the following time line:\n // '|' == start/end of each new fishing year\n // Sf = Survey in fall\n // Ss = Survey in spring\n // |...(t-2)...|.Ss..(t-1)...|...(t=2004)..Sf.|...(t+1).Sf..|...(t+2)..Sf.|...\n // Cfa 4X -- fall/winter fishery\n // Btot(t) = Bsurveyed(t) + removals(t) ## .. 2018-2019 -> 2018\n\n\n // spring surveys\n for (j in 1:2) {\n ( Y[1, j] / q[j] ) + qc[j] ~ normal( ( ( fmax( bm[1,j] - CAT[1,j]/K[j] , eps) )) , bosd[j] ) ;\n for (i in 2:(ty-1) ){\n ( Y[i, j] / q[j] ) + qc[j] ~ normal( ( ( fmax( bm[i,j] - CAT[i-1,j]/K[j] , eps) )), bosd[j] ) ;\n }\n }\n\n for (i in 1:(ty-1) ){\n ( Y[i, 3] / q[3] ) + qc[3] ~ normal( ( ( fmax( bm[i,3] - CAT[i,3]/K[3] , eps) )) , bosd[3] ) ;\n }\n\n\n // transition year (ty)\n for (j in 1:2) {\n ( Y[ty,j] / q[j] ) + qc[j] ~ normal( ( ( fmax( bm[ty,j] - (CAT[ty-1,j]/K[j] + CAT[ty,j]/K[j] ) / 2.0 , eps) ) ) , bosd[j] ) ; //NENS and SENS\n }\n ( Y[ty,3] / q[3] ) + qc[3] ~ normal( ( ( fmax( bm[ty,3] - CAT[ty,3]/K[3] , eps) ) ) , bosd[3] ) ; //SENS\n\n // fall surveys\n for (j in 1:3) {\n for (i in (ty+1):N) {\n ( Y[i,j] / q[j] ) + qc[j] ~ normal( ( ( fmax( bm[i,j] - CAT[i,j]/K[j] , eps) ) ) , bosd[j] ) ; // fall surveys\n }\n }\n\n // -------------------\n // biomass process model\n // fmax .. force positive value .. initial conditions\n bm[1,] ~ normal( (b0), bpsd ) ;\n\n for (j in 1:U) {\n real o;\n for (i in 2:N) {\n o = r[j] * fmax( 1.0 - bm[i-1,j], eps ) ; \n bm[i,j] ~ normal( ( ( bm[i-1,j] * ( 1.0 + o ) - CAT[i-1,j]/K[j] )), bpsd[j] ) ;\n }\n for (i in N1:MN) {\n o = r[j] * fmax( 1.0 - bm[i-1,j], eps ) ; \n bm[i,j] ~ normal( ( ( bm[i-1,j] * ( 1.0 + o ) - er*bm[(i-1),j] )), bpsd[j] ) ;\n }\n }\n }\n\n generated quantities {\n vector[U] MSY;\n vector[U] BMSY;\n vector[U] FMSY;\n matrix[MN,U] B;\n matrix[MN,U] C;\n matrix[MN,U] F;\n vector[Ndata] log_lik;\n int n;\n\n // -------------------\n // fishing mortality\n // fall fisheries\n\n for (j in 1:U) {\n for (i in 1:N) {\n F[i,j] = -log( fmax( 1.0 - CAT[i,j]/K[j] / bm[i,j], eps) ) ;\n }\n for (i in N1:MN) {\n F[i,j] = -log( fmax( 1.0 - er * bm[i-1,j] / bm[i,j], eps) ) ;\n }\n }\n\n // -------------------\n // parameter estimates for output\n for (j in 1:U) {\n MSY[j] = r[j]* exp(K[j]) / 4 ; // maximum height of of the latent productivity (yield)\n BMSY[j] = exp(K[j])/2 ; // biomass at MSY\n FMSY[j] = 2.0 * MSY[j] / exp(K[j]) ; // fishing mortality at MSY\n }\n\n // recaled estimates\n for (j in 1:U) {\n for(i in 1:N) {\n B[i,j] = bm[i,j] * K[j] - CAT[i,j] ;\n C[i,j] = CAT[i,j] ;\n }\n\n for (i in N1:MN) {\n B[i,j] = (bm[i,j] - er*bm[(i-1),j]) * K[j] ;\n C[i,j] = er*bm[(i-1),j] * K[j] ;\n }\n\n }\n \n // for loo calcs (pointwise loglikelihoods)\n n=0;\n for (j in 1:U) {\n for (i in 1:N) {\n if ( missing[i,j] == 0 ) {\n n += 1;\n log_lik[n] = normal_lpdf( Y[i,j] | B[i,j], bosd[j] );\n } \n }\n }\n\n }\n \"\n )\n }\n\n\n\n if (DS==\"stan_surplus_production_2022_model_variation1_wider_qc_normal_0\") {\n return( \"\n data {\n\n int N; // no. years\n int U; // no. regions\n int M; // no. years to project\n int ty;\n real er ;\n real eps ;\n vector[U] Ksd;\n vector[U] rsd;\n vector[U] Kmu ;\n vector[U] rmu ;\n vector[U] qmu ;\n vector[U] qsd ;\n matrix[N,U] CAT;\n matrix[N,U] IOA;\n matrix[N,U] missing;\n array[U] int missing_n;\n int missing_ntot;\n }\n\n transformed data {\n int MN;\n int N1;\n int NU;\n int Ndata;\n\n MN = M+N ;\n N1 = N+1;\n NU = N*U;\n Ndata = NU - missing_ntot; \n }\n\n parameters {\n vector [U] K;\n vector [U] r; // biologically should be ~ 1 \n vector [U] q; // multiplicative factor, unlikely to be >200%\n vector [U] qc; // offset .. unlikely to be off by > 50%\n vector [U] bosd; // observation error\n vector [U] bpsd; // process error\n vector [U] rem_sd; // catch error\n vector [U] b0;\n vector [missing_ntot] IOAmissing;\n matrix [M+N,U] bm; // force bm max 1 \n }\n\n transformed parameters {\n matrix[N,U] Y; // index of abundance\n // copy parameters to a new variable (Y) with imputed missing values\n {\n int ii;\n ii = 0;\n for (j in 1:U) {\n for (i in 1:N) {\n Y[i,j] = IOA[i,j] ; // translation of a zscore to a positive internal scale \n if ( missing[i,j] == 1 ) {\n ii = ii+1;\n Y[i,j] = IOAmissing[ii];\n }\n }\n }\n }\n\n }\n\n model {\n\n // -------------------\n // priors for parameters\n K ~ normal( Kmu, Ksd ) ;\n r ~ normal( rmu, rsd ) ;\n b0 ~ normal( 0.5, 0.1 ) ; // starting b prior to first catch event\n bosd ~ cauchy( 0, 0.1 ) ; // slightly informative .. center of mass between (0,1)\n bpsd ~ cauchy( 0, 0.1 ) ;\n\n q ~ normal( qmu, qsd ) ; // i.e., Y:b scaling coeeficient\n qc ~ normal( 0, 0.000001 ) ; // i.e.,force to be 0\n \n // -------------------\n // biomass observation model\n // cfanorth(1) and cfasouth(2)\n // This is slightly complicated because a fall / spring survey correction is required:\n // B represents the total fishable biomass available in fishing year y\n // in fall surveys: Btot(t) = Bsurveyed(t) + removals(t)\n // in spring surveys: Btot(t) = Bsurveyed(t) + removals(t-1)\n // spring surveys from 1998 to 2003\n // this is conceptualized in the following time line:\n // '|' == start/end of each new fishing year\n // Sf = Survey in fall\n // Ss = Survey in spring\n // |...(t-2)...|.Ss..(t-1)...|...(t=2004)..Sf.|...(t+1).Sf..|...(t+2)..Sf.|...\n // Cfa 4X -- fall/winter fishery\n // Btot(t) = Bsurveyed(t) + removals(t) ## .. 2018-2019 -> 2018\n\n\n // spring surveys\n for (j in 1:2) {\n ( Y[1, j] / q[j] ) + qc[j] ~ normal( ( ( fmax( bm[1,j] - CAT[1,j]/K[j] , eps) )) , bosd[j] ) ;\n for (i in 2:(ty-1) ){\n ( Y[i, j] / q[j] ) + qc[j] ~ normal( ( ( fmax( bm[i,j] - CAT[i-1,j]/K[j] , eps) )), bosd[j] ) ;\n }\n }\n\n for (i in 1:(ty-1) ){\n ( Y[i, 3] / q[3] ) + qc[3] ~ normal( ( ( fmax( bm[i,3] - CAT[i,3]/K[3] , eps) )) , bosd[3] ) ;\n }\n\n\n // transition year (ty)\n for (j in 1:2) {\n ( Y[ty,j] / q[j] ) + qc[j] ~ normal( ( ( fmax( bm[ty,j] - (CAT[ty-1,j]/K[j] + CAT[ty,j]/K[j] ) / 2.0 , eps) ) ) , bosd[j] ) ; //NENS and SENS\n }\n ( Y[ty,3] / q[3] ) + qc[3] ~ normal( ( ( fmax( bm[ty,3] - CAT[ty,3]/K[3] , eps) ) ) , bosd[3] ) ; //SENS\n\n // fall surveys\n for (j in 1:3) {\n for (i in (ty+1):N) {\n ( Y[i,j] / q[j] ) + qc[j] ~ normal( ( ( fmax( bm[i,j] - CAT[i,j]/K[j] , eps) ) ) , bosd[j] ) ; // fall surveys\n }\n }\n\n // -------------------\n // biomass process model\n // fmax .. force positive value .. initial conditions\n bm[1,] ~ normal( (b0), bpsd ) ;\n\n for (j in 1:U) {\n real o;\n for (i in 2:N) {\n o = r[j] * fmax( 1.0 - bm[i-1,j], eps ) ; \n bm[i,j] ~ normal( ( ( bm[i-1,j] * ( 1.0 + o ) - CAT[i-1,j]/K[j] )), bpsd[j] ) ;\n }\n for (i in N1:MN) {\n o = r[j] * fmax( 1.0 - bm[i-1,j], eps ) ; \n bm[i,j] ~ normal( ( ( bm[i-1,j] * ( 1.0 + o ) - er*bm[(i-1),j] )), bpsd[j] ) ;\n }\n }\n }\n\n generated quantities {\n vector[U] MSY;\n vector[U] BMSY;\n vector[U] FMSY;\n matrix[MN,U] B;\n matrix[MN,U] C;\n matrix[MN,U] F;\n vector[Ndata] log_lik;\n int n;\n\n // -------------------\n // fishing mortality\n // fall fisheries\n\n for (j in 1:U) {\n for (i in 1:N) {\n F[i,j] = -log( fmax( 1.0 - CAT[i,j]/K[j] / bm[i,j], eps) ) ;\n }\n for (i in N1:MN) {\n F[i,j] = -log( fmax( 1.0 - er * bm[i-1,j] / bm[i,j], eps) ) ;\n }\n }\n\n // -------------------\n // parameter estimates for output\n for (j in 1:U) {\n MSY[j] = r[j]* exp(K[j]) / 4 ; // maximum height of of the latent productivity (yield)\n BMSY[j] = exp(K[j])/2 ; // biomass at MSY\n FMSY[j] = 2.0 * MSY[j] / exp(K[j]) ; // fishing mortality at MSY\n }\n\n // recaled estimates\n for (j in 1:U) {\n for(i in 1:N) {\n B[i,j] = bm[i,j] * K[j] - CAT[i,j] ;\n C[i,j] = CAT[i,j] ;\n }\n\n for (i in N1:MN) {\n B[i,j] = (bm[i,j] - er*bm[(i-1),j]) * K[j] ;\n C[i,j] = er*bm[(i-1),j] * K[j] ;\n }\n\n }\n \n // for loo calcs (pointwise loglikelihoods)\n n=0;\n for (j in 1:U) {\n for (i in 1:N) {\n if ( missing[i,j] == 0 ) {\n n += 1;\n log_lik[n] = normal_lpdf( Y[i,j] | B[i,j], bosd[j] );\n } \n }\n }\n\n }\n \"\n )\n }\n\n\n if (DS==\"stan_surplus_production_2022_model_qc_beta\") {\n return( \"\n data {\n\n int N; // no. years\n int U; // no. regions\n int M; // no. years to project\n int ty;\n real er ;\n real eps ;\n vector[U] Ksd;\n vector[U] rsd;\n vector[U] Kmu ;\n vector[U] rmu ;\n vector[U] qmu ;\n vector[U] qsd ;\n matrix[N,U] CAT;\n matrix[N,U] IOA;\n matrix[N,U] missing;\n array[U] int missing_n;\n int missing_ntot;\n }\n\n transformed data {\n int MN;\n int N1;\n int NU;\n int Ndata;\n\n MN = M+N ;\n N1 = N+1;\n NU = N*U;\n Ndata = NU - missing_ntot; \n }\n\n parameters {\n vector [U] K;\n vector [U] r; // biologically should be ~ 1 \n vector [U] q; // multiplicative factor, unlikely to be >200%\n vector [U] qc; // offset .. unlikely to be off by > 50%\n vector [U] bosd; // observation error\n vector [U] bpsd; // process error\n vector [U] rem_sd; // catch error\n vector [U] b0;\n vector [missing_ntot] IOAmissing;\n matrix [M+N,U] bm; // force bm max 1 \n }\n\n transformed parameters {\n matrix[N,U] Y; // index of abundance\n // copy parameters to a new variable (Y) with imputed missing values\n {\n int ii;\n ii = 0;\n for (j in 1:U) {\n for (i in 1:N) {\n Y[i,j] = IOA[i,j] ; // translation of a zscore to a positive internal scale \n if ( missing[i,j] == 1 ) {\n ii = ii+1;\n Y[i,j] = IOAmissing[ii];\n }\n }\n }\n }\n\n }\n\n model {\n\n // -------------------\n // priors for parameters\n K ~ normal( Kmu, Ksd ) ;\n r ~ normal( rmu, rsd ) ;\n b0 ~ normal( 0.5, 0.1 ) ; // starting b prior to first catch event\n bosd ~ cauchy( 0, 0.1 ) ; // slightly informative .. center of mass between (0,1)\n bpsd ~ cauchy( 0, 0.1 ) ;\n\n q ~ normal( qmu, qsd ) ; // i.e., Y:b scaling coeeficient\n qc ~ beta( 1, 2 ) ; // i.e., Y:b offset constant ; plot(dbeta(seq(0,1,by=0.1), 1, 10 ) )\n\n // -------------------\n // biomass observation model\n // cfanorth(1) and cfasouth(2)\n // This is slightly complicated because a fall / spring survey correction is required:\n // B represents the total fishable biomass available in fishing year y\n // in fall surveys: Btot(t) = Bsurveyed(t) + removals(t)\n // in spring surveys: Btot(t) = Bsurveyed(t) + removals(t-1)\n // spring surveys from 1998 to 2003\n // this is conceptualized in the following time line:\n // '|' == start/end of each new fishing year\n // Sf = Survey in fall\n // Ss = Survey in spring\n // |...(t-2)...|.Ss..(t-1)...|...(t=2004)..Sf.|...(t+1).Sf..|...(t+2)..Sf.|...\n // Cfa 4X -- fall/winter fishery\n // Btot(t) = Bsurveyed(t) + removals(t) ## .. 2018-2019 -> 2018\n\n\n // spring surveys\n for (j in 1:2) {\n ( Y[1, j] / q[j] ) + qc[j] ~ normal( ( ( fmax( bm[1,j] - CAT[1,j]/K[j] , eps) )) , bosd[j] ) ;\n for (i in 2:(ty-1) ){\n ( Y[i, j] / q[j] ) + qc[j] ~ normal( ( ( fmax( bm[i,j] - CAT[i-1,j]/K[j] , eps) )), bosd[j] ) ;\n }\n }\n\n for (i in 1:(ty-1) ){\n ( Y[i, 3] / q[3] ) + qc[3] ~ normal( ( ( fmax( bm[i,3] - CAT[i,3]/K[3] , eps) )) , bosd[3] ) ;\n }\n\n\n // transition year (ty)\n for (j in 1:2) {\n ( Y[ty,j] / q[j] ) + qc[j] ~ normal( ( ( fmax( bm[ty,j] - (CAT[ty-1,j]/K[j] + CAT[ty,j]/K[j] ) / 2.0 , eps) ) ) , bosd[j] ) ; //NENS and SENS\n }\n ( Y[ty,3] / q[3] ) + qc[3] ~ normal( ( ( fmax( bm[ty,3] - CAT[ty,3]/K[3] , eps) ) ) , bosd[3] ) ; //SENS\n\n // fall surveys\n for (j in 1:3) {\n for (i in (ty+1):N) {\n ( Y[i,j] / q[j] ) + qc[j] ~ normal( ( ( fmax( bm[i,j] - CAT[i,j]/K[j] , eps) ) ) , bosd[j] ) ; // fall surveys\n }\n }\n\n // -------------------\n // biomass process model\n // fmax .. force positive value .. initial conditions\n bm[1,] ~ normal( (b0), bpsd ) ;\n\n for (j in 1:U) {\n real o;\n for (i in 2:N) {\n o = r[j] * fmax( 1.0 - bm[i-1,j], eps ) ; \n bm[i,j] ~ normal( ( ( bm[i-1,j] * ( 1.0 + o ) - CAT[i-1,j]/K[j] )), bpsd[j] ) ;\n }\n for (i in N1:MN) {\n o = r[j] * fmax( 1.0 - bm[i-1,j], eps ) ; \n bm[i,j] ~ normal( ( ( bm[i-1,j] * ( 1.0 + o ) - er*bm[(i-1),j] )), bpsd[j] ) ;\n }\n }\n }\n\n generated quantities {\n vector[U] MSY;\n vector[U] BMSY;\n vector[U] FMSY;\n matrix[MN,U] B;\n matrix[MN,U] C;\n matrix[MN,U] F;\n vector[Ndata] log_lik;\n int n;\n\n // -------------------\n // fishing mortality\n // fall fisheries\n\n for (j in 1:U) {\n for (i in 1:N) {\n F[i,j] = -log( fmax( 1.0 - CAT[i,j]/K[j] / bm[i,j], eps) ) ;\n }\n for (i in N1:MN) {\n F[i,j] = -log( fmax( 1.0 - er * bm[i-1,j] / bm[i,j], eps) ) ;\n }\n }\n\n // -------------------\n // parameter estimates for output\n for (j in 1:U) {\n MSY[j] = r[j]* exp(K[j]) / 4 ; // maximum height of of the latent productivity (yield)\n BMSY[j] = exp(K[j])/2 ; // biomass at MSY\n FMSY[j] = 2.0 * MSY[j] / exp(K[j]) ; // fishing mortality at MSY\n }\n\n // recaled estimates\n for (j in 1:U) {\n for(i in 1:N) {\n B[i,j] = bm[i,j] * K[j] - CAT[i,j] ;\n C[i,j] = CAT[i,j] ;\n }\n\n for (i in N1:MN) {\n B[i,j] = (bm[i,j] - er*bm[(i-1),j]) * K[j] ;\n C[i,j] = er*bm[(i-1),j] * K[j] ;\n }\n\n }\n \n // for loo calcs (pointwise loglikelihoods)\n n=0;\n for (j in 1:U) {\n for (i in 1:N) {\n if ( missing[i,j] == 0 ) {\n n += 1;\n log_lik[n] = normal_lpdf( Y[i,j] | B[i,j], bosd[j] );\n } \n }\n }\n\n }\n \"\n )\n }\n\n\n\n\n if (DS==\"stan_surplus_production_2022_model_qc_cauchy\") {\n return( \"\n data {\n\n int N; // no. years\n int U; // no. regions\n int M; // no. years to project\n int ty;\n real er ;\n real eps ;\n vector[U] Ksd;\n vector[U] rsd;\n vector[U] Kmu ;\n vector[U] rmu ;\n vector[U] qmu ;\n vector[U] qsd ;\n matrix[N,U] CAT;\n matrix[N,U] IOA;\n matrix[N,U] missing;\n array[U] int missing_n;\n int missing_ntot;\n }\n\n transformed data {\n int MN;\n int N1;\n int NU;\n int Ndata;\n\n MN = M+N ;\n N1 = N+1;\n NU = N*U;\n Ndata = NU - missing_ntot; \n }\n\n parameters {\n vector [U] K;\n vector [U] r; // biologically should be ~ 1 \n vector [U] q; // multiplicative factor, unlikely to be >200%\n vector [U] qc; // offset .. unlikely to be off by > 50%\n vector [U] bosd; // observation error\n vector [U] bpsd; // process error\n vector [U] rem_sd; // catch error\n vector [U] b0;\n vector [missing_ntot] IOAmissing;\n matrix [M+N,U] bm; // force bm max 1 \n }\n\n transformed parameters {\n matrix[N,U] Y; // index of abundance\n // copy parameters to a new variable (Y) with imputed missing values\n {\n int ii;\n ii = 0;\n for (j in 1:U) {\n for (i in 1:N) {\n Y[i,j] = IOA[i,j] ; // translation of a zscore to a positive internal scale \n if ( missing[i,j] == 1 ) {\n ii = ii+1;\n Y[i,j] = IOAmissing[ii];\n }\n }\n }\n }\n\n }\n\n model {\n\n // -------------------\n // priors for parameters\n K ~ normal( Kmu, Ksd ) ;\n r ~ normal( rmu, rsd ) ;\n b0 ~ normal( 0.5, 0.1 ) ; // starting b prior to first catch event\n bosd ~ cauchy( 0, 0.1 ) ; // slightly informative .. center of mass between (0,1)\n bpsd ~ cauchy( 0, 0.1 ) ;\n\n q ~ normal( qmu, qsd ) ; // i.e., Y:b scaling coeeficient\n qc ~ cauchy( 0, 0.1 ) ; // i.e., Y:b offset constant ; plot(dbeta(seq(0,1,by=0.1), 1, 10 ) )\n\n // -------------------\n // biomass observation model\n // cfanorth(1) and cfasouth(2)\n // This is slightly complicated because a fall / spring survey correction is required:\n // B represents the total fishable biomass available in fishing year y\n // in fall surveys: Btot(t) = Bsurveyed(t) + removals(t)\n // in spring surveys: Btot(t) = Bsurveyed(t) + removals(t-1)\n // spring surveys from 1998 to 2003\n // this is conceptualized in the following time line:\n // '|' == start/end of each new fishing year\n // Sf = Survey in fall\n // Ss = Survey in spring\n // |...(t-2)...|.Ss..(t-1)...|...(t=2004)..Sf.|...(t+1).Sf..|...(t+2)..Sf.|...\n // Cfa 4X -- fall/winter fishery\n // Btot(t) = Bsurveyed(t) + removals(t) ## .. 2018-2019 -> 2018\n\n\n // spring surveys\n for (j in 1:2) {\n ( Y[1, j] / q[j] ) + qc[j] ~ normal( ( ( fmax( bm[1,j] - CAT[1,j]/K[j] , eps) )) , bosd[j] ) ;\n for (i in 2:(ty-1) ){\n ( Y[i, j] / q[j] ) + qc[j] ~ normal( ( ( fmax( bm[i,j] - CAT[i-1,j]/K[j] , eps) )), bosd[j] ) ;\n }\n }\n\n for (i in 1:(ty-1) ){\n ( Y[i, 3] / q[3] ) + qc[3] ~ normal( ( ( fmax( bm[i,3] - CAT[i,3]/K[3] , eps) )) , bosd[3] ) ;\n }\n\n\n // transition year (ty)\n for (j in 1:2) {\n ( Y[ty,j] / q[j] ) + qc[j] ~ normal( ( ( fmax( bm[ty,j] - (CAT[ty-1,j]/K[j] + CAT[ty,j]/K[j] ) / 2.0 , eps) ) ) , bosd[j] ) ; //NENS and SENS\n }\n ( Y[ty,3] / q[3] ) + qc[3] ~ normal( ( ( fmax( bm[ty,3] - CAT[ty,3]/K[3] , eps) ) ) , bosd[3] ) ; //SENS\n\n // fall surveys\n for (j in 1:3) {\n for (i in (ty+1):N) {\n ( Y[i,j] / q[j] ) + qc[j] ~ normal( ( ( fmax( bm[i,j] - CAT[i,j]/K[j] , eps) ) ) , bosd[j] ) ; // fall surveys\n }\n }\n\n // -------------------\n // biomass process model\n // fmax .. force positive value .. initial conditions\n bm[1,] ~ normal( (b0), bpsd ) ;\n\n for (j in 1:U) {\n real o;\n for (i in 2:N) {\n o = r[j] * fmax( 1.0 - bm[i-1,j], eps ) ; \n bm[i,j] ~ normal( ( ( bm[i-1,j] * ( 1.0 + o ) - CAT[i-1,j]/K[j] )), bpsd[j] ) ;\n }\n for (i in N1:MN) {\n o = r[j] * fmax( 1.0 - bm[i-1,j], eps ) ; \n bm[i,j] ~ normal( ( ( bm[i-1,j] * ( 1.0 + o ) - er*bm[(i-1),j] )), bpsd[j] ) ;\n }\n }\n }\n\n generated quantities {\n vector[U] MSY;\n vector[U] BMSY;\n vector[U] FMSY;\n matrix[MN,U] B;\n matrix[MN,U] C;\n matrix[MN,U] F;\n vector[Ndata] log_lik;\n int n;\n\n // -------------------\n // fishing mortality\n // fall fisheries\n\n for (j in 1:U) {\n for (i in 1:N) {\n F[i,j] = -log( fmax( 1.0 - CAT[i,j]/K[j] / bm[i,j], eps) ) ;\n }\n for (i in N1:MN) {\n F[i,j] = -log( fmax( 1.0 - er * bm[i-1,j] / bm[i,j], eps) ) ;\n }\n }\n\n // -------------------\n // parameter estimates for output\n for (j in 1:U) {\n MSY[j] = r[j]* exp(K[j]) / 4 ; // maximum height of of the latent productivity (yield)\n BMSY[j] = exp(K[j])/2 ; // biomass at MSY\n FMSY[j] = 2.0 * MSY[j] / exp(K[j]) ; // fishing mortality at MSY\n }\n\n // recaled estimates\n for (j in 1:U) {\n for(i in 1:N) {\n B[i,j] = bm[i,j] * K[j] - CAT[i,j] ;\n C[i,j] = CAT[i,j] ;\n }\n\n for (i in N1:MN) {\n B[i,j] = (bm[i,j] - er*bm[(i-1),j]) * K[j] ;\n C[i,j] = er*bm[(i-1),j] * K[j] ;\n }\n\n }\n \n // for loo calcs (pointwise loglikelihoods)\n n=0;\n for (j in 1:U) {\n for (i in 1:N) {\n if ( missing[i,j] == 0 ) {\n n += 1;\n log_lik[n] = normal_lpdf( Y[i,j] | B[i,j], bosd[j] );\n } \n }\n }\n\n }\n \"\n )\n }\n\n\n if (DS==\"stan_surplus_production_2022_model_qc_cauchy_wider\") {\n return( \"\n data {\n\n int N; // no. years\n int U; // no. regions\n int M; // no. years to project\n int ty;\n real er ;\n real eps ;\n vector[U] Ksd;\n vector[U] rsd;\n vector[U] Kmu ;\n vector[U] rmu ;\n vector[U] qmu ;\n vector[U] qsd ;\n matrix[N,U] CAT;\n matrix[N,U] IOA;\n matrix[N,U] missing;\n array[U] int missing_n;\n int missing_ntot;\n }\n\n transformed data {\n int MN;\n int N1;\n int NU;\n int Ndata;\n\n MN = M+N ;\n N1 = N+1;\n NU = N*U;\n Ndata = NU - missing_ntot; \n }\n\n parameters {\n vector [U] K;\n vector [U] r; // biologically should be ~ 1 \n vector [U] q; // multiplicative factor, unlikely to be >200%\n vector [U] qc; // offset .. unlikely to be off by > 50%\n vector [U] bosd; // observation error\n vector [U] bpsd; // process error\n vector [U] rem_sd; // catch error\n vector [U] b0;\n vector [missing_ntot] IOAmissing;\n matrix [M+N,U] bm; // force bm max 1 \n }\n\n transformed parameters {\n matrix[N,U] Y; // index of abundance\n // copy parameters to a new variable (Y) with imputed missing values\n {\n int ii;\n ii = 0;\n for (j in 1:U) {\n for (i in 1:N) {\n Y[i,j] = IOA[i,j] ; // translation of a zscore to a positive internal scale \n if ( missing[i,j] == 1 ) {\n ii = ii+1;\n Y[i,j] = IOAmissing[ii];\n }\n }\n }\n }\n\n }\n\n model {\n\n // -------------------\n // priors for parameters\n K ~ normal( Kmu, Ksd ) ;\n r ~ normal( rmu, rsd ) ;\n b0 ~ normal( 0.5, 0.1 ) ; // starting b prior to first catch event\n bosd ~ cauchy( 0, 0.1 ) ; // slightly informative .. center of mass between (0,1)\n bpsd ~ cauchy( 0, 0.1 ) ;\n\n q ~ normal( qmu, qsd ) ; // i.e., Y:b scaling coeeficient\n qc ~ cauchy( 0, 0.1 ) ; // i.e., Y:b offset constant ; plot(dbeta(seq(0,1,by=0.1), 1, 10 ) )\n\n // -------------------\n // biomass observation model\n // cfanorth(1) and cfasouth(2)\n // This is slightly complicated because a fall / spring survey correction is required:\n // B represents the total fishable biomass available in fishing year y\n // in fall surveys: Btot(t) = Bsurveyed(t) + removals(t)\n // in spring surveys: Btot(t) = Bsurveyed(t) + removals(t-1)\n // spring surveys from 1998 to 2003\n // this is conceptualized in the following time line:\n // '|' == start/end of each new fishing year\n // Sf = Survey in fall\n // Ss = Survey in spring\n // |...(t-2)...|.Ss..(t-1)...|...(t=2004)..Sf.|...(t+1).Sf..|...(t+2)..Sf.|...\n // Cfa 4X -- fall/winter fishery\n // Btot(t) = Bsurveyed(t) + removals(t) ## .. 2018-2019 -> 2018\n\n\n // spring surveys\n for (j in 1:2) {\n ( Y[1, j] / q[j] ) + qc[j] ~ normal( ( ( fmax( bm[1,j] - CAT[1,j]/K[j] , eps) )) , bosd[j] ) ;\n for (i in 2:(ty-1) ){\n ( Y[i, j] / q[j] ) + qc[j] ~ normal( ( ( fmax( bm[i,j] - CAT[i-1,j]/K[j] , eps) )), bosd[j] ) ;\n }\n }\n\n for (i in 1:(ty-1) ){\n ( Y[i, 3] / q[3] ) + qc[3] ~ normal( ( ( fmax( bm[i,3] - CAT[i,3]/K[3] , eps) )) , bosd[3] ) ;\n }\n\n\n // transition year (ty)\n for (j in 1:2) {\n ( Y[ty,j] / q[j] ) + qc[j] ~ normal( ( ( fmax( bm[ty,j] - (CAT[ty-1,j]/K[j] + CAT[ty,j]/K[j] ) / 2.0 , eps) ) ) , bosd[j] ) ; //NENS and SENS\n }\n ( Y[ty,3] / q[3] ) + qc[3] ~ normal( ( ( fmax( bm[ty,3] - CAT[ty,3]/K[3] , eps) ) ) , bosd[3] ) ; //SENS\n\n // fall surveys\n for (j in 1:3) {\n for (i in (ty+1):N) {\n ( Y[i,j] / q[j] ) + qc[j] ~ normal( ( ( fmax( bm[i,j] - CAT[i,j]/K[j] , eps) ) ) , bosd[j] ) ; // fall surveys\n }\n }\n\n // -------------------\n // biomass process model\n // fmax .. force positive value .. initial conditions\n bm[1,] ~ normal( (b0), bpsd ) ;\n\n for (j in 1:U) {\n real o;\n for (i in 2:N) {\n o = r[j] * fmax( 1.0 - bm[i-1,j], eps ) ; \n bm[i,j] ~ normal( ( ( bm[i-1,j] * ( 1.0 + o ) - CAT[i-1,j]/K[j] )), bpsd[j] ) ;\n }\n for (i in N1:MN) {\n o = r[j] * fmax( 1.0 - bm[i-1,j], eps ) ; \n bm[i,j] ~ normal( ( ( bm[i-1,j] * ( 1.0 + o ) - er*bm[(i-1),j] )), bpsd[j] ) ;\n }\n }\n }\n\n generated quantities {\n vector[U] MSY;\n vector[U] BMSY;\n vector[U] FMSY;\n matrix[MN,U] B;\n matrix[MN,U] C;\n matrix[MN,U] F;\n vector[Ndata] log_lik;\n int n;\n\n // -------------------\n // fishing mortality\n // fall fisheries\n\n for (j in 1:U) {\n for (i in 1:N) {\n F[i,j] = -log( fmax( 1.0 - CAT[i,j]/K[j] / bm[i,j], eps) ) ;\n }\n for (i in N1:MN) {\n F[i,j] = -log( fmax( 1.0 - er * bm[i-1,j] / bm[i,j], eps) ) ;\n }\n }\n\n // -------------------\n // parameter estimates for output\n for (j in 1:U) {\n MSY[j] = r[j]* exp(K[j]) / 4 ; // maximum height of of the latent productivity (yield)\n BMSY[j] = exp(K[j])/2 ; // biomass at MSY\n FMSY[j] = 2.0 * MSY[j] / exp(K[j]) ; // fishing mortality at MSY\n }\n\n // recaled estimates\n for (j in 1:U) {\n for(i in 1:N) {\n B[i,j] = bm[i,j] * K[j] - CAT[i,j] ;\n C[i,j] = CAT[i,j] ;\n }\n\n for (i in N1:MN) {\n B[i,j] = (bm[i,j] - er*bm[(i-1),j]) * K[j] ;\n C[i,j] = er*bm[(i-1),j] * K[j] ;\n }\n\n }\n \n // for loo calcs (pointwise loglikelihoods)\n n=0;\n for (j in 1:U) {\n for (i in 1:N) {\n if ( missing[i,j] == 0 ) {\n n += 1;\n log_lik[n] = normal_lpdf( Y[i,j] | B[i,j], bosd[j] );\n } \n }\n }\n\n }\n \"\n )\n }\n\n\n\n\n\n if (DS==\"stan_surplus_production_catch_observation\") {\n return( \"\n data {\n\n int N; // no. years\n int U; // no. regions\n int M; // no. years to project\n int ty;\n real er ;\n real eps ;\n vector[U] Ksd;\n vector[U] rsd;\n vector[U] Kmu ;\n vector[U] rmu ;\n vector[U] qmu ;\n vector[U] qsd ;\n matrix[N,U] CAT;\n matrix[N,U] IOA;\n matrix[N,U] missing;\n array[U] int missing_n;\n int missing_ntot;\n }\n\n transformed data {\n int MN;\n int N1;\n MN = M+N ;\n N1 = N+1;\n }\n\n parameters {\n vector [U] K;\n vector [U] r; // biologically should be ~ 1 \n vector [U] q; // multiplicative factor, unlikely to be >200%\n vector [U] qc; // offset .. unlikely to be off by > 50%\n vector [U] bosd; // observation error\n vector [U] bpsd; // process error\n vector [U] catsd; // catch error\n vector [U] b0;\n vector [missing_ntot] IOAmissing;\n matrix [M+N,U] bm; // force bm max 1 \n matrix [N,U] cat; // estimated catch\n vector [U] catQ; // multiplicative factor .. fraction misreported\n }\n\n transformed parameters {\n \n matrix[N,U] Y; // index of abundance\n // copy parameters to a new variable (Y) with imputed missing values\n {\n int ii;\n ii = 0;\n for (j in 1:U) {\n for (i in 1:N) {\n Y[i,j] = IOA[i,j] ; // translation of a zscore to a positive internal scale \n if ( missing[i,j] == 1 ) {\n ii = ii+1;\n Y[i,j] = IOAmissing[ii];\n }\n }\n }\n }\n\n }\n\n model {\n\n // -------------------\n // priors for parameters\n K ~ normal( Kmu, Ksd ) ;\n r ~ normal( rmu, rsd ) ;\n b0 ~ normal( 0.5, 0.1 ) ; // starting b prior to first catch event\n bosd ~ cauchy( 0, 0.1 ) ; // slightly informative .. center of mass between (0,1)\n bpsd ~ cauchy( 0, 0.1 ) ;\n catsd ~ cauchy( 0, 0.1 ) ;\n catQ ~ beta( 1, 5 ) ;\n\n q ~ normal( qmu, qsd ) ; // i.e., Y:b scaling coeeficient\n qc ~ beta( 1, 5 ) ; // i.e., Y:b offset constant ; plot(dbeta(seq(0,1,by=0.1), 1, 10 ) )\n\n // -------------------\n // biomass observation model\n // cfanorth(1) and cfasouth(2)\n // This is slightly complicated because a fall / spring survey correction is required:\n // B represents the total fishable biomass available in fishing year y\n // in fall surveys: Btot(t) = Bsurveyed(t) + removals(t)\n // in spring surveys: Btot(t) = Bsurveyed(t) + removals(t-1)\n // spring surveys from 1998 to 2003\n // this is conceptualized in the following time line:\n // '|' == start/end of each new fishing year\n // Sf = Survey in fall\n // Ss = Survey in spring\n // |...(t-2)...|.Ss..(t-1)...|...(t=2004)..Sf.|...(t+1).Sf..|...(t+2)..Sf.|...\n // Cfa 4X -- fall/winter fishery\n // Btot(t) = Bsurveyed(t) + removals(t) ## .. 2018-2019 -> 2018\n\n\n // catch observation model -- cat = CAT/K *catQ\n // spring surveys\n for (j in 1:2) {\n ( CAT[1,j]/K[j] ) * (1.0 + catQ[j]) ~ normal( cat[1,j], catsd[j] ); \n for (i in 2:(ty-1) ){\n ( CAT[i-1,j]/K[j] ) * (1.0 + catQ[j]) ~ normal( cat[i-1,j], catsd[j] ); \n }\n }\n for (i in 1:(ty-1) ){\n ( CAT[i,3]/K[3] ) * (1.0 + catQ[3]) ~ normal( cat[i,3], catsd[3] ); \n }\n // transition year (ty)\n for (j in 1:2) {\n ( CAT[ty-1,j] + CAT[ty,j] ) / ( 2.0* K[j] ) * (1.0 + catQ[j]) ~ normal( cat[ty,j], catsd[j] ); \n }\n ( CAT[ty,3] / K[3] ) * (1.0 + catQ[3]) ~ normal( cat[ty,3], catsd[3] ); \n\n // fall surveys\n for (j in 1:3) {\n for (i in (ty+1):N) {\n ( CAT[i,j]/K[j] ) * (1.0 + catQ[j]) ~ normal( cat[i,j], catsd[j] ); \n }\n }\n\n // biomass observation model \n // spring surveys\n for (j in 1:2) {\n ( Y[1, j] / q[j] ) + qc[j] ~ normal( ( ( fmax( bm[1,j] - cat[1,j], eps) )) , bosd[j] ) ;\n for (i in 2:(ty-1) ){\n ( Y[i, j] / q[j] ) + qc[j] ~ normal( ( ( fmax( bm[i,j] - cat[i-1,j], eps) )), bosd[j] ) ;\n }\n }\n for (i in 1:(ty-1) ){\n ( Y[i, 3] / q[3] ) + qc[3] ~ normal( ( ( fmax( bm[i,3] - cat[i,3], eps) )) , bosd[3] ) ;\n }\n\n // transition year (ty)\n for (j in 1:3) {\n ( Y[ty,j] / q[j] ) + qc[j] ~ normal( ( ( fmax( bm[ty,j] - cat[ty,j], eps) ) ) , bosd[j] ) ; \n }\n // fall surveys\n for (j in 1:3) {\n for (i in (ty+1):N) {\n ( Y[i,j] / q[j] ) + qc[j] ~ normal( ( ( fmax( bm[i,j] - cat[i,j], eps) ) ), bosd[j] ) ; // fall surveys\n }\n }\n\n\n // -------------------\n // biomass process model\n // fmax .. force positive value .. initial conditions\n bm[1,] ~ normal( (b0), bpsd ) ;\n\n for (j in 1:U) {\n real o;\n for (i in 2:N) {\n o = r[j] * fmax( 1.0 - bm[i-1,j], eps ) ; \n bm[i,j] ~ normal( ( ( bm[i-1,j] * ( 1.0 + o ) - cat[i-1,j] )), bpsd[j] ) ;\n }\n for (i in N1:MN) {\n o = r[j] * fmax( 1.0 - bm[i-1,j], eps ) ; \n bm[i,j] ~ normal( ( ( bm[i-1,j] * ( 1.0 + o ) - er*bm[(i-1),j] )), bpsd[j] ) ;\n }\n }\n }\n\n generated quantities {\n vector[U] MSY;\n vector[U] BMSY;\n vector[U] FMSY;\n matrix[MN,U] B;\n matrix[MN,U] C;\n matrix[MN,U] F;\n\n // -------------------\n // fishing mortality\n // fall fisheries\n\n for (j in 1:U) {\n for (i in 1:N) {\n F[i,j] = -log( fmax( 1.0 - CAT[i,j]/K[j] / bm[i,j], eps) ) ;\n }\n for (i in N1:MN) {\n F[i,j] = -log( fmax( 1.0 - er * bm[i-1,j] / bm[i,j], eps) ) ;\n }\n }\n\n \n // -------------------\n // parameter estimates for output\n for (j in 1:U) {\n MSY[j] = r[j]* exp(K[j]) / 4 ; // maximum height of of the latent productivity (yield)\n BMSY[j] = exp(K[j])/2 ; // biomass at MSY\n FMSY[j] = 2.0 * MSY[j] / exp(K[j]) ; // fishing mortality at MSY\n }\n\n // recaled estimates\n for (j in 1:U) {\n for(i in 1:N) {\n B[i,j] = bm[i,j] * K[j] - CAT[i,j] ;\n C[i,j] = CAT[i,j] ;\n }\n\n for (i in N1:MN) {\n B[i,j] = (bm[i,j] - er*bm[(i-1),j]) * K[j] ;\n C[i,j] = er*bm[(i-1),j] * K[j] ;\n }\n\n }\n\n }\n \"\n )\n }\n\n\n\n if (DS==\"stan_surplus_production_2020\") {\n return( \"\n data {\n int N; // no. years\n int U; // no. regions\n int M; // no. years to project\n int ty;\n real er ;\n real eps ;\n vector[U] Ksd;\n vector[U] rsd;\n vector[U] qsd;\n vector[U] Kmu ;\n vector[U] rmu ;\n vector[U] qmu ;\n matrix[N,U] CAT;\n matrix[N,U] IOA;\n matrix[N,U] missing;\n array[U] int missing_n;\n int missing_ntot;\n }\n transformed data {\n int MN;\n int N1;\n MN = M+N ;\n N1 = N+1;\n }\n parameters {\n vector [U] K;\n vector [U] r;\n vector [U] q;\n vector [U] qs;\n vector [U] bosd; // observation error\n vector [U] bpsd; // process error\n vector [U] b0;\n vector [missing_ntot] IOAmissing;\n matrix [M+N,U] bm;\n }\n transformed parameters {\n matrix[N,U] Y; // index of abundance\n matrix[N,U] Ymu; // collator used to force positive values for lognormal\n matrix[MN,U] bmmu; // collator used to force positive values for lognormal\n matrix[MN,U] rem; // observed catch\n // copy parameters to a new variable (Y) with imputed missing values\n {\n int ii;\n ii = 0;\n for (j in 1:U) {\n for (i in 1:N) {\n Y[i,j] = IOA[i,j];\n if ( missing[i,j] == 1 ) {\n ii = ii+1;\n Y[i,j] = IOAmissing[ii];\n }\n }\n }\n }\n // -------------------\n // removals (catch) observation model, standardized to K (assuming no errors in observation of catch!)\n for (j in 1:U) {\n rem[1:N,j] = CAT[1:N,j]/K[j] ;\n rem[(N+1):MN,j] = er*bm[ N:(MN-1),j] ; // forecasts\n }\n // -------------------\n // observation model calcs and contraints:\n // Ymu = 'surveyed/observed' residual biomass at time of survey (Bsurveyed)\n // cfanorth(1) and cfasouth(2)\n // This is slightly complicated because a fall / spring survey correction is required:\n // B represents the total fishable biomass available in fishing year y\n // in fall surveys: Btot(t) = Bsurveyed(t) + removals(t)\n // in spring surveys: Btot(t) = Bsurveyed(t) + removals(t-1)\n // spring surveys from 1998 to 2003\n // this is conceptualized in the following time line:\n // '|' == start/end of each new fishing year\n // Sf = Survey in fall\n // Ss = Survey in spring\n // |...(t-2)...|.Ss..(t-1)...|...(t=2004)..Sf.|...(t+1).Sf..|...(t+2)..Sf.|...\n // Cfa 4X -- fall/winter fishery\n // Btot(t) = Bsurveyed(t) + removals(t) ## .. 2018-2019 -> 2018\n for (j in 1:2) {\n Ymu[1,j] = qs[j] * bm[1,j] - rem[1,j] ; // starting year approximation\n Ymu[2:(ty-1),j] = qs[j] * bm[2:(ty-1),j] - rem[1:(ty-2),j] ; //spring surveys\n Ymu[ty,j] = q[j] * bm[ty,j] - (rem[(ty-1),j] + rem[ty,j] )/2.0 ; // transition year .. approximation\n Ymu[(ty+1):N,j] = q[j] * bm[(ty+1):N,j] - rem[(ty+1):N,j] ; // fall surveys\n }\n {\n int k;\n k=3;\n Ymu[1,k] = q[k] * bm[1,k] - rem[1,k] ; // starting year approximation ymu[1991] = bm[1991]-rem[1991]\n Ymu[2:(ty-1),k] = q[k] * bm[2:(ty-1),k] - rem[2:(ty-1),k];\n Ymu[ty:N,k] = q[k] * bm[ty:N,k] - rem[ty:N,k];\n }\n for (j in 1:U) {\n for (i in 1:N) {\n Ymu[i,j] = K[j] * fmax( Ymu[i,j], eps); // force positive value\n }\n }\n // -------------------\n // process model calcs and constraints\n for (j in 1:U) {\n bmmu[1,j] = b0[j] ; // biomass at first year\n for (i in 2:MN) {\n bmmu[i,j] = bm[i-1,j] * ( 1.0 + r[j]*(1-bm[i-1,j]) ) - rem[i-1,j] ;\n }\n }\n for (j in 1:U) {\n for (i in 1:MN) {\n bmmu[i,j] = fmax(bmmu[i,j], eps); // force positive value\n }\n }\n }\n model {\n // -------------------\n // priors for parameters\n K ~ normal( Kmu, Ksd ) ;\n r ~ normal( rmu, rsd ) ;\n q ~ normal( qmu, qsd ) ;\n qs ~ normal( qmu, qsd ) ;\n b0 ~ beta( 8, 2 ) ; // starting b prior to first catch event\n bosd ~ cauchy( 0, 0.1 ) ; // slightly informative .. center of mass between (0,1)\n bpsd ~ cauchy( 0, 0.1 ) ;\n // -------------------\n // biomass observation model\n for (j in 1:U) {\n log(Y[1:N,j]) ~ normal( log(Ymu[1:N,j]), bosd[j] ) ; // stan thinks Y is being transformed due to attempt to impute missing values .. ignore\n }\n // -------------------\n // biomass process model\n for (j in 1:U) {\n log(bm[1:MN,j]) ~ normal( log(bmmu[1:MN,j]), bpsd[j] ) ;\n }\n // could have used lognormal but this parameterization is 10X faster and more stable\n target += - log(fabs(Y)); // required due to log transf above\n target += - log(fabs(bm));\n }\n generated quantities {\n vector[U] MSY;\n vector[U] BMSY;\n vector[U] FMSY;\n matrix[MN,U] B;\n matrix[MN,U] C;\n matrix[MN,U] F;\n matrix[M,U] TAC;\n // -------------------\n // fishing mortality\n // fall fisheries\n for (j in 1:3) {\n for (i in 1:N) {\n F[i,j] = 1.0 - rem[i,j] / bm[i,j] ;\n }\n }\n for (j in 1:U) {\n for (i in N1:MN) {\n F[i,j] = 1.0 - er * bm[i-1,j] / bm[i,j] ;\n }\n for (i in 1:MN) {\n F[i,j] = -log( fmax( F[i,j], eps) ) ;\n }\n }\n // -------------------\n // parameter estimates for output\n for(j in 1:U) {\n MSY[j] = r[j]* exp(K[j]) / 4 ; // maximum height of of the latent productivity (yield)\n BMSY[j] = exp(K[j])/2 ; // biomass at MSY\n FMSY[j] = 2.0 * MSY[j] / exp(K[j]) ; // fishing mortality at MSY\n }\n // recaled estimates\n for(j in 1:U) {\n for(i in 1:MN) {\n B[i,j] = (bm[i,j] - rem[i,j]) * K[j] ;\n C[i,j] = rem[i,j]*K[j] ;\n }\n for(i in 1:M) {\n TAC[i,j] = rem[N+i,j]*K[j] ;\n }\n }\n }\n \"\n )\n }\n\n\n\n\n if (DS==\"data_aggregated_timeseries\" ) {\n\n cfanorth = 1 # column index\n cfasouth = 2 # column index\n cfa4x = 3 # column index\n\n landings = bio.snowcrab::snowcrab_landings_db()\n # NOTE:: message( \"Fishing 'yr' for CFA 4X has been set to starting year:: 2001-2002 -> 2001, etc.\")\n # year is year of capture\n # yr is \"fishing year\" relative to the assessment cycle\n landings = landings[ which (landings$cfa %in% c( \"cfanorth\", \"cfasouth\", \"cfa4x\" ) ) , ]\n L = tapply( landings$landings, INDEX=landings[,c(\"yr\", \"cfa\")], FUN=sum, na.rm=T )\n nL = nrow(L)\n\n cfaall = tapply( landings$landings, INDEX=landings[,c(\"yr\")], FUN=sum, na.rm=T )\n L = cbind( L, cfaall )\n L = L / 1000/1000 # convert to kt pN$fishery_model_label = \"stan_surplus_production_2022_model_qc_cauchy\"\n L[ !is.finite(L)] = 0\n\n L = as.data.frame( L[ match( p$yrs, rownames(L) ), areas ] )\n\n # biomass data: post-fishery biomass are determined by survey B)\n B = aggregate_biomass_from_simulations( fn=carstm_filenames( p, returnvalue=\"filename\", fn=\"aggregated_timeseries\" ) )$RES\n\n rownames(B) = B$yrs\n B = as.data.frame( B[ match( p$yrs, B$yrs ), areas ] )\n\n # cfa4x have had no estimates prior to 2004\n\n cfanorth.baddata = which( p$yrs <= 2004 )\n# B[ cfanorth.baddata, cfanorth ] = NA\n\n cfasouth.baddata = which( p$yrs <= 2004 )\n# B[ cfasouth.baddata, cfasouth ] = NA\n\n cfa.nodata = which( p$yrs <= 2004 )\n B[ cfa.nodata , cfa4x ] = NA\n\n sb = list(\n IOA = as.matrix(B), # observed index of abundance\n CAT = as.matrix(L) # catches , assume 20% handling mortality and illegal landings\n )\n\n return(sb)\n }\n\n\n \n if (DS==\"logistic_model\" ) {\n\n message( \"Output location is: \", p$fishery_model$outdir )\n dir.create( p$fishery_model$outdir, recursive=T, showWarnings=F )\n\n\n if (is.null(fit)) {\n p$fishery_model$stancode$compile()\n fit = p$fishery_model$stancode$sample( ... )\n }\n\n if (0) {\n # Posterior summary statistics .. the $sample() method creates R6 CmdStanMCMC objects,\n fit$summary() # summarise_draws() from posterior package\n fit$summary(\"K\", \"r\", \"q\")\n\n # this is a draws_array object from the posterior package\n # str(fit$sampler_diagnostics())\n\n diagnostics_df = as_draws_df(fit$sampler_diagnostics())\n print(diagnostics_df)\n\n fit$cmdstan_diagnose()\n fit$cmdstan_summary()\n\n # Posterior draws .. $draws() a 3-D array (iteration x chain x variable)\n draws_array = fit$draws()\n str(draws_array)\n\n draws_df = as_draws_df(draws_array) # as_draws_matrix() for matrix\n print(draws_df)\n\n }\n\n fit$save_object( file = p$fishery_model$fnfit ) # save this way due to R-lazy loading; RDS file\n\n res = list( mcmc=stan_extract( as_draws_df(fit$draws() ) ), p=p )\n\n saveRDS(res, file=p$fishery_model$fnres, compress=TRUE)\n\n return(res)\n }\n\n\n\n if (DS==\"samples\" ) {\n res = NULL\n if (file.exists(p$fishery_model$fnres)) res = readRDS(p$fishery_model$fnres)\n return(res)\n }\n\n\n if (DS==\"fit\" ) {\n fit = NULL\n if (file.exists(p$fishery_model$fnfit)) fit = readRDS(p$fishery_model$fnfit)\n return(fit)\n }\n\n\n if (DS==\"plot\") {\n\n y = res$mcmc\n sb= res$p$fishery_model$standata\n \n if (is.null(fn)) {\n outdir = pN$fishery_model$outdir \n } else{\n outdir = dirname(fn)\n }\n\n ntacs = sb$nProj\n yrs0 = res$p$yrs\n yrs = c( yrs0, (max(yrs0)+c(1:sb$M) ) )\n yrs.last = max(yrs0) + 0.5\n ndata = length(yrs0)\n hdat = 1:ndata\n\n\n if (vname ==\"r.ts\") {\n # catch this first as the layout is different\n if (is.null(fn)) fn=file.path(outdir, \"r.ts.density.png\" )\n\n br = 75\n\n plot.new()\n layout( matrix(c(1:(sb$N*3)), ncol=3, nrow=sb$N ))\n par(mar = c(1., 1., 0.65, 0.75))\n\n u = apply( y[[\"r\"]], c(2, 3), median, na.rm=T )\n\n for (i in 1:3) {\n for (yr in 1:sb$N) {\n qs = apply( u, 2, quantile, probs=c(0.025, 0.5, 0.975) )\n qs = signif( qs, 3 )\n pdat = u[ yr,i ]\n xrange = range( pdat, na.rm=T )\n postdat = hist( pdat, breaks=br, plot=FALSE )\n yrange = range( 0, postdat$density, na.rm=T ) * 1.02\n hist( pdat, freq=FALSE, breaks=br, xlim=xrange, ylim=yrange, main=\"\", xlab=\"\", ylab=\"Density\", col=\"lightgray\", border=\"gray\")\n YR = rownames(sb$IOA) [yr]\n legend( \"topright\", bty=\"n\", legend=paste( aulabels[i], YR, \"r\", \" = \", qs[2,i], \" {\", qs[1,i], \", \", qs[3,i], \"} \", sep=\"\" ), cex=0.9 )\n }}\n\n if (save.plot) savePlot( filename=fn, type=\"png\" )\n return( fn)\n\n }\n\n\n plot.new()\n layout( matrix(c(1,2,3), 3, 1 ))\n par(mar = c(4.4, 4.4, 0.65, 0.75))\n\n prr = NULL\n prr$class =\"none\" # no priors by default\n\n\n if ( type==\"density\" ) { # default\n\n if ( vname==\"K\" ) {\n \n if (is.null(fn)) fn=file.path(outdir, \"K.density.png\" )\n u = y[[vname]]\n\n qs = apply( u, 2, quantile, probs=c(0.025, 0.5, 0.975) )\n qs = signif( qs, 3 )\n for (i in 1:3) {\n pdat = u[,i]\n prr=NULL\n prr$class=\"normal\"\n\n # E(X) = exp(mu + 1/2 sigma^2)\n # med(X) = exp(mu)\n # Var(X) = exp(2*mu + sigma^2)*(exp(sigma^2) - 1)\n # CV = sqrt( Var(X) ) / E(X) = sqrt(exp(sigma^2) - 1) ~ sigma; sigma < 1/2\n # SD(X) = sqrt( exp(2*mu + sigma^2)*(exp(sigma^2) - 1) )\n # or = CV * E(X)\n\n prr$mean= sb$Kmu[i]\n prr$sd = sb$Ksd[i]\n plot.freq.distribution.prior.posterior( prior=prr, posterior=pdat, ... )\n\n legend( \"topright\", bty=\"n\", legend=paste( aulabels[i], \"\\n\", vname, \" = \", qs[2,i], \" {\", qs[1,i], \", \", qs[3,i], \"} \", sep=\"\" ))\n }\n }\n\n if ( vname==\"r\" ) {\n if (is.null(fn)) fn=file.path(outdir, \"r.density.png\" )\n\n u = y[[vname]]\n qs = apply( u, 2, quantile, probs=c(0.025, 0.5, 0.975) )\n qs = signif( qs, 3 )\n for (i in 1:3) { prr=NULL\n prr=NULL\n prr$class='normal'\n prr$mean=sb$rmu[i]\n prr$sd= sb$rsd[i]\n pdat = u[,i]\n plot.freq.distribution.prior.posterior( prior=prr, posterior=pdat, ... )\n legend( \"topright\", bty=\"n\", legend=paste( aulabels[i], \"\\n\", vname, \" = \", qs[2,i], \" {\", qs[1,i], \", \", qs[3,i], \"} \", sep=\"\" ) )\n }}\n\n\n\n if ( vname==\"q\" ) {\n if (is.null(fn)) fn=file.path(outdir, \"q.density.png\" )\n\n u = y[[vname]]\n qs = apply( u, 2, quantile, probs=c(0.025, 0.5, 0.975) )\n qs = signif( qs, 3 )\n for (i in 1:3) {\n pdat = u[,i]\n prr=NULL\n prr$class=\"normal\"\n prr$mean=sb$qmu[i]\n prr$sd=sb$qsd[i]\n plot.freq.distribution.prior.posterior( prior=prr, posterior=pdat, ... )\n legend( \"topright\", bty=\"n\", legend=paste( aulabels[i], \"\\n\", vname, \" = \", qs[2,i], \" {\", qs[1,i], \", \", qs[3,i], \"} \", sep=\"\" )\n )}}\n\n\n if ( vname==\"qc\" ) {\n if (is.null(fn)) fn=file.path(outdir, \"qc.density.png\" )\n u = y[[vname]]\n qc = apply( u, 2, quantile, probs=c(0.025, 0.5, 0.975) )\n for (i in 1:3) {\n pdat = u[,i]\n prr=NULL\n prr$class=\"cauchy\"\n prr$a = 0\n prr$b = 0.1\n plot.freq.distribution.prior.posterior( prior=prr, posterior=pdat, ... )\n legend( \"topright\", bty=\"n\", legend=paste( aulabels[i], \"\\n\", vname, \" = \", qc[2,i], \" {\", qc[1,i], \", \", qc[3,i], \"} \", sep=\"\" )\n )}}\n\n\n if ( vname==\"qs\" ) {\n if (is.null(fn)) fn=file.path(outdir, \"qs.density.png\" )\n u = y[[vname]]\n qs = apply( u, 2, quantile, probs=c(0.025, 0.5, 0.975) )\n for (i in 1:3) {\n pdat = u[,i]\n # prr=NULL\n # prr$class=\"normal\"\n # prr$mean=sb$q0x[i]\n # prr$sd=sb$q0x[i]*sb$cv\n plot.freq.distribution.prior.posterior( prior=prr, posterior=pdat, ... )\n legend( \"topright\", bty=\"n\", legend=paste( aulabels[i], \"\\n\", vname, \" = \", qs[2,i], \" {\", qs[1,i], \", \", qs[3,i], \"} \", sep=\"\" )\n )}}\n\n\n if ( vname==\"BMSY\" ) {\n if (is.null(fn)) fn=file.path(outdir, \"BMSY.density.png\" )\n u = y[[vname]]\n qs = apply( u, 2, quantile, probs=c(0.025, 0.5, 0.975) )\n qs = signif( qs, 3 )\n for (i in 1:3) {\n pdat = u[,i]\n prr=NULL\n prr$class=\"none\"\n plot.freq.distribution.prior.posterior( prior=prr, posterior=pdat, ... )\n legend( \"topright\", bty=\"n\",\n legend=paste( aulabels[i], \" \", vname, \" = \", qs[2,i], \" {\", qs[1,i], \", \", qs[3,i], \"}\", sep=\"\" )\n )}}\n\n if ( vname==\"FMSY\" ) {\n if (is.null(fn)) fn=file.path(outdir, \"FMSY.density.png\" )\n u = y[[vname]]\n qs = apply( u, 2, quantile, probs=c(0.025, 0.5, 0.975) )\n qs = signif( qs, 3 )\n for (i in 1:3) {\n pdat = u[,i]\n prr=NULL\n prr$class=\"none\"\n plot.freq.distribution.prior.posterior( prior=prr, posterior=pdat, ... )\n legend( \"topright\", bty=\"n\",\n legend=paste( aulabels[i], \" \", vname, \" = \", qs[2,i], \" {\", qs[1,i], \", \", qs[3,i], \"}\", sep=\"\" )\n )}}\n\n\n if ( vname==\"bosd\" ) {\n if (is.null(fn)) fn=file.path(outdir, \"bosd.density.png\" )\n u = y[[vname]]\n qs = apply( u, 2, quantile, probs=c(0.025, 0.5, 0.975) )\n qs = signif( qs, 3 )\n for (i in 1:3) {\n pdat = u[,i]\n prr=NULL\n prr$class='uniform'\n prr$max=3\n prr$min=0\n #prr$class=\"lognormal\"\n #prr$meanlog=sb$bomup\n #prr$sdlog=sqrt(sb$bosdp)\n plot.freq.distribution.prior.posterior( prior=prr, posterior=pdat, ... )\n legend( \"topright\", bty=\"n\",\n legend=paste( aulabels[i], \" \", vname, \" = \", qs[2,i], \" {\", qs[1,i], \", \", qs[3,i], \"}\", sep=\"\" )\n )}}\n\n if ( vname==\"bpsd\" ) {\n if (is.null(fn)) fn=file.path(outdir, \"bpsd.density.png\" )\n u = y[[vname]]\n qs = apply( u, 2, quantile, probs=c(0.025, 0.5, 0.975) )\n qs = signif( qs, 3 )\n for (i in 1:3) {\n pdat = u[,i]\n prr=NULL\n prr$class='uniform'\n prr$max=3\n prr$min=0\n #prr$class=\"lognormal\"\n #prr$meanlog=sb$bpmup\n #prr$sdlog=sqrt(sb$bpsdp)\n plot.freq.distribution.prior.posterior( prior=prr, posterior=pdat, ... )\n legend( \"topright\", bty=\"n\",\n legend=paste( aulabels[i], \" \", vname, \" = \", qs[2,i], \" {\", qs[1,i], \", \", qs[3,i], \"}\", sep=\"\" )\n )}}\n\n\n }\n\n # --------------\n\n if ( type==\"timeseries\" ) {\n\n plot.new()\n layout( matrix(c(1,2,3), 3, 1 ))\n par(mar = c(4.4, 4.4, 0.65, 0.75))\n\n if (vname==\"biomass\") {\n \n if (is.null(fn)) fn=file.path(outdir, \"biomass.timeseries.png\" )\n\n u = y[[\"B\"]]\n\n for (i in 1:3) {\n meanval = apply( u[,1:sb$N,i], 2, mean, na.rm=T )\n\n prs = seq( from=0.025, to=0.975, length.out=600)\n Bq = apply( u[,1:sb$N,i], 2, quantile, probs=prs, na.rm=T )\n\n #yran = range(c(0, Bq, sb$IOA[,i] ), na.rm=T )*1.01\n yran = range(c(0, Bq ), na.rm=T )*1.01\n plot( yrs0, Bq[1,], type=\"n\", ylim=yran, xlim=range(yrs0), xlab=\"\", ylab=\"\" ) #change xlim to yrs0 to remove 3 yr projection\n cols = gray.colors( floor(length( prs)/2) )\n cols2 = c(cols[length(cols):1], cols )\n for ( j in 1:length(prs) ) {\n lines ( yrs0, Bq[j,], lwd=4, col=cols2[j] )\n }\n # lines( yrs0, B, lwd=3, col=\"darkgreen\" )\n #abline (v=yrs.last , lwd=2, lty=\"dashed\" ) #can comment out this line if not providing forward projection\n if (i==2) title( ylab=\"Fishable biomass (kt)\" )\n if (i==3) title( xlab=\"Year\" )\n #points( yrs0, qIOA, pch=20, col=\"darkgreen\" )\n #lines ( yrs0, qIOA, lwd=3, col=\"darkgreen\", lty=\"dashed\" )\n lines ( yrs0, meanval, lwd=2, col=\"blue\", lty=\"dotted\" )\n #points( yrs0, IOA, pch=20, col=\"darkred\" )\n #lines( yrs0, IOA, lwd=3, lty=\"dotdash\", col=\"red\" )\n # legend( \"topright\", bty=\"n\", legend=aulabels[i])\n }\n }\n\n if (vname==\"rem\") {\n\n if (is.null(fn)) fn=file.path(outdir, \"rem.timeseries.png\" ) \n \n u = y[[vname]]\n\n for (i in 1:3) {\n meanval = apply( u[,,i], 2, mean, na.rm=T )\n\n prs = seq( from=0.025, to=0.975, length.out=600)\n Bq = apply( u[,,i], 2, quantile, probs=prs, na.rm=T )\n\n #yran = range(c(0, Bq, sb$IOA[,i] ), na.rm=T )*1.01\n yran = range(c(0, Bq ), na.rm=T )*1.01\n plot( yrs, Bq[1,], type=\"n\", ylim=yran, xlim=range(yrs0), xlab=\"\", ylab=\"\" ) #change xlim to yrs0 to remove 3 yr projection\n cols = gray.colors( floor(length( prs)/2) )\n cols2 = c(cols[length(cols):1], cols )\n for ( j in 1:length(prs) ) {\n lines ( yrs, Bq[j,], lwd=4, col=cols2[j] )\n }\n # lines( yrs, rem, lwd=3, col=\"darkgreen\" )\n #abline (v=yrs.last , lwd=2, lty=\"dashed\" ) #can comment out this line if not providing forward projection\n if (i==2) title( ylab=\"Fishable biomass (kt)\" )\n if (i==3) title( xlab=\"Year\" )\n #points( yrs0, qIOA, pch=20, col=\"darkgreen\" )\n #lines ( yrs0, qIOA, lwd=3, col=\"darkgreen\", lty=\"dashed\" )\n lines ( yrs, meanval, lwd=2, col=\"blue\", lty=\"dotted\" )\n #points( yrs0, IOA, pch=20, col=\"darkred\" )\n #lines( yrs0, IOA, lwd=3, lty=\"dotdash\", col=\"red\" )\n legend( \"topright\", bty=\"n\", legend=aulabels[i])\n }\n }\n\n if (vname==\"fishingmortality\") {\n\n if (is.null(fn)) fn=file.path(outdir, \"fishingmortality.timeseries.png\" ) \n\n Fmsy = apply( y[[\"FMSY\"]], 2, mean, na.rm=T )\n \n prs = seq( from=0.025, to=0.975, length.out=600)\n\n F = y[[\"F\"]]\n \n Fi = apply( F[, 1:sb$N, ] , c(2,3), quantile, probs=prs, na.rm=T )\n \n for (i in 1:3) {\n yran = range(c(0, max(c(Fi,Fmsy))), na.rm=T )*1.05\n yran = pmin( yran, 1.2 )\n plot( yrs0, Fi[1,,i], type=\"n\", ylim=yran, xlab=\"\", ylab=\"\" )\n cols = gray.colors( floor(length( prs)/2) )\n cols2 = c(cols[length(cols):1], cols )\n if (i %in% c(1,2)){\n for ( j in 1:length(prs) ) {\n lines ( yrs0, Fi[j,,i], lwd=4, col=cols2[j] )\n }}\n if (i==3){\n for ( j in 1:length(prs) ) {\n lines ( yrs0-0.2, Fi[j,,i], lwd=4, col=cols2[j] )\n }}\n if (i==2) title( ylab=\"Fishing mortality\" )\n if (i==3) title( xlab=\"Year\" )\n # legend( \"topright\", bty=\"n\", legend=aulabels[i])\n abline (h=-log(1-0.2), lwd=2, lty=\"dashed\" )\n abline (h=Fmsy[i], lwd=2, lty=\"solid\", col=\"red\" )\n }\n }\n\n }\n\n if (type==\"hcr\") {\n if (vname==\"default\") {\n\n if (is.null(fn)) fn=file.path(outdir, \"hcr.default.png\" )\n \n B = apply( y[[\"B\"]], c(2,3), median, na.rm=T )\n F = apply( y[[\"F\"]], c(2,3), median, na.rm=T )\n K = apply( y[[\"K\"]], c(2), median, na.rm=T )\n FMSY = apply( y[[\"FMSY\"]], c(2), median, na.rm=T )\n BMSY = apply( y[[\"BMSY\"]], c(2), median, na.rm=T )\n\n for (i in 1:3 ) {\n ylims = c(0, min( 1, max( FMSY[i] * 1.25, F[hdat,i] ) ) )\n plot( B[hdat,i], F[hdat,i], type=\"b\", xlim=c(0, K[i] * 1.1 ),\n ylim=ylims, col=\"darkorange\", cex=0.8, lwd=2, xlab=\"\", ylab=\"\", pch=20 )\n\n\n # nn = as.matrix( cbind( Bx=as.vector( y$B[,ndata,i] ), Fx = as.vector( y$F[,ndata,i] ) ))\n # ellipse.2d(nn[,1], nn[,2], pv=0.05, sc=30)\n\n if (i==3) title( xlab=\"Fishable biomass (kt)\" )\n if (i==2) title( ylab=\"Fishing mortality\" )\n\n F30 = -log(1-0.3)\n F10 = -log(1-0.1)\n\n Fref = 0.22\n Bmsy = K[i] * 0.5\n Bref = K[i] * 0.2\n BK = K[i]\n BK25 = K[i] * .25\n Fhistorical = mean( F[hdat,i], na.rm=T )\n Bhistorical = mean( B[hdat,i], na.rm=T )\n yl = 0.05\n\n polygon(x=c(Bmsy,Bmsy*2,Bmsy*2, Bmsy),y=c(-0.08,-0.1,FMSY[i],FMSY[i]),col='lightgreen',border=NA)\n polygon(x=c(Bmsy/2,Bmsy,Bmsy, Bmsy/2),y=c(-0.08,-0.1,FMSY[i],FMSY[i]),col='lightgoldenrod',border=NA)\n polygon(x=c(0,Bmsy/2,Bmsy/2, 0),y=c(-0.08,-0.1,FMSY[i],FMSY[i]),col='darksalmon',border=NA)\n\n#might need adjustment below to offset F vs B. Need to plot F against PREfishery biomass\n lines( B[hdat,i], F[hdat,i], type=\"b\", xlim=c(0, K[i] * 1.1 ),\n ylim=ylims, col='blue', cex=0.8, lwd=2, xlab=\"\", ylab=\"\", pch=20 )\n\n abline (h=Fref, lty=\"solid\", col=\"gray\", lwd=2 )\n\n abline (h=F10, lty=\"dotted\", col=\"gray\")\n # text( 0.05*K[i], F10, \"10% HR\", pos=1 )\n\n abline (h=F30, lty=\"dotted\", col=\"gray\")\n # text( 0.05*K[i], F30, \"30% HR\", pos=1 )\n\n\n abline (h=FMSY[i], lty=\"dashed\", col=\"red\" )\n\n # abline (h=Fhistorical, lty=\"dashed\")\n # text( 0.05*K[i], Fhistorical, \"Mean\", pos=1, lwd=2 )\n\n # abline (v=Bref, lty=\"dotted\")\n # text( Bref-0.2, 0.25, \"Lower biomass reference point\\n (LBRP = 0.2 * BMSY)\" , srt=90, pos=3)\n\n abline (v=Bmsy, lty=\"dotted\")\n\n abline (v=BK, lty=\"dotted\")\n\n abline (v=BK25, lty=\"dotted\")\n\n text( Bmsy-0.01*K[i], yl, \"K/2\" , srt=90, pos=3)\n text( BK-0.01*K[i], yl, \"K\" , srt=90, pos=3)\n text( BK25-0.01*K[i], yl, \"K/4\" , srt=90, pos=3)\n text( 0.05*K[i], Fref, \"20% HR\", pos=1 )\n text( 0.05*K[i], FMSY[i], \"FMSY\", pos=3, lwd=2, col=\"red\" )\n if (i %in% c(1,2)){\n text( B[1:(ndata-1),i], F[1:(ndata-1),i], labels=yrs0[-ndata], pos=3, cex= 0.8 )\n points( B[ndata,i], F[ndata,i], pch=21, bg='darkorange', cex= 1.4 )\n text( B[ndata,i], F[ndata,i], labels=yrs0[ndata], pos=3, cex= 1.4, font=2 )\n\n text( 0, ylims[2]*0.9, labels=aulabels[i], pos=3, cex= 0.85 )\n }\n if (i==3){\n text( B[1:(ndata-1),i], F[1:(ndata-1),i], labels=(yrs0[-ndata]), pos=3, cex= 0.8 )\n points( B[ndata,i], F[ndata,i], pch=21, bg='darkorange', cex= 1.4 )\n text( B[ndata,i], F[ndata,i], labels=yrs0[ndata], pos=3, cex= 1.4, font=2 )\n text( 0, ylims[2]*0.9, labels=aulabels[i], pos=3, cex= 0.85 )\n }\n # abline (v=Bhistorical, lty=\"dashed\")\n # text( Bhistorical-0.01*K[i], yl, \"Mean\" , srt=90, pos=3, lwd=2)\n }\n #Enable below to see the annual F estimates for inclusion in the document\n print(\"F for N-ENS\" )\n print(F[hdat,1] )\n print(\"F for S-ENS\" )\n print(F[hdat,2] )\n print(\"F for 4X\" )\n print(F[hdat,3] )\n\n\n\n }\n\n if (vname==\"default.unmodelled\") {\n\n if (is.null(fn)) fn=file.path(outdir, \"hcr.default.unmodelled.png\" )\n\n\n B = sb$IOA\n F = apply( y[[\"F\"]], c(2,3), median, na.rm=T )\n\n areas = c(\"cfa4x\", \"cfasouth\", \"cfanorth\" )\n regions = c(\"4X\", \"S-ENS\", \"N-ENS\")\n\n td = exploitationrates(p=p, areas=areas, labels=regions, CFA4X.exclude.year.assessment=FALSE )\n\n\n K = apply( y[[\"K\"]], c(2), median, na.rm=T )\n FMSY = apply( y[[\"FMSY\"]], c(2), median, na.rm=T )\n BMSY = apply( y[[\"BMSY\"]], c(2), median, na.rm=T )\n\n for (i in 1:3 ) {\n ylims = c(0, FMSY[i] * 1.25)\n plot( B[hdat,i], F[hdat,i], type=\"b\", xlim=c(0, K[i] * 1.1 ),\n ylim=ylims, col=\"darkorange\", cex=0.8, lwd=2, xlab=\"\", ylab=\"\", pch=20 )\n\n # nn = as.matrix( cbind( Bx=as.vector( y$B[,ndata,i] ), Fx = as.vector( y$F[,ndata,i] ) ))\n # ellipse.2d(nn[,1], nn[,2], pv=0.05, sc=30)\n\n if (i==3) title( xlab=\"Fishable biomass (kt)\" )\n if (i==2) title( ylab=\"Fishing mortality\" )\n\n F30 = -log(1-0.3)\n F10 = -log(1-0.1)\n\n Fref = 0.22\n Bmsy = BMSY[i]\n Bref = K[i] * 0.2\n BK = K[i]\n BK25 = K[i] * .25\n Fhistorical = mean( F[hdat,i], na.rm=T )\n Bhistorical = mean( B[hdat,i], na.rm=T )\n yl = 0.05\n\n\n abline (h=Fref, lty=\"solid\", col=\"gray\", lwd=2 )\n\n abline (h=F10, lty=\"dotted\", col=\"gray\")\n # text( 0.05*K[i], F10, \"10% HR\", pos=1 )\n\n abline (h=F30, lty=\"dotted\", col=\"gray\")\n # text( 0.05*K[i], F30, \"30% HR\", pos=1 )\n\n\n abline (h=FMSY[i], lty=\"dashed\", col=\"red\" )\n\n # abline (h=Fhistorical, lty=\"dashed\")\n # text( 0.05*K[i], Fhistorical, \"Mean\", pos=1, lwd=2 )\n\n # abline (v=Bref, lty=\"dotted\")\n # text( Bref-0.2, 0.25, \"Lower biomass reference point\\n (LBRP = 0.2 * BMSY)\" , srt=90, pos=3)\n\n abline (v=Bmsy, lty=\"dotted\")\n\n abline (v=BK, lty=\"dotted\")\n\n abline (v=BK25, lty=\"dotted\")\n\n text( 0.05*K[i], Fref, \"20% HR\", pos=1 )\n text( 0.05*K[i], FMSY[i], \"FMSY\", pos=3, lwd=2, col=\"red\" )\n text( BK-0.01*K[i], yl, \"K\" , srt=90, pos=3)\n text( Bmsy-0.01*K[i], yl, \"K/2\" , srt=90, pos=3)\n text( BK25-0.01*K[i], yl, \"K/4\" , srt=90, pos=3)\n text( B[hdat,i], F[hdat,i], labels=yrs0, pos=3, cex= 0.8 )\n\n text( 0, ylims[2]*0.9, labels=aulabels[i], pos=3, cex= 0.85 )\n\n\n\n # abline (v=Bhistorical, lty=\"dashed\")\n # text( Bhistorical-0.01*K[i], yl, \"Mean\" , srt=90, pos=3, lwd=2)\n\n }\n }\n\n if (vname==\"simple\") {\n\n if (is.null(fn)) fn=file.path(outdir, \"hcr.simple.png\" )\n\n require(car)\n\n B = apply( y[[\"B\"]], c(2,3), median, na.rm=T )\n F = apply( y[[\"F\"]], c(2,3), median, na.rm=T )\n C = apply( y[[\"C\"]], c(2,3), median, na.rm=T )\n K = apply( y[[\"K\"]], c(2), median, na.rm=T )\n FMSY = apply( y[[\"FMSY\"]], c(2), median, na.rm=T )\n BMSY = apply( y[[\"BMSY\"]], c(2), median, na.rm=T )\n\n aulabels = c(\"N-ENS\", \"S-ENS\", \"4X\")\n\n for (i in 1:3 ) {\n ylims = max(C[,i] )* c(0, 1.1)\n plot( B[hdat,i], C[hdat,i], type=\"l\", xlim=c(0, K[i]*1.05 ),\n ylim=ylims, xlab=\"\", ylab=\"\", lwd=2, col=\"darkorange\" )\n\n abline(0,0.1, lty=\"dotted\", lwd=2, col=\"gray\" )\n abline(0,0.2, lwd=3, col=\"gray\" )\n abline(0,0.3, lty=\"dotted\", lwd=2, col=\"gray\" )\n\n points( B[hdat,i], C[hdat,i], col=\"orange\", cex=0.8, pch=20 )\n text( B[hdat,i], C[hdat,i], labels=yrs0, pos=3, cex= 0.85 )\n\n text( 0, ylims[2]*0.9, labels=aulabels[i], pos=3, cex= 0.85 )\n\n # nn = as.matrix( cbind( Bx=as.vector( y$B[,ndata,i] ), Fx = as.vector( y$F[,ndata,i] ) ))\n # ellipse.2d(nn[,1], nn[,2], pv=0.05, sc=30)\n\n if (i==3) title( xlab=\"Fishable biomass (kt)\" )\n if (i==2) title( ylab=\"Catch (kt)\" )\n\n Cmsy = ( exp( FMSY[i] ) - 1)\n Cref = ( exp( FMSY[i] * 0.2 ) - 1) * K[i]\n Bmsy = BMSY[i]\n Bref = K[i] * 0.2\n BK = K[i]\n BK25 = K[i] * .25\n # Chistorical = mean( C[hdat,i], na.rm=T )\n # Bhistorical = mean( B[hdat,i], na.rm=T )\n yl = 0.1 * max(C[hdat,i])\n\n # abline (h=Fref, lty=\"dotted\")\n # text( 0.25, Fref, \"Target\\n (0.2 * FMSY) \", pos=1 )\n\n abline (0, Cmsy, lty=\"dotted\", col=\"red\")\n # text( 0.1*K[i], Cmsy, \"FMSY\", pos=1 )\n\n # abline (h=Chistorical, lty=\"dashed\")\n # text( 0.1*K[i], Chistorical, \"Mean\", pos=3, lwd=2 )\n\n # abline (v=Bref, lty=\"dotted\")\n # text( Bref-0.2, 0.25, \"Lower biomass reference point\\n (LBRP = 0.2 * BMSY)\" , srt=90, pos=3)\n\n\n abline (v=BK, lty=\"dotted\")\n text( BK-0.01*K[i], yl, \"K\" , srt=90, pos=3)\n\n abline (v=BK/2, lty=\"dotted\")\n text( BK/2-0.01*K[i], yl, \"K/2\" , srt=90, pos=3)\n\n abline (v=BK25, lty=\"dotted\")\n text( BK25-0.01*K[i], yl, \"K/4\" , srt=90, pos=3)\n\n }\n\n\n }\n }\n\n if (type==\"diagnostic.catch\") {\n\n }\n\n\n if (type==\"diagnostic.phase\") {\n \n if (is.null(fn)) fn=file.path(outdir, \"diagnostic.phase.png\" )\n\n B = apply( y[[\"B\"]], c(2,3), median, na.rm=T )\n K = apply( y[[\"K\"]], c(2), median, na.rm=T )\n\n for (i in 1:3 ) {\n plot( B[1:ndata-1,i], B[2:ndata,i], type=\"b\", xlab=\"t\", ylab=\"t+1\",\n xlim=c(0, K[i] * 1.25 ), ylim=max(K[i] )* c(0, 1.25), lwd=2, col=\"darkorange\" )\n\n # abline(0,0.1, lty=\"dotted\", lwd=2, col=\"gray\" )\n abline( coef=c(0,1) )\n #text( B[1:ndata-1,], B[2:ndata,], labels=yrs4 , pos=4, cex=0.8 )\n }\n }\n\n\n if (type==\"diagnostic.errors\") {\n\n if (is.null(fn)) fn=file.path(outdir, \"diagnostic.errors.png\" )\n\n # observation vs process error\n graphics.off()\n layout( matrix(c(1,2,3), 3, 1 ))\n par(mar = c(5, 4, 0, 2))\n require(car)\n\n eP = y[[\"bpsd\"]] \n eO = y[[\"bosd\"]]\n for (i in 1:3 ) {\n plot( eP[,,i], eO[,,i], type=\"p\", pch=22 )\n if (i==2) title( ylab=\"Process error (SD)\" )\n if (i==3) title( xlab=\"Observation error (SD)\" )\n\n }\n\n\n }\n\n\n if (type==\"diagnostic.production\") {\n \n B = apply( y[[\"B\"]], c(2,3), median, na.rm=T )\n P = apply( y[[\"P\"]], c(2,3), median, na.rm=T )\n C = apply( y[[\"C\"]], c(2,3), median, na.rm=T )\n K = apply( y[[\"K\"]], c(2), median, na.rm=T )\n FMSY = apply( y[[\"FMSY\"]], c(2), median, na.rm=T )\n BMSY = apply( y[[\"BMSY\"]], c(2), median, na.rm=T )\n MSY = apply( y[[\"MSY\"]], c(2), median, na.rm=T )\n\n\n # production vs biomass\n plot.new()\n layout( matrix(c(1,2,3), 3, 1 ))\n par(mar = c(5, 4, 0, 2))\n for (i in 1:3) {\n plot( B[,i], P[,i], type=\"n\", pch=20, ylim=c(0, max( c(P[,i], MSY[i]))*1.1), xlim=c(0,K[i]*1.05), xlab=\"Biomass; kt\", ylab=\"Yield; kt\" )\n a = MSY[i] / (BMSY[i])^2\n curve( -a*(x-BMSY[i])^2 + MSY[i], from=0, to=K[i], add=TRUE, lwd=3, col=\"gray\" )\n abline(v=BMSY[i], lty=\"dotted\", lwd=3, col=\"gray\")\n points( B[,i], P[,i], type=\"p\", pch=20 )\n text( B[,i], P[,i], yrs0, pos=3, cex=0.8 )\n # abline(h=0)\n }\n\n }\n\n if (is.null(fn)) fn=file.path(outdir, \"diagnostic.production.png\" )\n \n if(save.plot) savePlot( filename=fn, type=\"png\" )\n return( fn)\n\n }\n\n\n}\n\n\n\n", "meta": {"hexsha": "e11e9dd4f811802b8e97f59d952019b2b6448742", "size": 96494, "ext": "r", "lang": "R", "max_stars_repo_path": "R/fishery_model.r", "max_stars_repo_name": "jae0/snowcrab", "max_stars_repo_head_hexsha": "b168df368b739175004275c47f5bdf6907d066d9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/fishery_model.r", "max_issues_repo_name": "jae0/snowcrab", "max_issues_repo_head_hexsha": "b168df368b739175004275c47f5bdf6907d066d9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/fishery_model.r", "max_forks_repo_name": "jae0/snowcrab", "max_forks_repo_head_hexsha": "b168df368b739175004275c47f5bdf6907d066d9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.4236231382, "max_line_length": 208, "alphanum_fraction": 0.4449395817, "num_tokens": 33503, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195269001831, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.39567810697837963}} {"text": "# Copyright 2014-2019 Arnaud Poret\n# This work is licensed under the BSD 2-Clause License.\n# To view a copy of this license, visit https://opensource.org/licenses/BSD-2-Clause\n\n# number of nodes\nnnode<-7\n\n# vector declarations\n# see below for their meaning\nnodelab<-vector(mode=\"character\",length=nnode)\nnode0<-vector(mode=\"numeric\",length=nnode)\n\n# node names\n# only relevant if node states are plotted\nnodelab[1]<-\"EGF\"\nnodelab[2]<-\"HRG\"\nnodelab[3]<-\"EGFR\"\nnodelab[4]<-\"Raf\"\nnodelab[5]<-\"ERK\"\nnodelab[6]<-\"PI3K\"\nnodelab[7]<-\"AKT\"\n\n# node initial states\n# here randomly selected between 0 and 0.1 as example\nnode0[1]<-runif(1,0,0.1)# EGF\nnode0[2]<-runif(1,0,0.1)# HRG\nnode0[3]<-runif(1,0,0.1)# EGFR\nnode0[4]<-runif(1,0,0.1)# Raf\nnode0[5]<-runif(1,0,0.1)# ERK\nnode0[6]<-runif(1,0,0.1)# PI3K\nnode0[7]<-runif(1,0,0.1)# AKT\n\n# node updating function\n# for all nodes and at each iteration of the simulation: the function which calculates their updated states\n# EGF and HRG are the two inputs of this example\n# as such, they are set manually:\n# EGF is activated from 20% to 60% of the simulation, otherwise it is inactive (i.e. equals to its initial state)\n# HRG is not active (i.e. equals to its initial state)\nfnode<-function(edge,k,nnode) {\n y<-vector(mode=\"numeric\",length=nnode)\n if(0.2*kend<=k && k<=0.6*kend) {\n y[1]<-1# EGF\n } else {\n y[1]<-node0[1]# EGF\n }\n y[2]<-node0[2]# HRG\n y[3]<-or(edge[1,k],edge[2,k])# EGFR\n y[4]<-or(edge[3,k],edge[4,k])# Raf\n y[5]<-edge[5,k]# ERK\n y[6]<-and(edge[6,k],not(edge[7,k]))# PI3K\n y[7]<-edge[8,k]# AKT\n return(y)\n}\n", "meta": {"hexsha": "d08991f84c8d15771e9a3288664243c39407bdd1", "size": 1610, "ext": "r", "lang": "R", "max_stars_repo_path": "node.r", "max_stars_repo_name": "arnaudporet/enhance_my_Boole", "max_stars_repo_head_hexsha": "8181e8e43d02cd29fb83b9e170224e2a73c694e1", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "node.r", "max_issues_repo_name": "arnaudporet/enhance_my_Boole", "max_issues_repo_head_hexsha": "8181e8e43d02cd29fb83b9e170224e2a73c694e1", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "node.r", "max_forks_repo_name": "arnaudporet/enhance_my_Boole", "max_forks_repo_head_hexsha": "8181e8e43d02cd29fb83b9e170224e2a73c694e1", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2016-05-01T18:56:42.000Z", "max_forks_repo_forks_event_max_datetime": "2016-05-01T18:56:42.000Z", "avg_line_length": 29.8148148148, "max_line_length": 117, "alphanum_fraction": 0.6583850932, "num_tokens": 623, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943925708562, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.39566336538183544}} {"text": "###############################################################################\n# Copyright (C) 1994 - 2009, Performance Dynamics Company #\n# #\n# This software is licensed as described in the file COPYING, which #\n# you should have received as part of this distribution. The terms #\n# are also available at http://www.perfdynamics.com/Tools/copyright.html. #\n# #\n# You may opt to use, copy, modify, merge, publish, distribute and/or sell #\n# copies of the Software, and permit persons to whom the Software is #\n# furnished to do so, under the terms of the COPYING file. #\n# #\n# This software is distributed on an \"AS IS\" basis, WITHOUT WARRANTY OF ANY #\n# KIND, either express or implied. #\n###############################################################################\n\nlibrary(pdq)\n\narrivRate = 0.75\nservice_time = 1.0\n\n#---- Initialize --------------------------------------------------------------\n\nInit(\"OpenCircuit\")\nSetComment(\"A simple M/M/1 queue\")\n\n#---- Define the queueing center ----------------------------------------------\n\nCreateNode(\"server\", CEN, FCFS)\n\n#---- Define the workload and circuit type ------------------------------------\n\nCreateOpen(\"work\", arrivRate)\n\nSetWUnit(\"Customers\")\nSetTUnit(\"Seconds\")\n\n#---- Define service demand due to workload on the queueing center ------------\n\nSetDemand(\"server\", \"work\", service_time)\n\n#---- Solve the model ---------------------------------------------------------\n# Must use the CANONical method for an open circuit\n\nSolve(CANON)\n\n#---- Generate a report -------------------------------------------------------\n\nReport()\n", "meta": {"hexsha": "a5182a180979559e4dba3f53ce490e3bb1f0d05f", "size": 1943, "ext": "r", "lang": "R", "max_stars_repo_path": "R/test.r", "max_stars_repo_name": "peterlharding/PDQ", "max_stars_repo_head_hexsha": "b6ff8dd958dbae85b4402745539898b711760713", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2015-08-12T16:22:11.000Z", "max_stars_repo_stars_event_max_datetime": "2019-06-05T05:57:35.000Z", "max_issues_repo_path": "R/test.r", "max_issues_repo_name": "peterlharding/PDQ", "max_issues_repo_head_hexsha": "b6ff8dd958dbae85b4402745539898b711760713", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/test.r", "max_forks_repo_name": "peterlharding/PDQ", "max_forks_repo_head_hexsha": "b6ff8dd958dbae85b4402745539898b711760713", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2018-03-12T12:25:28.000Z", "max_forks_repo_forks_event_max_datetime": "2019-06-05T05:57:44.000Z", "avg_line_length": 39.6530612245, "max_line_length": 79, "alphanum_fraction": 0.4276891405, "num_tokens": 328, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.689305616785446, "lm_q2_score": 0.5736784074525098, "lm_q1q2_score": 0.39543974848554464}} {"text": "#' @title Calculate Likelihood based on Dirichlet-multinomial distribution estimated parameters\n#'\n#' @description\n#' This function estimates parameters from Dirichlet-multinomial distribution.\n#' @param FS_out An object from the FeatureSelection()\n#' @param testSet A test set in data frame or matrix form. The colnames should have the same bacteria (features) as in the training set.\n#' @param col_start An index indicating at which column is the beginning of bacteria (features) data. The default is the 3rd column.\n#' @param type_col An index indicating at which column is group/type variable. The default is the 2nd column.\n#' @param HighestRank The top number of features inclueded in model. The default is all the features left after filtering.\n#' @return A data frame with 17 columns, each row represents a model estimation output.\n#' @export\n#' @examples\n#' data(training)\n#'\n#' #### Take one row as testSet ####\n#' idx <- sample(1:nrow(training),1)\n#' test <- training[idx,]\n#' train <- training[-idx,]\n#'\n#' CalPrb(FS(train),test) # This may take up to one minute\n\nCalPrb <- function(FS_out=FS_out,testSet=testSet,col_start=3,type_col=2,HighestRank=nrow(FS_out$Feature)){\n\n Genus <- FS_out$CountData\n SortP <- FS_out$Feature\n\n Disease <- levels(Genus[,type_col])\n\n TotalType1 <- nrow(Genus[Genus[,type_col] == Disease[1], ])\n TotalType2 <- nrow(Genus[Genus[,type_col] == Disease[2], ])\n Prior1 <- TotalType1/(TotalType1+TotalType2)\n Prior2 <- TotalType2/(TotalType1+TotalType2)\n\n lh <- list()\n for(rank in 2:HighestRank) {\n #for(rank in 2:5) {\nprint(rank)\n ######## choose the signature taxa and merge the training data\n\n #NameList = as.vector(P_table[as.numeric(as.character(P_table$P_Wilcoxon))<0.2,]$Genera)\n #select the NameList based on the rank\n NameList <- as.vector(rownames(SortP)[1:rank])\n NewDF <- Genus[,colnames(Genus) %in% NameList]\n NewDF2 <- Genus[,!colnames(Genus)%in% NameList]\n\n col_end2 <- dim(NewDF2)[2]\n NewDF2$Others <- rowSums(NewDF2[, col_start:col_end2])\n #NewDFTotal = data.frame(NewDF2[, 1:(col_start-1)],NewDF, NewDF2$Others)\n NewDFTotal <- data.frame(NewDF2[, 1:(col_start-1)],NewDF)\n ###### merge in test row\n\n NewTestSignature <- testSet[, colnames(Genus) %in% NameList]\n NewTestNonSignature <- testSet[, !colnames(Genus)%in% NameList]\n NewTestNonSignature$Others <- rowSums(NewTestNonSignature[, col_start:col_end2])\n NewTestTotal <- data.frame(NewTestNonSignature[, 1:(col_start-1)],NewTestSignature)\n #NewTestTotal = data.frame(NewTestNonSignature[, 1:(col_start-1)],NewTestSignature, NewTestNonSignature$Others)\n\n\n rep2_Type1 <- NewDFTotal[NewDFTotal[,type_col] ==Disease[1],]\n rep2_Type2 <- NewDFTotal[NewDFTotal[,type_col] ==Disease[2],]\n\n\n ############Estimate Zero Inflated Generalized Dirchlet-Multinomial parameters\n tol <-0.0001\n max.iter<-1000\n\n ###### Estimate the parameters from the control data\n Xc <- as.matrix(rep(1, dim(rep2_Type1)[1]))\n Xa <- Xc\n Xb <- Xc\n c0 <- as.matrix(rep(1, dim(rep2_Type1)[2]-col_start))\n alpha0 <- c0\n beta0 <- c0\n\n\n ZIGDM_est1 <-ZIGDM.EM.PAR2(rep2_Type1[,-(1:(col_start-1))], Xc, Xa, Xb, c0, alpha0, beta0, tol=0.0001, max.iter=1000)\n\n # ZIGDM_est1 <-ZIGDM.EM.PAR2(rep2_Type1[,-c((1:(col_start-1)), ncol(rep2_Type1))], Xc, Xa, Xb, c0, alpha0, beta0, tol=0.0001, max.iter=1000)\n ###p_Type1 <- ZIGDM_prob(rep2_Type1[,-(1:(col_start-1))], Xc, Xa, Xb, c0, alpha0, beta0, tol=0.0001, max.iter=1000)\n #fit3 <- dirmult(rep2_Type1[,-(1:(col_start-1))],epsilon=10^(-4),trace=FALSE)\n\n ###### Estimate the paramenters from the baseline data\n Xc <- as.matrix(rep(1, nrow(rep2_Type2)))\n Xa <- Xc\n Xb <- Xc\n c0 <- as.matrix(rep(1, ncol(rep2_Type1)-col_start))\n alpha0 <- c0\n beta0 <- c0\n\n ZIGDM_est2<-ZIGDM.EM.PAR2(rep2_Type2[,-(1:(col_start-1))], Xc, Xa, Xb, c0, alpha0, beta0, tol=0.0001, max.iter=1000)\n\n ##p_Type2 <- ZIGDM_prob(rep2_Type2[,-(1:(col_start-1))], Xc, Xa, Xb, c0, alpha0, beta0, tol=0.0001, max.iter=1000)\n #fit4 <- dirmult(rep2_Type2[,-(1:(col_start-1))],epsilon=10^(-4),trace=FALSE)\n\n\n #########Calculate the likelihood of the test sample being Type1 and Type2\n######error p_Type1 has 7 number as 7 taxa? while only 2 taxa in\n #p_Type1 <- ZIGDM_prob(ZIGDM_est1, row = Xc[1,])\n #p_Type2 <- ZIGDM_prob(ZIGDM_est2, row = Xc[1,])\n\n testlist <- list()\n\n for (r in 1:nrow(testSet)){\n repeatlist <- list()\n for (rep in 1:10) {\n ##### Calculate zero inflated generalized Dirichlet multinomial probability mass function P(x|Type1)\n p_Type1 <- ZIGDM_prob(ZIGDM_est1, row = Xc[1,])\n p_Type2 <- ZIGDM_prob(ZIGDM_est2, row = Xc[1,])\n normalizeTest = NewTestTotal[r,-(1:(col_start-1))]/sum(NewTestTotal[r,-(1:(col_start-1))])*100\n if(length(normalizeTest) == 2) {\n probability_Type1 = apply(round(normalizeTest[1]),1,dbinom, 100, prob = p_Type1[1])\n }else{\n probability_Type1 = apply(normalizeTest,1,dmultinom, prob = p_Type1)\n }\n lhP_Type1 = probability_Type1*Prior1\n\n #pdfln_Type1 <- ddirmn(NewTestTotal[r,-(1:(col_start-1))], t(as.matrix(p_Type1)))\n #lh_Type1=exp(pdfln_Type1)\n #lhP_Type1 = lh_Type1*Prior1\n\n ##### Calculate log of Dirichlet multinomial probability mass function P(x|Type2)\n if(length(normalizeTest) == 2) {\n probability_Type2 = apply(round(normalizeTest[1]),1,dbinom, 100, prob = p_Type2[1])\n }else{\n probability_Type2 = apply(normalizeTest,1,dmultinom, prob = p_Type2)\n }\n\n lhP_Type2 = probability_Type2*Prior2\n\n #pdfln_Type2 <- ddirmn(NewTestTotal[r,-(1:(col_start-1))], t(as.matrix(p_Type2)))\n #lh_Type2=exp(pdfln_Type2)\n #lhP_Type2 = lh_Type2*Prior2\n\n #Pos_Type1 = lh_Type1/(lh_Type1+lh_Type2)\n #Pos_Type2 = lh_Type2/(lh_Type1+lh_Type2)\n\n PosP_Type1 = lhP_Type1/(lhP_Type1+lhP_Type2)\n PosP_Type2 = lhP_Type2/(lhP_Type1+lhP_Type2)\n\n #### Create truth labels ####\n\n if(testSet[r,type_col] == Disease[1]) {\n Type1Label = 1\n Type2Label = 0\n } else if (testSet[r,type_col] == Disease[2]) {\n Type1Label = 0\n Type2Label = 1\n }\n repeatlist[[rep]] <- as.matrix(t(c(Disease[1], Disease[2], rownames(testSet)[r], rank, PosP_Type1, PosP_Type2, Type1Label, Type2Label,paste(NameList,collapse=\";\"))))\n\n }\n RandomRepeat = data.frame(t(sapply(repeatlist,'[')))\n PosP_Type1 = mean(as.numeric(as.character(RandomRepeat$X5)), na.rm = TRUE)\n PosP_Type2 = mean(as.numeric(as.character(RandomRepeat$X6)), na.rm = TRUE)\n\n testlist[[r]] <- as.matrix(t(c(Disease[1], Disease[2], rownames(testSet)[r], rank, PosP_Type1, PosP_Type2, Type1Label, Type2Label,paste(NameList,collapse=\";\"))))\n\n\n\n\n## lh[[rank]] <- as.matrix(t(c(Disease[1], Disease[2], rownames(testSet), rank, Prior1, Prior2, lh_Type1, lh_Type2, Pos_Type1, Pos_Type2, lhP_Type1, lhP_Type2, PosP_Type1, PosP_Type2, Type1Label, Type2Label,paste(NameList,collapse=\";\"))))\n\n lh[[rank]] <- data.frame(t(sapply(testlist,'[')))\n\n } #end of rank\n\n lh_table <- data.frame(do.call(rbind,lh))\n## colnames(lh_table) = c(\"Type1\", \"Type2\", \"row\", \"feature_rank\", \"Prior1\", \"Prior2\", \"lh_Type1\", \"lh_Type2\", \"Poster_Type1\", \"Poster_Type2\", \"lhP_Type1\", \"lhP_Type2\",\"Poster_Prio_Type1\",\"Poster_Prio_Type2\", \"Type1Label\", \"Type2Label\",\"SelectedFeatures\" )\n\n colnames(lh_table) = c(\"Type1\", \"Type2\", \"row\", \"feature_rank\", \"Type1_Posterior_Prb\",\"Type2_Postereior_Prb\", \"Type1Label\", \"Type2Label\",\"SelectedFeatures\" )\n}\n return(lh_table)\n}\n", "meta": {"hexsha": "7c25c071a22ff8ef60083c53f7e72b3aff04e143", "size": 7621, "ext": "r", "lang": "R", "max_stars_repo_path": "R/CalPrb.r", "max_stars_repo_name": "qunfengdong/BioMarkerClassifier", "max_stars_repo_head_hexsha": "06acc16d28de665119be76c529d7d07ad3ddfcf6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/CalPrb.r", "max_issues_repo_name": "qunfengdong/BioMarkerClassifier", "max_issues_repo_head_hexsha": "06acc16d28de665119be76c529d7d07ad3ddfcf6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/CalPrb.r", "max_forks_repo_name": "qunfengdong/BioMarkerClassifier", "max_forks_repo_head_hexsha": "06acc16d28de665119be76c529d7d07ad3ddfcf6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 43.7988505747, "max_line_length": 257, "alphanum_fraction": 0.667235271, "num_tokens": 2488, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7718434873426302, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.39496512870599315}} {"text": "subroutine addpt(j,nadj,madj,x,y,ntot,eps,ntri,nerror)\n# Add point j to the triangulation.\n# Called by master, dirseg.\n\nimplicit double precision(a-h,o-z)\ndimension nadj(-3:ntot,0:madj), x(-3:ntot), y(-3:ntot)\nlogical didswp\n\n# Put the new point in, joined to the vertices of its\n# enclosing triangle.\ncall initad(j,nadj,madj,x,y,ntot,eps,ntri,nerror)\nif(nerror > 0) return\n\n# Look at each `gap', i.e. pair of adjacent segments\n# emanating from the new point; they form two sides of a\n# quadrilateral; see whether the extant diagonal of this\n# quadrilateral should be swapped with its alternative\n# (according to the LOP: local optimality principle).\nnow = nadj(j,1)\nnxt = nadj(j,2)\nngap = 0\n\nrepeat {\n\tcall swap(j,now,nxt,didswp,nadj,madj,x,y,ntot,eps,nerror)\n\tif(nerror > 0) return\n n = nadj(j,0)\n if(!didswp) { # If no swap of diagonals\n now = nxt # move to the next gap.\n ngap = ngap+1\n }\n call succ(nxt,j,now,nadj,madj,ntot,nerror)\n\tif(nerror > 0) return\n}\nuntil(ngap==n)\n\nreturn\nend\n", "meta": {"hexsha": "c05142a5c9322947442caa048c6a309ac7e8575c", "size": 1059, "ext": "r", "lang": "R", "max_stars_repo_path": "deldir/ratfor/addpt.r", "max_stars_repo_name": "solgenomics/R_libs", "max_stars_repo_head_hexsha": "a936847f6063cdf3d207e8364f05f2e13be2d878", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "deldir/ratfor/addpt.r", "max_issues_repo_name": "solgenomics/R_libs", "max_issues_repo_head_hexsha": "a936847f6063cdf3d207e8364f05f2e13be2d878", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-08-17T15:14:11.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-23T21:55:49.000Z", "max_forks_repo_path": "deldir/ratfor/addpt.r", "max_forks_repo_name": "solgenomics/R_libs", "max_forks_repo_head_hexsha": "a936847f6063cdf3d207e8364f05f2e13be2d878", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-11-04T05:34:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-04T05:34:16.000Z", "avg_line_length": 27.8684210526, "max_line_length": 58, "alphanum_fraction": 0.6685552408, "num_tokens": 340, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321842389469, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.3949117103547496}} {"text": "# 4. faza: Analiza podatkov\n\n## Uvozimo funkcijo za uvoz spletne strani.\n#source(\"lib/xml.r\")\n\n# # Preberemo spletno stran v razpredelnico.\n# cat(\"Uvažam spletno stran...\\n\")\n# tabela <- preuredi(uvozi.obcine(), obcine)\n# \n# # Narišemo graf v datoteko PDF.\n# cat(\"Rišem graf...\\n\")\n# pdf(\"slike/naselja.pdf\", width=6, height=4)\n# plot(tabela[[1]], tabela[[4]],\n# main = \"Število naselij glede na površino občine\",\n# xlab = \"Površina (km^2)\",\n# ylab = \"Št. naselij\")\n# dev.off()\n\n\n#1.) Normiran zemljevid Števila športnikov iz posameznih držav na OI 2012\n\n#najprej izračunamo vektor ki vsebuje podatek o športnikih/število prebivalcev\nnn<-sportniki*1000000 #število športnikov pomnoženo z 10^6, da vsa števila v legendi niso enaka 0\npop<-svet$pop_est #populacija, podatki iz zemljevida svet\n\n#uredimo\nl <- match(svet$name_long, rownames(nn))\nnorm.sp.svet <- nn[l,]\n\npodatki.za.norm.zemlj<-norm.sp.svet/pop #podatki ki jih bomo uporabili za zemljevid\n\n\n# Izračunamo max, min, povprečje\n#druzine$povprecje <- apply(druzine[1:4], 1, function(x) sum(x*(1:4))/sum(x))\nmin.norm <- min(podatki.za.norm.zemlj, na.rm=TRUE)\nmax.norm <- max(podatki.za.norm.zemlj, na.rm=TRUE)\npovp.norm<-sum(podatki.za.norm.zemlj,na.rm=TRUE)/length(podatki.za.norm.zemlj)\nnorm.norm <- (podatki.za.norm.zemlj-min.norm)/(max.norm-min.norm)\n\n# Narišimo zemljevid v PDF.\ncat(\"Rišem normiran zemljevid za OI...\\n\")\npdf(\"slike/normiranzemljevid.pdf\")\n\nn = 100\nbarve.norm=rgb(0, 0, 1, (1:n)/n)[unlist(1+(n-1)*norm.norm)]\n\nplot(svet, col = barve.norm)\n\n#naslov\ntitle(\"Št. športnikov na milijon prebivalcev iz posameznih držav na OI 2012\")\n#legenda\nlegend(\"left\", legend = round(seq(min.norm, max.norm, (max.norm-min.norm)/5)),\n fill = rgb(0, 0, 1, (1:6)/6), bg = \"white\")\n\n\n#Dodamo imena drzav\n#najprej poberemo iz zemljevida svet tiste države ki bi jih radi označili\noznacene<-svet[c(9,23,28,31,136,169),]\n#dodamo imena na zemljevid\ntext(coordinates(oznacene),labels=c(\"Avstralija\",\"Brazilija\",\"Kanada\",\"Kitajska\",\"Rusija\",\"ZDA\"),cex=0.55,col=\"black\")\n\ndev.off()\n\n\n#2.) Krivulje, ki se najbolj prilegajo številu dogodkov na poletnih in zimskih OI\nattach(OI)\npdf(\"slike/naprednigrafi.pdf\",paper=\"a4r\")\n\n\n#2.1.)modeli: krivulje za št dogodkov poletnih OI\n\nletop<-OI$Leto[Vrsta==\"poletne\"] #leta poletnih OI\ndogp<-OI$Stevilo.dogodkov[Vrsta==\"poletne\"] #st dogodkov poletnih OI\n\n #graf\nplot(letop,dogp, xlim=c(1896,2050),ylim=c(0,500),\n xlab=\"Leto\",ylab=\"Število dogodkov\",\n main=\"Napoved za število dogodkov na poletnih OI\",pch=20,col=\"red\",type=\"p\",lwd=3.5)\n\n #premica\nlinp<-lm(dogp~letop)\nabline(linp,col=\"green\")\n #parabola\nkvp<-lm(dogp~I(letop^2)+letop)\ncurve(predict(kvp, data.frame(letop=x)), add = TRUE, col = \"purple\")\n #loess\nloep<-loess(dogp~letop)\ncurve(predict(loep, data.frame(letop=x)),add=TRUE,col=\"orange\")\n #legenda\nlegend(\"topleft\", c(\"Linerana metoda\", \"Kvadratna metoda\",\"Loess\"),lty=c(1,1,1), col = c(\"green\",\"purple\",\"orange\"))\n #Ocenimo prileganje krivulj tako, da izračunamo vsote kvadratov razdalj od napovedanih do dejanskih vrednosti\nostp<-sapply(list(linp, kvp, loep), function(x) sum(x$residuals^2))\n\n#2.2.)modeli: krivulje za št dogodkov zimskih OI\n\nletoz<-OI$Leto[Vrsta==\"zimske\"] #leta zimskih OI\ndogz<-OI$Stevilo.dogodkov[Vrsta==\"zimske\"] #st dogodkov zimskih OI\n\n #graf\nplot(letoz,dogz,xlim=c(1924,2050),ylim=c(0,200),\n xlab=\"Leto\",ylab=\"Število dogodkov\",\n main=\"Napoved za število dogodkov na zimskih OI\",pch=20,col=\"blue\",type=\"p\",lwd=3.5)\n \n #premica\nlinz<-lm(dogz~letoz)\nabline(linz,col=\"green\")\n #parabola\nkvz<-lm(dogz~I(letoz^2)+letoz)\ncurve(predict(kvz, data.frame(letoz=x)), add = TRUE, col = \"purple\")\n #loess\nloez<-loess(dogz~letoz)\ncurve(predict(loez, data.frame(letoz=x)),add=TRUE,col=\"orange\")\n #legenda\nlegend(\"topleft\", c(\"Linerana metoda\", \"Kvadratna metoda\",\"Loess\"),lty=c(1,1,1), col = c(\"green\",\"purple\",\"orange\"))\n #Ocenimo prileganje krivulj tako, da izračunamo vsote kvadratov razdalj od napovedanih do dejanskih vrednosti\nostz<-sapply(list(linz, kvz, loez), function(x) sum(x$residuals^2))\n\ndetach(OI)\ndev.off()\n\n#3.) Razvrstimo države v skupine glede na število športnikov\n\npdf(\"slike/skupine.pdf\",paper=\"a4r\")\n\n#tabela, ki za države na zemljevidu pove, koliko šprtnikov na milijon prebivalcev so poslale na OI 2012\nza10<-data.frame(row.names=svet$name_long,podatki.za.norm.zemlj) \n#znebimo se NA vrstic\nza10<-za10[-c(7,8,24,39,55,66,89,114,138,141,146,164),]\ndrz<-svet$name_long[-c(7,8,24,39,55,66,89,114,138,141,146,164)]\n#končna tabela, ki jo bom uporabila za razvrščanje v skupine\ntab.za.skupine<-data.frame(row.names=drz,za10)\n\n#normaliziramo\nX <- scale(as.matrix(tab.za.skupine))\nt <- hclust(dist(X),method = \"ward\")\n#narišemo graf\nplot(t, hang=-1, cex=0.2, lwd=0.1,main = \"Skupine držav\")\nlegend(\"topleft\", c(\"Skupina 1\", \"Skupina 2\",\"Skupina 3\",\"Skupina 4\",\"Skupina 5\",\"Skupina 6\"),lty=c(1,1,1), col = c(\"red\",\"yellow\",\"orange\",\"blue\",\"magenta\",\"green\"))\ntext(20,30,\"Skupina 1 predstavlja\")\ntext(20,27.7,\"državo z najmanj,\")\ntext(20,25.4,\"skupina 6 državo z\")\ntext(20,23.1,\"največ športniki\")\ntext(20,20.8,\"na milijon prebivalcev.\")\n#določimo skupine\nrect.hclust(t,k=6,border=c(\"red\",\"yellow\",\"magenta\",\"green\",\"orange\",\"blue\"))\n\n\ncutree(t, k=6)\n\ndev.off()\n", "meta": {"hexsha": "f616665ac920180d0bee9cca8b56b57668b70f2b", "size": 5248, "ext": "r", "lang": "R", "max_stars_repo_path": "analiza/analiza.r", "max_stars_repo_name": "urskabele/APPR-2014-15", "max_stars_repo_head_hexsha": "d6a0cc39b464cae28ee59616cdd7874467bdca5a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "analiza/analiza.r", "max_issues_repo_name": "urskabele/APPR-2014-15", "max_issues_repo_head_hexsha": "d6a0cc39b464cae28ee59616cdd7874467bdca5a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2015-01-08T23:00:15.000Z", "max_issues_repo_issues_event_max_datetime": "2015-02-24T17:39:47.000Z", "max_forks_repo_path": "analiza/analiza.r", "max_forks_repo_name": "urskabele/APPR-2014-15", "max_forks_repo_head_hexsha": "d6a0cc39b464cae28ee59616cdd7874467bdca5a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.7549668874, "max_line_length": 166, "alphanum_fraction": 0.704839939, "num_tokens": 2190, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6477982315512488, "lm_q2_score": 0.6076631698328917, "lm_q1q2_score": 0.39364312679657343}} {"text": "# Wind Manipulation\n# 2016-05-05 Ismail SEZEN\n# sezenismail@gmail.com\n\n#' rwind: A package for processing wind and related data.\n#'\n#' The rwind package provides four categories of important functions:\n#' \\code{\\link{deg2comp}}, \\code{\\link{hd2uv}}, \\code{\\link{uv2hd}}\n#' and \\code{\\link{rotax}}.\n#'\n#' @section rwind functions:\n#' The rwind functions ...\n#'\n#' @docType package\n#' @name rwind\nNULL\n\n\nindex_array <- function(x, dim, value, drop = T) {\n indices <- rep(list(bquote()), length(dim(x)))\n indices[[dim]] <- value\n call <- as.call(c(\n list(as.name(\"[\"), quote(x)),\n indices,\n list(drop = drop)))\n eval(call)\n}\n\n\nwindhelper_get_args <- function(...) {\n l <- list(...); x <- NULL\n if (length(l) == 1) {\n if (is.array(l[[1]])) x <- l[[1]]\n if (is.data.frame(l[[1]])) x <- as.matrix(l[[1]])\n }\n if (is.null(x)) x <- do.call(c, l)\n if (is.vector(x) && (length(x) %% 2) == 0)\n x <- array(x, dim = c(length(x) / 2, 2))\n return(x)\n}\n\n\n#' Wind direction to compass direction\n#'\n#' \\code{deg2comp} converts horizontal wind speed and direction to uv\n#' components of wind.\n#'\n#' @param x A numeric vector of wind directions in degrees.\n#' @return Wind directions converted to compass directions\n#'\n#' @author Ismail SEZEN, \\email{sezenismail@@gmail.com}\n#'\n#' @examples\n#' deg2comp(runif(100, 0, 360))\n#' x <- array(runif(1000, 0, 360), dim = c(10, 10, 10))\n#' deg2comp(x)\n#'\n#' @export\ndeg2comp <- function(x, bins = c(\"N\", \"NNE\", \"NE\", \"ENE\",\n \"E\", \"ESE\", \"SE\", \"SSE\",\n \"S\", \"SSW\", \"SW\", \"WSW\",\n \"W\", \"WNW\", \"NW\", \"NNW\")) {\n x[x == 0] <- 360\n x <- round((x * length(bins) / 360) + .5)\n x[1:length(x)] <- bins[x]\n return(x)\n}\n\n\n#' uv to horizontal speed & direction\n#'\n#' Convert uv components of wind to horizontal wind speed and direction.\n#'\n#' @param ... The names of the objects to be converted\n#' @param deg Should the resulting wind directions are degree or radian?\n#' @param reverse should be added 180 degree (or pi) to the wind directions?\n#' @param drop Should be deleted the dimensions of an array which\n#' have only one level?\n#' @return Speed and direction of the wind\n#'\n#' @author Ismail SEZEN, \\email{sezenismail@@gmail.com}\n#'\n#' @examples\n#' uv2hd(1, 1)\n#' uv2hd(c(1, 1))\n#' x <- array(runif(100, -5, 5), dim = c(100, 100, 2))\n#' uv2hd(x)\n#'\n#' @export\nuv2hd <- function(..., deg = T, reverse = T, drop = T) {\n x <- windhelper_get_args(...)\n comp_loc <- which(dim(x) == 2, arr.ind = T) # find uv dim order\n if (length(comp_loc) == 0)\n stop(\"x does not have a dim = 2 represents u and v\")\n dx <- dim(x); ldx <- length(dx)\n r <- aperm(x, c(comp_loc, (1:ldx)[-comp_loc])) # get uv dim to start\n\n num_pi <- if (deg) 180 else pi\n add_pi <- if (reverse) num_pi else 0\n u <- index_array(r, 1, 1)\n v <- index_array(r, 1, 2)\n h <- sqrt(colSums(r ^ 2))\n d <- ((atan2(u / h, v / h) * num_pi / pi) + add_pi)\n if (deg) d <- d %% 360\n r <- array(c(h, d), dim = dx)\n\n r[is.nan(r)] <- 0\n dmn <- dimnames(x)\n if (is.null(dmn)) {\n dimnames(r)[[comp_loc]] <- c(\"h\", \"d\")\n } else {\n dimnames(r) <- dmn\n }\n if (drop) r <- drop(r)\n return(r)\n}\n\n\n#' Horizontal wind speed & direction to uv\n#'\n#' Convert horizontal wind speed and direction to uv components of wind.\n#'\n#' @param ... The names of the objects to be converted\n#' @param deg Should the resulting wind directions are degree or radian?\n#' @param drop Should be deleted the dimensions of an array which\n#' have only one level?\n#' @return uv components of the wind\n#'\n#' @author Ismail SEZEN, \\email{sezenismail@@gmail.com}\n#'\n#' @examples\n#' hd2uv(5, 30)\n#' hd2uv(c(5, 30))\n#' x <- matrix(c(runif(100, -5, 5), round(runif(100, 0, 360), 2)), ncol = 2,\n#' dimnames = list(NULL, c(\"h\",\"d\")))\n#' hd2uv(x)\n#'\n#' @export\nhd2uv <- function(..., deg = T, drop = T) {\n x <- windhelper_get_args(...)\n comp_loc <- which(dim(x) == 2, arr.ind = T) # find uv dim order\n if (length(comp_loc) == 0)\n stop(\"x does not have a dim = 2 represents h and d\")\n dx <- dim(x); ldx <- length(dx)\n r <- aperm(x, c(comp_loc, (1:ldx)[-comp_loc])) # get uv dim to start\n\n num_pi <- if (deg) 180 else pi\n h <- index_array(r, 1, 1)\n d <- index_array(r, 1, 2)\n d <- (d - num_pi) / num_pi\n u <- h * sinpi(d)\n v <- h * cospi(d)\n r <- array(c(u, v), dim = dx)\n\n r[is.nan(r)] <- 0\n dmn <- dimnames(x)\n if (is.null(dmn)) {\n dimnames(r)[[comp_loc]] <- c(\"u\", \"v\")\n } else {\n dimnames(r) <- dmn\n }\n if (drop) r <- drop(r)\n return(r)\n}\n\n\n#' Rotate coordinate axis for uv wind components\n#'\n#' Rotates coordinate axes for uv components of the wind. uv values will be\n#' re-calculated based on new axis. For instance, rotating axis 30 degrees\n#' in clockwise means new and old positive y-directions will have 30 degrees\n#' between them.\n#'\n#'\n#' @param ... The names of the objects to be converted.\n#' @param alfa Rotation angle in degrees or radians.\n#' @param deg TRUE if alfa is degree.\n#' @param right TRUE if rotation is in clockwise.\n#' @param drop Should be deleted the dimensions of an array which have\n#' only one level?\n#' @return Rotated uv components\n#'\n#' @author Ismail SEZEN, \\email{sezenismail@@gmail.com}\n#'\n#' @examples\n#' rotax(1, 1)\n#' rotax(1, 1, alfa = 120)\n#' x <- array(runif(100, -5, 5), dim = c(100, 100, 2))\n#' rotax(x)\n#'\n#' @export\nrotax <- function(..., alfa = 45, deg = T, right = T, drop = T) {\n x <- windhelper_get_args(...)\n comp_loc <- which(dim(x) == 2, arr.ind = T) # find uv dim order\n if (length(comp_loc) == 0)\n stop(\"x does not have a dim = 2 represents u and v\")\n\n u <- index_array(x, comp_loc, 1)\n v <- index_array(x, comp_loc, 2)\n a <- if (deg) alfa / 180 else alfa / pi\n c <- cospi(a); s <- sinpi(a)\n if (right) {\n un <- u * c - v * s\n vn <- u * s + v * c\n } else {\n un <- u * c + v * s\n vn <- v * c - u * s\n }\n dm <- dim(x); dn <- dimnames(x)\n x <- array(c(un, vn), dim = dm)\n dimnames(x) <- dn\n if (drop) x <- drop(x)\n return(x)\n}\n", "meta": {"hexsha": "ae1ee7b5609cc8afcd5e8aa11e1e1a5563b0ec8f", "size": 6043, "ext": "r", "lang": "R", "max_stars_repo_path": "R/rwind.r", "max_stars_repo_name": "isezen/rwind", "max_stars_repo_head_hexsha": "776d7966b341c0d8af69640f9ada7ce9aa32ba33", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2017-12-06T16:10:13.000Z", "max_stars_repo_stars_event_max_datetime": "2017-12-06T16:10:13.000Z", "max_issues_repo_path": "R/rwind.r", "max_issues_repo_name": "isezen/rwind", "max_issues_repo_head_hexsha": "776d7966b341c0d8af69640f9ada7ce9aa32ba33", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/rwind.r", "max_forks_repo_name": "isezen/rwind", "max_forks_repo_head_hexsha": "776d7966b341c0d8af69640f9ada7ce9aa32ba33", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.1069767442, "max_line_length": 76, "alphanum_fraction": 0.5838159854, "num_tokens": 2019, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5926665999540698, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.3922995802618359}} {"text": "# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n# \n# http://www.apache.org/licenses/LICENSE-2.0\n# \n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\n#' Calculate Kinship matrix by VanRaden method\n#'\n#' Build date: Dec 12, 2016\n#' Last update: Dec 12, 2019\n#' \n#' @param M Genotype, m * n, m is marker size, n is population size\n#' @param priority speed or memory\n#' @param cpu the number of cpu\n#' @param verbose whether to print detail.\n#'\n#' @return K, n * n matrix\n#' @export\n#'\n#' @examples\n#' genoPath <- system.file(\"extdata\", \"06_mvp-impute\", \"mvp.imp.geno.desc\", package = \"rMVP\")\n#' genotype <- attach.big.matrix(genoPath)\n#' print(dim(genotype))\n#' \n#' K <- MVP.K.VanRaden(genotype)\n#' \nMVP.K.VanRaden <-\nfunction(\n M, \n priority=c(\"speed\", \"memory\"), \n cpu=1,\n verbose=TRUE\n){\n # R.ver <- Sys.info()[['sysname']]\n # wind <- R.ver == 'Windows'\n # linux <- R.ver == 'Linux'\n # mac <- (!linux) & (!wind)\n r.open <- eval(parse(text = \"!inherits(try(Revo.version,silent=TRUE),'try-error')\"))\n\n # if(r.open && mac){\n # Sys.setenv(\"VECLIB_MAXIMUM_THREADS\" = \"1\")\n # }\n\n if (!is.big.matrix(M)) stop(\"Format of Genotype Data must be big.matrix\")\n if(hasNA(M@address)) stop(\"NA is not allowed in genotype, use 'MVP.Data.impute' to impute.\")\n \n # logging.log(\"Relationship matrix mode in\", priority[1], \"\\n\", verbose = verbose)\n # if(is.null(dim(M))) M <- t(as.matrix(M))\n switch(\n match.arg(priority),\n \"speed\" = {\n # if (!is.matrix(M)) M <- as.matrix(M)\n # n <- ncol(M)\n # m <- nrow(M)\n # Pi <- 0.5 * rowMeans(M)\n # logging.log(\"Scale the genotype matrix\", \"\\n\", verbose = verbose)\n # M <- M - 2 * Pi\n # SUM <- sum(Pi * (1 - Pi))\n # logging.log(\"Computing Z'Z\", \"\\n\", verbose = verbose)\n\n K <- try(kin_cal_s(M@address, threads = cpu, verbose = verbose, mkl = r.open), silent=TRUE)\n \n if(inherits(K,\"try-error\")){\n logging.log(\"Out of memory, please set parameter (..., priority='memory') and try again.\", \"\\n\", verbose = verbose)\n stop(K[[1]])\n }\n },\n \n \"memory\" = {\n K <- kin_cal_m(M@address, threads=cpu, verbose = verbose)\n # n <- ncol(M)\n # m <- nrow(M)\n # bac <- paste0(\"Z\", memo, \".temp.bin\")\n # des <- paste0(\"Z\", memo, \".temp.desc\")\n # if (file.exists(bac)) file.remove(bac)\n # if (file.exists(des)) file.remove(des)\n # #options(bigmemory.typecast.warning=FALSE)\n # Z <- big.matrix(\n # nrow = m,\n # ncol = n,\n # type = \"double\",\n # backingfile = bac, \n # descriptorfile = des,\n # init = 0.1\n # )\n # Pi <- NULL\n # estimate.memory <- function(dat, integer=FALSE, raw=FALSE){\n # cells.per.gb <- 2^27 # size of double() resulting in ~1GB of memory use by R 2.15\n # dimz <- dat\n # if(length(dimz) == 1) { dimz[2] <- 1 }\n # if(length(dimz)>1 & length(dimz)<11 & is.numeric(dimz)) {\n # total.size <- as.double(1)\n # for(cc in 1:length(dimz)) { total.size <- as.double(total.size * as.double(dimz[cc])) }\n # memory.estimate <- as.double(as.double(total.size)/cells.per.gb)\n # memory.estimate <- memory.estimate\n # if(integer) { memory.estimate <- memory.estimate/2 } else { if(raw) { memory.estimate <- memory.estimate/8 } }\n # return(memory.estimate)\n # } else {\n # # guessing this is a vector\n # if(!is.list(dimz) & is.vector(dimz)) {\n # LL <- length(dimz)\n # return(estimate.memory(LL, integer=integer, raw=raw))\n # } else {\n # warning(\"tried to estimate memory for object which is neither a vector, pair of dimension sizes or a dataframe/matrix\")\n # }\n # }\n # }\n # if((Sys.info()[['sysname']]) == 'Windows'){\n # max.gb <- memory.limit()/1000\n # }else{\n # max.gb <- Inf\n # }\n # maxLines.gb <- estimate.memory(c(maxLine, n))\n # if(maxLines.gb > max.gb) stop(\"Memory limited! Please reset the 'maxLine'\")\n # loop.index <- seq(0, m, maxLine)[-1]\n # if(max(loop.index) < m) loop.index <- c(loop.index, m)\n # loop.len <- length(loop.index)\n # print(\"Z assignment...\")\n # for(cc in 1:loop.len){\n # if(loop.len == 1){\n # c1 <- 1\n # }else{\n # c1 <- ifelse(cc == loop.len, (loop.index[cc-1]) + 1, loop.index[cc]-maxLine + 1)\n # }\n # c2 <- loop.index[cc]\n # means <-rowMeans(M[c1:c2, 1:n])\n # if(!is.null(weight)){\n # Z[c1:c2, 1:n] <- (M[c1:c2, 1:n]-means) * sqrt(weight[c1:c2])\n # }else{\n # Z[c1:c2, 1:n] <- M[c1:c2, 1:n]-means\n # }\n # Pi <- c(Pi, 0.5 * means);gc()\n # }\n # print(\"Assignment DONE!\")\n # if(is.null(SUM)){\n # SUM <- sum(Pi * (1-Pi))\n # }\n # fl.suc <- flush(Z)\n # if(!fl.suc){ stop(\"flush failed\\n\") } \n # RR <- describe(Z); rm(list=c(\"Z\", \"Pi\", \"means\")); gc()\n # Z <- attach.big.matrix(RR)\n # print(\"Computing Z'Z in big.matrix...\")\n # K <- 0.5 * big.crossprod(Z)/SUM\n # rm(Z)\n # gc()\n # unlink(c(paste0(\"Z\", memo, \".temp.bin\"), paste0(\"Z\", memo, \".temp.desc\")), recursive = TRUE)\n }\n )\n #print(\"K Preparation is Done!\")\n logging.log(\"Deriving relationship matrix successfully\", \"\\n\", verbose = verbose); gc()\n return(K)\n}#end of MVP.k.VanRaden function\n\n", "meta": {"hexsha": "0ffff2cdaa924a8f6803b6079689cbbb5fa1e0c3", "size": 6530, "ext": "r", "lang": "R", "max_stars_repo_path": "R/MVP.K.VanRaden.r", "max_stars_repo_name": "hxxonly/rMVP", "max_stars_repo_head_hexsha": "9c3564f90bc436f6676774f9a80129df7811fb37", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2022-03-14T02:20:21.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T02:20:21.000Z", "max_issues_repo_path": "R/MVP.K.VanRaden.r", "max_issues_repo_name": "hxxonly/rMVP", "max_issues_repo_head_hexsha": "9c3564f90bc436f6676774f9a80129df7811fb37", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/MVP.K.VanRaden.r", "max_forks_repo_name": "hxxonly/rMVP", "max_forks_repo_head_hexsha": "9c3564f90bc436f6676774f9a80129df7811fb37", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.5590062112, "max_line_length": 145, "alphanum_fraction": 0.4901990812, "num_tokens": 1739, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7122321964553657, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.3921602933396667}} {"text": "#########\n# Rafael Aparecido Martins Frade - Central European University\n# Replication code for paper: \n# Does payroll tax relief increase employment level? Evidence from Brazil - 2020\n# This script runs the regressions\n#########\n\nsetwd('/home/rafael/arquivos/mestrado/2_term/metrics_II/paper/dataset')\nset.seed(123456)\nrequire(data.table)\nlibrary(stargazer)\n\n# Descriptive table\nfirmsNS2010 = fread('firms2010.csv')\nfirmsNS2011 = fread('firms2011.csv')\nfirmsNS2012 = fread('firms2012.csv')\nfirmsNS2013 = fread('firms2013.csv')\n\nsummary(firmsNS2013[eligible == 1 & Ind.Simples == 0]$Qtd.Vínculos.CLT)\nsummary(firmsNS2013[eligible == 0 & Ind.Simples == 0]$Qtd.Vínculos.CLT)\nsummary(firmsNS2013[eligible == 1 & Ind.Simples == 1]$Qtd.Vínculos.CLT)\nsummary(firmsNS2013[eligible == 0 & Ind.Simples == 1]$Qtd.Vínculos.CLT)\n\nfirmsNS2013[eligible == 1 & Ind.Simples == 0, .N]\nfirmsNS2013[eligible == 0 & Ind.Simples == 0, .N]\nfirmsNS2013[eligible == 1 & Ind.Simples == 1, .N]\nfirmsNS2013[eligible == 0 & Ind.Simples == 1, .N]\n\n# Non-SIMPLES\nfirmsNS2010 = fread('firms2010.csv')[Ind.Simples == 0]\nfirmsNS2011 = fread('firms2011.csv')[Ind.Simples == 0]\nfirmsNS2012 = fread('firms2012.csv')[Ind.Simples == 0]\nfirmsNS2013 = fread('firms2013.csv')[Ind.Simples == 0]\n\nfirmsNS2012$year = 1\nfirmsModel = rbind(firmsNS2010, firmsNS2011, firmsNS2012)\nfirmsModel$treated = firmsModel$eligible\nmodelNS12 = lm(log(Qtd.Vínculos.CLT) ~ year*treated, data = firmsModel)\n\nfirmsNS2012$year = 0\nfirmsModel = rbind(firmsNS2010, firmsNS2011, firmsNS2012, firmsNS2013)\nfirmsModel$treated = firmsModel$eligible\nmodelNS13 = lm(log(Qtd.Vínculos.CLT) ~ year*treated, data = firmsModel)\n\nsummary(firmsModel)\n\nteste[eligible == 1 & Ind.Simples == 1, .N]\nteste[eligible == 1 & Ind.Simples == 0, .N]\nteste[eligible == 0 & Ind.Simples == 1, .N]\nteste[eligible == 0 & Ind.Simples == 0, .N]\n\n#SIMPLES\nfirmsS2010 = fread('firms2010.csv')[Qtd.Vínculos.CLT <= 100]\nfirmsS2011 = fread('firms2011.csv')[Qtd.Vínculos.CLT <= 100]\nfirmsS2012 = fread('firms2012.csv')[Qtd.Vínculos.CLT <= 100]\nfirmsS2013 = fread('firms2013.csv')[Qtd.Vínculos.CLT <= 100]\n\nfirmsS2012$year = 1\nfirmsModel = rbind(firmsS2010, firmsS2011, firmsS2012)\nfirmsModel$treated = as.numeric(!firmsModel$Ind.Simples)\nmodelSNS12 = lm(log(Qtd.Vínculos.CLT) ~ year*treated, data = firmsModel[eligible == 1])\n\nfirmsS2012$year = 0\nfirmsModel = rbind(firmsS2010, firmsS2011, firmsS2012, firmsS2013)\nfirmsModel$treated = as.numeric(!firmsModel$Ind.Simples)\nmodelSNS13 = lm(log(Qtd.Vínculos.CLT) ~ year*treated, data = firmsModel[eligible == 1])\n\nstargazer(modelSNS12, modelSNS13,modelNS12, modelNS13, \n title = \"Diff in Diff results\",\n dep.var.labels = \"Formal Jobs\",\n column.separate = 1,\n column.labels = c(\"SIMPLES 12\", \"SIMPLES 13\", \"Standard 12\", \"Standard 13\"),\n covariate.labels = c(\n \"Year\", \"Treated\", \"Year.Treated (ATE)\", \"Intercept\"),\n digits = 2,\n df = FALSE)\n\n\n\n\n\ndata2011 = fread('firms2011.csv')\ngroups2011NS = data2011[eligible == 1 & Ind.Simples == 0 ,sum(Qtd.Vínculos.CLT), by = CNAE.2.0.Classe]\ngroups2011Simples = data2011[eligible == 1 & Ind.Simples == 1 ,sum(Qtd.Vínculos.CLT), by = CNAE.2.0.Classe]\n\ndata2012 = fread('firms2012.csv')\ndata2012$year = 1\ngroups2012NS = data2012[eligible == 1 & Ind.Simples == 0 ,sum(Qtd.Vínculos.CLT), by = CNAE.2.0.Classe]\ngroups2012Simples = data2012[eligible == 1 & Ind.Simples == 1 ,sum(Qtd.Vínculos.CLT), by = CNAE.2.0.Classe]\n\ndata2013 = fread('firms2013.csv')\ngroups2013NS = data2013[eligible == 1 & Ind.Simples == 0 ,sum(Qtd.Vínculos.CLT), by = CNAE.2.0.Classe]\ngroups2013Simples = data2013[eligible == 1 & Ind.Simples == 1 ,sum(Qtd.Vínculos.CLT), by = CNAE.2.0.Classe]\n\ndifferenceFirmsSimples1211 = numeric(0)\ndifferenceFirmsNSimples1211 = numeric(0)\n\ndifferenceFirmsSimples1312 = numeric(0)\ndifferenceFirmsNSimples1312 = numeric(0)\n\nfor (index in 1:154) {\n \n cnae = groups2012Simples[index]$CNAE.2.0.Classe\n \n firmsSimples2011 = groups2011Simples[CNAE.2.0.Classe == cnae]$V1\n firmsSimples2012 = groups2012Simples[CNAE.2.0.Classe == cnae]$V1\n firmsSimples2013 = groups2013Simples[CNAE.2.0.Classe == cnae]$V1\n\n firmsNSimples2011 = groups2011NS[CNAE.2.0.Classe == cnae]$V1\n firmsNSimples2012 = groups2012NS[CNAE.2.0.Classe == cnae]$V1\n firmsNSimples2013 = groups2013NS[CNAE.2.0.Classe == cnae]$V1\n\n differenceFirmsSimples1211[index] = firmsSimples2012 - firmsSimples2011\n differenceFirmsNSimples1211[index] = firmsNSimples2012 - firmsNSimples2011\n\n differenceFirmsSimples1312[index] = firmsSimples2013 - firmsSimples2012\n differenceFirmsNSimples1312[index] = firmsNSimples2013 - firmsNSimples2012\n print(paste(cnae, ))\n}\n$Qtd.Vínculos.CLT\nprintQtt = function(cnae, diffS1211, diffNS1211, diffS1312, diffNS1312) {\n \n}\n\nsum(differenceFirmsNSimples1211[1:152])\nsum(differenceFirmsSimples1211[1:152])\nsum(differenceFirmsNSimples1312[1:151])\nsum(differenceFirmsSimples1312[1:151])\n\n\ndiffNS1211 = data.frame(jobs = differenceFirmsNSimples1211, year = 0, simples = 0)\ndiffS1211 = data.frame(jobs = differenceFirmsSimples1211, year = 0, simples = 1)\n\ndiffNS1312 = data.frame(jobs = differenceFirmsNSimples1312, year = 1, simples = 0)\ndiffS1312 = data.frame(jobs = differenceFirmsSimples1312, year = 1, simples = 1)\n\ndiffData = rbind(diffNS1211, diffS1211, diffNS1312, diffS1312)\ndiffData$eligible = as.numeric(!diffData$simples)\ndiffData$year_treated = diffData$treated*diffData$year\n\nmodelDiff = lm(log(jobs) ~ eligible*year, data = diffData)\nsummary(modelDiff)\n\n", "meta": {"hexsha": "8783d2b0f27f029f9ca0f46667abcf2319878009", "size": 5526, "ext": "r", "lang": "R", "max_stars_repo_path": "frade2020_model.r", "max_stars_repo_name": "rfrade/frade2020taxRelief", "max_stars_repo_head_hexsha": "c627b549d8a699f32fba3cf1c7f4332266bbb13b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "frade2020_model.r", "max_issues_repo_name": "rfrade/frade2020taxRelief", "max_issues_repo_head_hexsha": "c627b549d8a699f32fba3cf1c7f4332266bbb13b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "frade2020_model.r", "max_forks_repo_name": "rfrade/frade2020taxRelief", "max_forks_repo_head_hexsha": "c627b549d8a699f32fba3cf1c7f4332266bbb13b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 38.375, "max_line_length": 107, "alphanum_fraction": 0.7283749548, "num_tokens": 2059, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6113819732941511, "lm_q2_score": 0.6406358479787609, "lm_q1q2_score": 0.39167320890022667}} {"text": "\n\nemma.kinship <- function(snps, method=\"additive\", use=\"all\") {\n n0 <- sum(snps==0,na.rm=TRUE)\n nh <- sum(snps==0.5,na.rm=TRUE)\n n1 <- sum(snps==1,na.rm=TRUE)\n nNA <- sum(is.na(snps))\n\n stopifnot(n0+nh+n1+nNA == length(snps))\n\n if ( method == \"dominant\" ) {\n flags <- matrix(as.double(rowMeans(snps,na.rm=TRUE) > 0.5),nrow(snps),ncol(snps))\n snps[!is.na(snps) & (snps == 0.5)] <- flags[!is.na(snps) & (snps == 0.5)]\n }\n else if ( method == \"recessive\" ) {\n flags <- matrix(as.double(rowMeans(snps,na.rm=TRUE) < 0.5),nrow(snps),ncol(snps))\n snps[!is.na(snps) & (snps == 0.5)] <- flags[!is.na(snps) & (snps == 0.5)]\n }\n else if ( ( method == \"additive\" ) && ( nh > 0 ) ) {\n dsnps <- snps\n rsnps <- snps\n flags <- matrix(as.double(rowMeans(snps,na.rm=TRUE) > 0.5),nrow(snps),ncol(snps))\n dsnps[!is.na(snps) & (snps==0.5)] <- flags[!is.na(snps) & (snps==0.5)]\n flags <- matrix(as.double(rowMeans(snps,na.rm=TRUE) < 0.5),nrow(snps),ncol(snps))\n rsnps[!is.na(snps) & (snps==0.5)] <- flags[!is.na(snps) & (snps==0.5)]\n snps <- rbind(dsnps,rsnps)\n }\n\n if ( use == \"all\" ) {\n mafs <- matrix(rowMeans(snps,na.rm=TRUE),nrow(snps),ncol(snps))\n snps[is.na(snps)] <- mafs[is.na(snps)]\n }\n else if ( use == \"complete.obs\" ) {\n snps <- snps[rowSums(is.na(snps))==0,]\n }\n\n n <- ncol(snps)\n K <- matrix(nrow=n,ncol=n)\n diag(K) <- 1\n\n for(i in 2:n) {\n for(j in 1:(i-1)) {\n x <- snps[,i]*snps[,j] + (1-snps[,i])*(1-snps[,j])\n K[i,j] <- sum(x,na.rm=TRUE)/sum(!is.na(x))\n K[j,i] <- K[i,j]\n }\n }\n return(K)\n}\n\nemma.eigen.L <- function(Z,K,complete=TRUE) {\n if ( is.null(Z) ) {\n return(emma.eigen.L.wo.Z(K))\n }\n else {\n return(emma.eigen.L.w.Z(Z,K,complete))\n }\n}\n\nemma.eigen.L.wo.Z <- function(K) {\n eig <- eigen(K,symmetric=TRUE)\n return(list(values=eig$values,vectors=eig$vectors))\n}\n\nemma.eigen.L.w.Z <- function(Z,K,complete=TRUE) {\n if ( complete == FALSE ) {\n vids <- colSums(Z)>0\n Z <- Z[,vids]\n K <- K[vids,vids]\n }\n eig <- eigen(K%*%crossprod(Z,Z),symmetric=FALSE,EISPACK=TRUE)\n return(list(values=eig$values,vectors=qr.Q(qr(Z%*%eig$vectors),complete=TRUE)))\n}\n\nemma.eigen.R <- function(Z,K,X,complete=TRUE) {\n if ( ncol(X) == 0 ) {\n return(emma.eigen.L(Z,K))\n }\n else if ( is.null(Z) ) {\n return(emma.eigen.R.wo.Z(K,X))\n }\n else {\n return(emma.eigen.R.w.Z(Z,K,X,complete))\n }\n}\n\nemma.eigen.R.wo.Z <- function(K, X) {\n n <- nrow(X)\n q <- ncol(X)\n S <- diag(n)-X%*%solve(crossprod(X,X))%*%t(X)\n eig <- eigen(S%*%(K+diag(1,n))%*%S,symmetric=TRUE)\n stopifnot(!is.complex(eig$values))\n return(list(values=eig$values[1:(n-q)]-1,vectors=eig$vectors[,1:(n-q)]))\n}\n\nemma.eigen.R.w.Z <- function(Z, K, X, complete = TRUE) {\n if ( complete == FALSE ) {\n vids <- colSums(Z) > 0\n Z <- Z[,vids]\n K <- K[vids,vids]\n }\n n <- nrow(Z)\n t <- ncol(Z)\n q <- ncol(X)\n \n SZ <- Z - X%*%solve(crossprod(X,X))%*%crossprod(X,Z)\n eig <- eigen(K%*%crossprod(Z,SZ),symmetric=FALSE,EISPACK=TRUE)\n if ( is.complex(eig$values) ) {\n eig$values <- Re(eig$values)\n eig$vectors <- Re(eig$vectors) \n }\n qr.X <- qr.Q(qr(X))\n return(list(values=eig$values[1:(t-q)],\n vectors=qr.Q(qr(cbind(SZ%*%eig$vectors[,1:(t-q)],qr.X)),\n complete=TRUE)[,c(1:(t-q),(t+1):n)])) \n}\n\nemma.delta.ML.LL.wo.Z <- function(logdelta, lambda, etas, xi) {\n n <- length(xi)\n delta <- exp(logdelta)\n return( 0.5*(n*(log(n/(2*pi))-1-log(sum((etas*etas)/(lambda+delta))))-sum(log(xi+delta))) ) \n}\n\nemma.delta.ML.LL.w.Z <- function(logdelta, lambda, etas.1, xi.1, n, etas.2.sq ) {\n t <- length(xi.1)\n delta <- exp(logdelta)\n# stopifnot(length(lambda) == length(etas.1))\n return( 0.5*(n*(log(n/(2*pi))-1-log(sum(etas.1*etas.1/(lambda+delta))+etas.2.sq/delta))-(sum(log(xi.1+delta))+(n-t)*logdelta)) )\n}\n\nemma.delta.ML.dLL.wo.Z <- function(logdelta, lambda, etas, xi) {\n n <- length(xi)\n delta <- exp(logdelta)\n etasq <- etas*etas\n ldelta <- lambda+delta\n return( 0.5*(n*sum(etasq/(ldelta*ldelta))/sum(etasq/ldelta)-sum(1/(xi+delta))) )\n}\n\nemma.delta.ML.dLL.w.Z <- function(logdelta, lambda, etas.1, xi.1, n, etas.2.sq ) {\n t <- length(xi.1)\n delta <- exp(logdelta)\n etasq <- etas.1*etas.1\n ldelta <- lambda+delta\n return( 0.5*(n*(sum(etasq/(ldelta*ldelta))+etas.2.sq/(delta*delta))/(sum(etasq/ldelta)+etas.2.sq/delta)-(sum(1/(xi.1+delta))+(n-t)/delta) ) )\n}\n\nemma.delta.REML.LL.wo.Z <- function(logdelta, lambda, etas) {\n nq <- length(etas)\n delta <- exp(logdelta)\n return( 0.5*(nq*(log(nq/(2*pi))-1-log(sum(etas*etas/(lambda+delta))))-sum(log(lambda+delta))) )\n}\n\nemma.delta.REML.LL.w.Z <- function(logdelta, lambda, etas.1, n, t, etas.2.sq ) {\n tq <- length(etas.1)\n nq <- n - t + tq\n delta <- exp(logdelta)\n return( 0.5*(nq*(log(nq/(2*pi))-1-log(sum(etas.1*etas.1/(lambda+delta))+etas.2.sq/delta))-(sum(log(lambda+delta))+(n-t)*logdelta)) ) \n}\n\nemma.delta.REML.dLL.wo.Z <- function(logdelta, lambda, etas) {\n nq <- length(etas)\n delta <- exp(logdelta)\n etasq <- etas*etas\n ldelta <- lambda+delta\n return( 0.5*(nq*sum(etasq/(ldelta*ldelta))/sum(etasq/ldelta)-sum(1/ldelta)) )\n}\n\nemma.delta.REML.dLL.w.Z <- function(logdelta, lambda, etas.1, n, t1, etas.2.sq ) {\n t <- t1\n tq <- length(etas.1)\n nq <- n - t + tq\n delta <- exp(logdelta)\n etasq <- etas.1*etas.1\n ldelta <- lambda+delta\n return( 0.5*(nq*(sum(etasq/(ldelta*ldelta))+etas.2.sq/(delta*delta))/(sum(etasq/ldelta)+etas.2.sq/delta)-(sum(1/ldelta)+(n-t)/delta)) )\n}\n\nemma.MLE <- function(y, X, K, Z=NULL, ngrids=100, llim=-10, ulim=10,\n esp=1e-10, eig.L = NULL, eig.R = NULL)\n{\n n <- length(y)\n t <- nrow(K)\n q <- ncol(X)\n \n# stopifnot(nrow(K) == t)\n stopifnot(ncol(K) == t)\n stopifnot(nrow(X) == n)\n\n if ( det(crossprod(X,X)) == 0 ) {\n warning(\"X is singular\")\n return (list(ML=0,delta=0,ve=0,vg=0))\n }\n\n if ( is.null(Z) ) {\n if ( is.null(eig.L) ) {\n eig.L <- emma.eigen.L.wo.Z(K)\n }\n if ( is.null(eig.R) ) {\n eig.R <- emma.eigen.R.wo.Z(K,X)\n }\n etas <- crossprod(eig.R$vectors,y)\n \n \n logdelta <- (0:ngrids)/ngrids*(ulim-llim)+llim\n m <- length(logdelta)\n delta <- exp(logdelta)\n Lambdas <- matrix(eig.R$values,n-q,m) + matrix(delta,n-q,m,byrow=TRUE)\n Xis <- matrix(eig.L$values,n,m) + matrix(delta,n,m,byrow=TRUE)\n Etasq <- matrix(etas*etas,n-q,m)\n LL <- 0.5*(n*(log(n/(2*pi))-1-log(colSums(Etasq/Lambdas)))-colSums(log(Xis)))\n dLL <- 0.5*delta*(n*colSums(Etasq/(Lambdas*Lambdas))/colSums(Etasq/Lambdas)-colSums(1/Xis))\n \n optlogdelta <- vector(length=0)\n optLL <- vector(length=0)\n if ( dLL[1] < esp ) {\n optlogdelta <- append(optlogdelta, llim)\n optLL <- append(optLL, emma.delta.ML.LL.wo.Z(llim,eig.R$values,etas,eig.L$values))\n }\n if ( dLL[m-1] > 0-esp ) {\n optlogdelta <- append(optlogdelta, ulim)\n optLL <- append(optLL, emma.delta.ML.LL.wo.Z(ulim,eig.R$values,etas,eig.L$values))\n }\n\n for( i in 1:(m-1) )\n {\n if ( ( dLL[i]*dLL[i+1] < 0-esp*esp ) && ( dLL[i] > 0 ) && ( dLL[i+1] < 0 ) ) \n {\n r <- uniroot(emma.delta.ML.dLL.wo.Z, lower=logdelta[i], upper=logdelta[i+1], lambda=eig.R$values, etas=etas, xi=eig.L$values)\n optlogdelta <- append(optlogdelta, r$root)\n optLL <- append(optLL, emma.delta.ML.LL.wo.Z(r$root,eig.R$values, etas, eig.L$values))\n }\n }\n# optdelta <- exp(optlogdelta)\n }\n else {\n if ( is.null(eig.L) ) {\n eig.L <- emma.eigen.L.w.Z(Z,K)\n }\n if ( is.null(eig.R) ) {\n eig.R <- emma.eigen.R.w.Z(Z,K,X)\n }\n etas <- crossprod(eig.R$vectors,y)\n etas.1 <- etas[1:(t-q)]\n etas.2 <- etas[(t-q+1):(n-q)]\n etas.2.sq <- sum(etas.2*etas.2)\n\n logdelta <- (0:ngrids)/ngrids*(ulim-llim)+llim\n\n m <- length(logdelta)\n delta <- exp(logdelta)\n Lambdas <- matrix(eig.R$values,t-q,m) + matrix(delta,t-q,m,byrow=TRUE)\n Xis <- matrix(eig.L$values,t,m) + matrix(delta,t,m,byrow=TRUE)\n Etasq <- matrix(etas.1*etas.1,t-q,m)\n #LL <- 0.5*(n*(log(n/(2*pi))-1-log(colSums(Etasq/Lambdas)+etas.2.sq/delta))-colSums(log(Xis))+(n-t)*log(deltas))\n dLL <- 0.5*delta*(n*(colSums(Etasq/(Lambdas*Lambdas))+etas.2.sq/(delta*delta))/(colSums(Etasq/Lambdas)+etas.2.sq/delta)-(colSums(1/Xis)+(n-t)/delta))\n \n optlogdelta <- vector(length=0)\n optLL <- vector(length=0)\n if ( dLL[1] < esp ) {\n optlogdelta <- append(optlogdelta, llim)\n optLL <- append(optLL, emma.delta.ML.LL.w.Z(llim,eig.R$values,etas.1,eig.L$values,n,etas.2.sq))\n }\n if ( dLL[m-1] > 0-esp ) {\n optlogdelta <- append(optlogdelta, ulim)\n optLL <- append(optLL, emma.delta.ML.LL.w.Z(ulim,eig.R$values,etas.1,eig.L$values,n,etas.2.sq))\n }\n\n for( i in 1:(m-1) )\n {\n if ( ( dLL[i]*dLL[i+1] < 0-esp*esp ) && ( dLL[i] > 0 ) && ( dLL[i+1] < 0 ) ) \n {\n r <- uniroot(emma.delta.ML.dLL.w.Z, lower=logdelta[i], upper=logdelta[i+1], lambda=eig.R$values, etas.1=etas.1, xi.1=eig.L$values, n=n, etas.2.sq = etas.2.sq )\n optlogdelta <- append(optlogdelta, r$root)\n optLL <- append(optLL, emma.delta.ML.LL.w.Z(r$root,eig.R$values, etas.1, eig.L$values, n, etas.2.sq ))\n }\n }\n# optdelta <- exp(optlogdelta)\n }\n\n maxdelta <- exp(optlogdelta[which.max(optLL)])\n maxLL <- max(optLL)\n if ( is.null(Z) ) {\n maxva <- sum(etas*etas/(eig.R$values+maxdelta))/n \n }\n else {\n maxva <- (sum(etas.1*etas.1/(eig.R$values+maxdelta))+etas.2.sq/maxdelta)/n\n }\n maxve <- maxva*maxdelta\n\n return (list(ML=maxLL,delta=maxdelta,ve=maxve,vg=maxva))\n}\n\nemma.MLE.noX <- function(y, K, Z=NULL, ngrids=100, llim=-10, ulim=10,\n esp=1e-10, eig.L = NULL)\n{\n n <- length(y)\n t <- nrow(K)\n \n# stopifnot(nrow(K) == t)\n stopifnot(ncol(K) == t)\n\n if ( is.null(Z) ) {\n if ( is.null(eig.L) ) {\n eig.L <- emma.eigen.L.wo.Z(K)\n }\n etas <- crossprod(eig.L$vectors,y)\n \n logdelta <- (0:ngrids)/ngrids*(ulim-llim)+llim\n m <- length(logdelta)\n delta <- exp(logdelta)\n Xis <- matrix(eig.L$values,n,m) + matrix(delta,n,m,byrow=TRUE)\n Etasq <- matrix(etas*etas,n,m)\n LL <- 0.5*(n*(log(n/(2*pi))-1-log(colSums(Etasq/Xis)))-colSums(log(Xis)))\n dLL <- 0.5*delta*(n*colSums(Etasq/(Xis*Xis))/colSums(Etasq/Xis)-colSums(1/Xis))\n \n optlogdelta <- vector(length=0)\n optLL <- vector(length=0)\n #print(dLL)\n if ( dLL[1] < esp ) {\n optlogdelta <- append(optlogdelta, llim)\n optLL <- append(optLL, emma.delta.ML.LL.wo.Z(llim,eig.L$values,etas,eig.L$values))\n }\n if ( dLL[m-1] > 0-esp ) {\n optlogdelta <- append(optlogdelta, ulim)\n optLL <- append(optLL, emma.delta.ML.LL.wo.Z(ulim,eig.L$values,etas,eig.L$values))\n }\n\n for( i in 1:(m-1) )\n {\n #if ( ( dLL[i]*dLL[i+1] < 0 ) && ( dLL[i] > 0 ) && ( dLL[i+1] < 0 ) )\n if ( ( dLL[i]*dLL[i+1] < 0-esp*esp ) && ( dLL[i] > 0 ) && ( dLL[i+1] < 0 ) ) \n {\n r <- uniroot(emma.delta.ML.dLL.wo.Z, lower=logdelta[i], upper=logdelta[i+1], lambda=eig.L$values, etas=etas, xi=eig.L$values)\n optlogdelta <- append(optlogdelta, r$root)\n optLL <- append(optLL, emma.delta.ML.LL.wo.Z(r$root,eig.L$values, etas, eig.L$values))\n }\n }\n# optdelta <- exp(optlogdelta)\n }\n else {\n if ( is.null(eig.L) ) {\n eig.L <- emma.eigen.L.w.Z(Z,K)\n }\n etas <- crossprod(eig.L$vectors,y)\n etas.1 <- etas[1:t]\n etas.2 <- etas[(t+1):n]\n etas.2.sq <- sum(etas.2*etas.2)\n\n logdelta <- (0:ngrids)/ngrids*(ulim-llim)+llim\n\n m <- length(logdelta)\n delta <- exp(logdelta)\n Xis <- matrix(eig.L$values,t,m) + matrix(delta,t,m,byrow=TRUE)\n Etasq <- matrix(etas.1*etas.1,t,m)\n #LL <- 0.5*(n*(log(n/(2*pi))-1-log(colSums(Etasq/Lambdas)+etas.2.sq/delta))-colSums(log(Xis))+(n-t)*log(deltas))\n dLL <- 0.5*delta*(n*(colSums(Etasq/(Xis*Xis))+etas.2.sq/(delta*delta))/(colSums(Etasq/Xis)+etas.2.sq/delta)-(colSums(1/Xis)+(n-t)/delta))\n \n optlogdelta <- vector(length=0)\n optLL <- vector(length=0)\n if ( dLL[1] < esp ) {\n optlogdelta <- append(optlogdelta, llim)\n optLL <- append(optLL, emma.delta.ML.LL.w.Z(llim,eig.L$values,etas.1,eig.L$values,n,etas.2.sq))\n }\n if ( dLL[m-1] > 0-esp ) {\n optlogdelta <- append(optlogdelta, ulim)\n optLL <- append(optLL, emma.delta.ML.LL.w.Z(ulim,eig.L$values,etas.1,eig.L$values,n,etas.2.sq))\n }\n\n for( i in 1:(m-1) )\n {\n if ( ( dLL[i]*dLL[i+1] < 0-esp*esp ) && ( dLL[i] > 0 ) && ( dLL[i+1] < 0 ) ) \n {\n r <- uniroot(emma.delta.ML.dLL.w.Z, lower=logdelta[i], upper=logdelta[i+1], lambda=eig.L$values, etas.1=etas.1, xi.1=eig.L$values, n=n, etas.2.sq = etas.2.sq )\n optlogdelta <- append(optlogdelta, r$root)\n optLL <- append(optLL, emma.delta.ML.LL.w.Z(r$root,eig.L$values, etas.1, eig.L$values, n, etas.2.sq ))\n }\n }\n# optdelta <- exp(optlogdelta)\n }\n\n maxdelta <- exp(optlogdelta[which.max(optLL)])\n maxLL <- max(optLL)\n if ( is.null(Z) ) {\n maxva <- sum(etas*etas/(eig.L$values+maxdelta))/n\n }\n else {\n maxva <- (sum(etas.1*etas.1/(eig.L$values+maxdelta))+etas.2.sq/maxdelta)/n\n }\n maxve <- maxva*maxdelta\n\n return (list(ML=maxLL,delta=maxdelta,ve=maxve,vg=maxva))\n}\n\nemma.REMLE <- function(y, X, K, Z=NULL, ngrids=100, llim=-10, ulim=10,\n esp=1e-10, eig.L = NULL, eig.R = NULL) {\n n <- length(y)\n t <- nrow(K)\n q <- ncol(X)\n\n# stopifnot(nrow(K) == t)\n stopifnot(ncol(K) == t)\n stopifnot(nrow(X) == n)\n\n if ( det(crossprod(X,X)) == 0 ) {\n warning(\"X is singular\")\n return (list(REML=0,delta=0,ve=0,vg=0))\n }\n\n if ( is.null(Z) ) {\n if ( is.null(eig.R) ) {\n eig.R <- emma.eigen.R.wo.Z(K,X)\n }\n etas <- crossprod(eig.R$vectors,y)\n \n logdelta <- (0:ngrids)/ngrids*(ulim-llim)+llim\n m <- length(logdelta)\n delta <- exp(logdelta)\n Lambdas <- matrix(eig.R$values,n-q,m) + matrix(delta,n-q,m,byrow=TRUE)\n Etasq <- matrix(etas*etas,n-q,m)\n LL <- 0.5*((n-q)*(log((n-q)/(2*pi))-1-log(colSums(Etasq/Lambdas)))-colSums(log(Lambdas)))\n dLL <- 0.5*delta*((n-q)*colSums(Etasq/(Lambdas*Lambdas))/colSums(Etasq/Lambdas)-colSums(1/Lambdas))\n \n optlogdelta <- vector(length=0)\n optLL <- vector(length=0)\n if ( dLL[1] < esp ) {\n optlogdelta <- append(optlogdelta, llim)\n optLL <- append(optLL, emma.delta.REML.LL.wo.Z(llim,eig.R$values,etas))\n }\n if ( dLL[m-1] > 0-esp ) {\n optlogdelta <- append(optlogdelta, ulim)\n optLL <- append(optLL, emma.delta.REML.LL.wo.Z(ulim,eig.R$values,etas))\n }\n\n for( i in 1:(m-1) )\n {\n if ( ( dLL[i]*dLL[i+1] < 0-esp*esp ) && ( dLL[i] > 0 ) && ( dLL[i+1] < 0 ) ) \n {\n r <- uniroot(emma.delta.REML.dLL.wo.Z, lower=logdelta[i], upper=logdelta[i+1], lambda=eig.R$values, etas=etas)\n optlogdelta <- append(optlogdelta, r$root)\n optLL <- append(optLL, emma.delta.REML.LL.wo.Z(r$root,eig.R$values, etas))\n }\n }\n# optdelta <- exp(optlogdelta)\n }\n else {\n if ( is.null(eig.R) ) {\n eig.R <- emma.eigen.R.w.Z(Z,K,X)\n }\n etas <- crossprod(eig.R$vectors,y)\n etas.1 <- etas[1:(t-q)]\n etas.2 <- etas[(t-q+1):(n-q)]\n etas.2.sq <- sum(etas.2*etas.2)\n \n logdelta <- (0:ngrids)/ngrids*(ulim-llim)+llim\n m <- length(logdelta)\n delta <- exp(logdelta)\n Lambdas <- matrix(eig.R$values,t-q,m) + matrix(delta,t-q,m,byrow=TRUE)\n Etasq <- matrix(etas.1*etas.1,t-q,m)\n dLL <- 0.5*delta*((n-q)*(colSums(Etasq/(Lambdas*Lambdas))+etas.2.sq/(delta*delta))/(colSums(Etasq/Lambdas)+etas.2.sq/delta)-(colSums(1/Lambdas)+(n-t)/delta))\n \n optlogdelta <- vector(length=0)\n optLL <- vector(length=0)\n if ( dLL[1] < esp ) {\n optlogdelta <- append(optlogdelta, llim)\n optLL <- append(optLL, emma.delta.REML.LL.w.Z(llim,eig.R$values,etas.1,n,t,etas.2.sq))\n }\n if ( dLL[m-1] > 0-esp ) {\n optlogdelta <- append(optlogdelta, ulim)\n optLL <- append(optLL, emma.delta.REML.LL.w.Z(ulim,eig.R$values,etas.1,n,t,etas.2.sq))\n }\n\n for( i in 1:(m-1) )\n {\n if ( ( dLL[i]*dLL[i+1] < 0-esp*esp ) && ( dLL[i] > 0 ) && ( dLL[i+1] < 0 ) ) \n {\n r <- uniroot(emma.delta.REML.dLL.w.Z, lower=logdelta[i], upper=logdelta[i+1], lambda=eig.R$values, etas.1=etas.1, n=n, t1=t, etas.2.sq = etas.2.sq )\n optlogdelta <- append(optlogdelta, r$root)\n optLL <- append(optLL, emma.delta.REML.LL.w.Z(r$root,eig.R$values, etas.1, n, t, etas.2.sq ))\n }\n }\n# optdelta <- exp(optlogdelta)\n } \n\n maxdelta <- exp(optlogdelta[which.max(optLL)])\n maxLL <- max(optLL)\n if ( is.null(Z) ) {\n maxva <- sum(etas*etas/(eig.R$values+maxdelta))/(n-q) \n }\n else {\n maxva <- (sum(etas.1*etas.1/(eig.R$values+maxdelta))+etas.2.sq/maxdelta)/(n-q)\n }\n maxve <- maxva*maxdelta\n\n return (list(REML=maxLL,delta=maxdelta,ve=maxve,vg=maxva))\n}\n\nemma.ML.LRT <- function(ys, xs, K, Z=NULL, X0 = NULL, ngrids=100, llim=-10, ulim=10, esp=1e-10, ponly = FALSE) {\n if ( is.null(dim(ys)) || ncol(ys) == 1 ) {\n ys <- matrix(ys,1,length(ys))\n }\n if ( is.null(dim(xs)) || ncol(xs) == 1 ) {\n xs <- matrix(xs,1,length(xs))\n }\n if ( is.null(X0) ) {\n X0 <- matrix(1,ncol(ys),1)\n } \n \n g <- nrow(ys)\n n <- ncol(ys)\n m <- nrow(xs)\n t <- ncol(xs)\n q0 <- ncol(X0)\n q1 <- q0 + 1\n\n if ( !ponly ) {\n ML1s <- matrix(nrow=m,ncol=g)\n ML0s <- matrix(nrow=m,ncol=g)\n vgs <- matrix(nrow=m,ncol=g)\n ves <- matrix(nrow=m,ncol=g)\n }\n stats <- matrix(nrow=m,ncol=g)\n ps <- matrix(nrow=m,ncol=g)\n ML0 <- vector(length=g)\n \n stopifnot(nrow(K) == t)\n stopifnot(ncol(K) == t)\n stopifnot(nrow(X0) == n)\n\n if ( sum(is.na(ys)) == 0 ) {\n eig.L <- emma.eigen.L(Z,K)\n eig.R0 <- emma.eigen.R(Z,K,X0)\n \n for(i in 1:g) {\n ML0[i] <- emma.MLE(ys[i,],X0,K,Z,ngrids,llim,ulim,esp,eig.L,eig.R0)$ML\n }\n\n x.prev <- vector(length=0)\n \n for(i in 1:m) {\n vids <- !is.na(xs[i,])\n nv <- sum(vids)\n xv <- xs[i,vids]\n\n if ( ( mean(xv) <= 0 ) || ( mean(xv) >= 1 ) ) {\n if (!ponly) {\n stats[i,] <- rep(NA,g)\n vgs[i,] <- rep(NA,g)\n ves[i,] <- rep(NA,g)\n ML1s[i,] <- rep(NA,g)\n ML0s[i,] <- rep(NA,g)\n }\n ps[i,] = rep(1,g)\n }\n else if ( identical(x.prev, xv) ) {\n if ( !ponly ) {\n stats[i,] <- stats[i-1,]\n vgs[i,] <- vgs[i-1,]\n ves[i,] <- ves[i-1,]\n ML1s[i,] <- ML1s[i-1,]\n ML0s[i,] <- ML0s[i-1,]\n }\n ps[i,] <- ps[i-1,]\n }\n else {\n if ( is.null(Z) ) {\n X <- cbind(X0[vids,,drop=FALSE],xs[i,vids])\n eig.R1 = emma.eigen.R.wo.Z(K[vids,vids],X)\n }\n else {\n vrows <- as.logical(rowSums(Z[,vids]))\n nr <- sum(vrows)\n X <- cbind(X0[vrows,,drop=FALSE],Z[vrows,vids]%*%t(xs[i,vids,drop=FALSE]))\n eig.R1 = emma.eigen.R.w.Z(Z[vrows,vids],K[vids,vids],X) \n }\n\n for(j in 1:g) {\n if ( nv == t ) {\n MLE <- emma.MLE(ys[j,],X,K,Z,ngrids,llim,ulim,esp,eig.L,eig.R1)\n# MLE <- emma.MLE(ys[j,],X,K,Z,ngrids,llim,ulim,esp,eig.L,eig.R1) \n if (!ponly) { \n ML1s[i,j] <- MLE$ML\n vgs[i,j] <- MLE$vg\n ves[i,j] <- MLE$ve\n }\n stats[i,j] <- 2*(MLE$ML-ML0[j])\n \n }\n else {\n if ( is.null(Z) ) {\n eig.L0 <- emma.eigen.L.wo.Z(K[vids,vids])\n MLE0 <- emma.MLE(ys[j,vids],X0[vids,,drop=FALSE],K[vids,vids],NULL,ngrids,llim,ulim,esp,eig.L0)\n MLE1 <- emma.MLE(ys[j,vids],X,K[vids,vids],NULL,ngrids,llim,ulim,esp,eig.L0)\n }\n else {\n if ( nr == n ) {\n MLE1 <- emma.MLE(ys[j,],X,K,Z,ngrids,llim,ulim,esp,eig.L)\n }\n else {\n eig.L0 <- emma.eigen.L.w.Z(Z[vrows,vids],K[vids,vids]) \n MLE0 <- emma.MLE(ys[j,vrows],X0[vrows,,drop=FALSE],K[vids,vids],Z[vrows,vids],ngrids,llim,ulim,esp,eig.L0)\n MLE1 <- emma.MLE(ys[j,vrows],X,K[vids,vids],Z[vrows,vids],ngrids,llim,ulim,esp,eig.L0)\n }\n }\n if (!ponly) { \n ML1s[i,j] <- MLE1$ML\n ML0s[i,j] <- MLE0$ML\n vgs[i,j] <- MLE1$vg\n ves[i,j] <- MLE1$ve\n }\n stats[i,j] <- 2*(MLE1$ML-MLE0$ML)\n }\n }\n if ( ( nv == t ) && ( !ponly ) ) {\n ML0s[i,] <- ML0\n }\n ps[i,] <- pchisq(stats[i,],1,lower.tail=FALSE)\n }\n }\n }\n else {\n eig.L <- emma.eigen.L(Z,K)\n eig.R0 <- emma.eigen.R(Z,K,X0)\n \n for(i in 1:g) {\n vrows <- !is.na(ys[i,]) \n if ( is.null(Z) ) {\n ML0[i] <- emma.MLE(ys[i,vrows],X0[vrows,,drop=FALSE],K[vrows,vrows],NULL,ngrids,llim,ulim,esp)$ML\n }\n else {\n vids <- colSums(Z[vrows,]>0)\n \n ML0[i] <- emma.MLE(ys[i,vrows],X0[vrows,,drop=FALSE],K[vids,vids],Z[vrows,vids],ngrids,llim,ulim,esp)$ML \n }\n }\n\n x.prev <- vector(length=0)\n \n for(i in 1:m) {\n vids <- !is.na(xs[i,])\n nv <- sum(vids)\n xv <- xs[i,vids]\n\n if ( ( mean(xv) <= 0 ) || ( mean(xv) >= 1 ) ) {\n if (!ponly) {\n stats[i,] <- rep(NA,g)\n vgs[i,] <- rep(NA,g)\n ves[i,] <- rep(NA,g)\n ML1s[i,] <- rep(NA,g)\n ML0s[,i] <- rep(NA,g)\n }\n ps[i,] = rep(1,g)\n } \n else if ( identical(x.prev, xv) ) {\n if ( !ponly ) {\n stats[i,] <- stats[i-1,]\n vgs[i,] <- vgs[i-1,]\n ves[i,] <- ves[i-1,]\n ML1s[i,] <- ML1s[i-1,]\n }\n ps[i,] = ps[i-1,]\n }\n else {\n if ( is.null(Z) ) {\n X <- cbind(X0,xs[i,])\n if ( nv == t ) {\n eig.R1 = emma.eigen.R.wo.Z(K,X)\n } \n }\n else {\n vrows <- as.logical(rowSums(Z[,vids]))\n X <- cbind(X0,Z[,vids,drop=FALSE]%*%t(xs[i,vids,drop=FALSE]))\n if ( nv == t ) {\n eig.R1 = emma.eigen.R.w.Z(Z,K,X)\n }\n }\n\n for(j in 1:g) {\n# print(j)\n vrows <- !is.na(ys[j,])\n if ( nv == t ) {\n nr <- sum(vrows)\n if ( is.null(Z) ) {\n if ( nr == n ) {\n MLE <- emma.MLE(ys[j,],X,K,NULL,ngrids,llim,ulim,esp,eig.L,eig.R1) \n }\n else {\n MLE <- emma.MLE(ys[j,vrows],X[vrows,],K[vrows,vrows],NULL,ngrids,llim,ulim,esp)\n }\n }\n else {\n if ( nr == n ) {\n MLE <- emma.MLE(ys[j,],X,K,Z,ngrids,llim,ulim,esp,eig.L,eig.R1) \n }\n else {\n vtids <- as.logical(colSums(Z[vrows,,drop=FALSE]))\n MLE <- emma.MLE(ys[j,vrows],X[vrows,],K[vtids,vtids],Z[vrows,vtids],ngrids,llim,ulim,esp)\n }\n }\n \n if (!ponly) { \n ML1s[i,j] <- MLE$ML\n vgs[i,j] <- MLE$vg\n ves[i,j] <- MLE$ve\n }\n stats[i,j] <- 2*(MLE$ML-ML0[j])\n }\n else {\n if ( is.null(Z) ) {\n vtids <- vrows & vids\n eig.L0 <- emma.eigen.L(NULL,K[vtids,vtids])\n MLE0 <- emma.MLE(ys[j,vtids],X0[vtids,,drop=FALSE],K[vtids,vtids],NULL,ngrids,llim,ulim,esp,eig.L0)\n MLE1 <- emma.MLE(ys[j,vtids],X[vtids,],K[vtids,vtids],NULL,ngrids,llim,ulim,esp,eig.L0)\n }\n else {\n vtids <- as.logical(colSums(Z[vrows,])) & vids\n vtrows <- vrows & as.logical(rowSums(Z[,vids]))\n eig.L0 <- emma.eigen.L(Z[vtrows,vtids],K[vtids,vtids])\n MLE0 <- emma.MLE(ys[j,vtrows],X0[vtrows,,drop=FALSE],K[vtids,vtids],Z[vtrows,vtids],ngrids,llim,ulim,esp,eig.L0)\n MLE1 <- emma.MLE(ys[j,vtrows],X[vtrows,],K[vtids,vtids],Z[vtrows,vtids],ngrids,llim,ulim,esp,eig.L0)\n }\n if (!ponly) { \n ML1s[i,j] <- MLE1$ML\n vgs[i,j] <- MLE1$vg\n ves[i,j] <- MLE1$ve\n ML0s[i,j] <- MLE0$ML\n }\n stats[i,j] <- 2*(MLE1$ML-MLE0$ML)\n }\n }\n if ( ( nv == t ) && ( !ponly ) ) {\n ML0s[i,] <- ML0\n }\n ps[i,] <- pchisq(stats[i,],1,lower.tail=FALSE)\n }\n } \n }\n if ( ponly ) {\n return (ps)\n }\n else {\n return (list(ps=ps,ML1s=ML1s,ML0s=ML0s,stats=stats,vgs=vgs,ves=ves))\n } \n}\n\nemma.test <- function(ys, xs, K, Z=NULL, x0s = NULL, X0 = NULL, dfxs = 1, dfx0s = 1, use.MLE = FALSE, use.LRT = FALSE, ngrids = 100, llim = -10, ulim = 10, esp=1e-10, ponly = FALSE)\n{\n stopifnot (dfxs > 0)\n \n if ( is.null(dim(ys)) || ncol(ys) == 1 ) {\n ys <- matrix(ys,1,length(ys))\n }\n \n if ( is.null(dim(xs)) || ncol(xs) == 1 ) {\n xs <- matrix(xs,1,length(xs))\n }\n nx <- nrow(xs)/dfxs\n \n if ( is.null(x0s) ) {\n dfx0s = 0\n x0s <- matrix(NA,0,ncol(xs))\n }\n # X0 automatically contains intercept. If no intercept is to be used,\n # X0 should be matrix(nrow=ncol(ys),ncol=0)\n if ( is.null(X0) ) {\n X0 <- matrix(1,ncol(ys),1)\n }\n\n stopifnot(Z == NULL) # The case where Z is not null is not implemented\n\n ny <- nrow(ys)\n iy <- ncol(ys)\n ix <- ncol(xs)\n \n stopifnot(nrow(K) == ix)\n stopifnot(ncol(K) == ix)\n stopifnot(nrow(X0) == iy)\n\n if ( !ponly ) {\n LLs <- matrix(nrow=m,ncol=g)\n vgs <- matrix(nrow=m,ncol=g)\n ves <- matrix(nrow=m,ncol=g)\n }\n dfs <- matrix(nrow=m,ncol=g)\n stats <- matrix(nrow=m,ncol=g)\n ps <- matrix(nrow=m,ncol=g)\n\n # The case with no missing phenotypes\n if ( sum(is.na(ys)) == 0 ) {\n if ( ( use.MLE ) || ( !use.LRT ) ) {\n eig.L0 <- emma.eigen.L(Z,K)\n }\n if ( dfx0s == 0 ) {\n eig.R0 <- emma.eigen.R(Z,K,X0)\n }\n x.prev <- NULL\n\n for(i in 1:ix) {\n x1 <- t(xs[(dfxs*(i-1)+1):(dfxs*i),,drop=FALSE])\n if ( dfxs0 == 0 ) {\n x0 <- X0\n }\n else {\n x0 <- cbind(t(x0s[(dfx0s*(i-1)+1):(dfx0s*i),,drop=FALSE]),X0)\n }\n x <- cbind(x1,x0)\n xvids <- rowSums(is.na(x) == 0)\n nxv <- sum(xvids)\n xv <- x[xvids,,drop=FALSE]\n Kv <- K[xvids,xvids,drop=FALSE]\n yv <- ys[j,xvids]\n\n if ( identical(x.prev, xv) ) {\n if ( !ponly ) {\n vgs[i,] <- vgs[i-1,]\n ves[i,] <- ves[i-1,]\n dfs[i,] <- dfs[i-1,]\n REMLs[i,] <- REMLs[i-1,]\n stats[i,] <- stats[i-1,]\n }\n ps[i,] <- ps[i-1,]\n }\n else {\n eig.R1 = emma.eigen.R.wo.Z(Kv,xv)\n \n for(j in 1:iy) {\n if ( ( use.MLE ) || ( !use.LRT ) ) { \n if ( nxv < t ) {\n # NOTE: this complexity can be improved by avoiding eigen computation for identical missing patterns\n eig.L0v <- emma.eigen.L.wo.Z(Kv) \n }\n else {\n eig.L0v <- eig.L0\n }\n }\n\n if ( use.MLE ) {\n MLE <- emma.REMLE(yv,xv,Kv,NULL,ngrids,llim,ulim,esp,eig.R1)\n stop(\"Not implemented yet\")\n }\n else {\n REMLE <- emma.REMLE(yv,xv,Kv,NULL,ngrids,llim,ulim,esp,eig.R1)\n if ( use.LRT ) {\n stop(\"Not implemented yet\") \n }\n else {\n U <- eig.L0v$vectors * matrix(sqrt(1/(eig.L0v$values+REMLE$delta)),t,t,byrow=TRUE)\n dfs[i,j] <- length(eig.R1$values)\n yt <- crossprod(U,yv)\n xt <- crossprod(U,xv)\n ixx <- solve(crossprod(xt,xt))\n beta <- ixx%*%crossprod(xt,yt)\n if ( dfxs == 1 ) {\n stats[i,j] <- beta[q1]/sqrt(iXX[q1,q1]*REMLE$vg)\n }\n else {\n model.m <- c(rep(1,dfxs),rep(0,ncol(xv)-dfxs))\n stats[i,j] <-\n crossprod(crossprod(solve(crossprod(crossprod(iXX,model.m),\n model.m)),\n model.m*beta),model.m*beta)\n \n }\n if ( !ponly ) {\n vgs[i,j] <- REMLE$vg\n ves[i,j] <- REMLE$ve\n REMLs[i,j] <- REMLE$REML\n }\n }\n }\n }\n if ( dfxs == 1 ) {\n ps[i,] <- 2*pt(abs(stats[i,]),dfs[i,],lower.tail=FALSE)\n }\n else {\n ps[i,] <- pf(abs(stats[i,]),dfs[i,],lower.tail=FALSE) \n }\n }\n }\n }\n # The case with missing genotypes - not implemented yet\n else {\n stop(\"Not implemented yet\")\n eig.L <- emma.eigen.L(Z,K)\n eig.R0 <- emma.eigen.R(Z,K,X0)\n \n x.prev <- vector(length=0)\n \n for(i in 1:m) {\n vids <- !is.na(xs[i,])\n nv <- sum(vids)\n xv <- xs[i,vids]\n\n if ( ( mean(xv) <= 0 ) || ( mean(xv) >= 1 ) ) {\n if (!ponly) {\n vgs[i,] <- rep(NA,g)\n ves[i,] <- rep(NA,g)\n REMLs[i,] <- rep(NA,g)\n dfs[i,] <- rep(NA,g)\n }\n ps[i,] = rep(1,g)\n } \n else if ( identical(x.prev, xv) ) {\n if ( !ponly ) {\n stats[i,] <- stats[i-1,]\n vgs[i,] <- vgs[i-1,]\n ves[i,] <- ves[i-1,]\n REMLs[i,] <- REMLs[i-1,]\n dfs[i,] <- dfs[i-1,]\n }\n ps[i,] = ps[i-1,]\n }\n else {\n if ( is.null(Z) ) {\n X <- cbind(X0,xs[i,])\n if ( nv == t ) {\n eig.R1 = emma.eigen.R.wo.Z(K,X)\n }\n }\n else {\n vrows <- as.logical(rowSums(Z[,vids,drop=FALSE]))\n X <- cbind(X0,Z[,vids,drop=FALSE]%*%t(xs[i,vids,drop=FALSE]))\n if ( nv == t ) {\n eig.R1 = emma.eigen.R.w.Z(Z,K,X)\n } \n }\n\n for(j in 1:g) {\n vrows <- !is.na(ys[j,])\n if ( nv == t ) {\n yv <- ys[j,vrows]\n nr <- sum(vrows)\n if ( is.null(Z) ) {\n if ( nr == n ) {\n REMLE <- emma.REMLE(yv,X,K,NULL,ngrids,llim,ulim,esp,eig.R1)\n U <- eig.L$vectors * matrix(sqrt(1/(eig.L$values+REMLE$delta)),n,n,byrow=TRUE) \n }\n else {\n eig.L0 <- emma.eigen.L.wo.Z(K[vrows,vrows,drop=FALSE])\n REMLE <- emma.REMLE(yv,X[vrows,,drop=FALSE],K[vrows,vrows,drop=FALSE],NULL,ngrids,llim,ulim,esp)\n U <- eig.L0$vectors * matrix(sqrt(1/(eig.L0$values+REMLE$delta)),nr,nr,byrow=TRUE)\n }\n dfs[i,j] <- nr-q1\n }\n else {\n if ( nr == n ) {\n REMLE <- emma.REMLE(yv,X,K,Z,ngrids,llim,ulim,esp,eig.R1)\n U <- eig.L$vectors * matrix(c(sqrt(1/(eig.L$values+REMLE$delta)),rep(sqrt(1/REMLE$delta),n-t)),n,n,byrow=TRUE) \n }\n else {\n vtids <- as.logical(colSums(Z[vrows,,drop=FALSE]))\n eig.L0 <- emma.eigen.L.w.Z(Z[vrows,vtids,drop=FALSE],K[vtids,vtids,drop=FALSE])\n REMLE <- emma.REMLE(yv,X[vrows,,drop=FALSE],K[vtids,vtids,drop=FALSE],Z[vrows,vtids,drop=FALSE],ngrids,llim,ulim,esp)\n U <- eig.L0$vectors * matrix(c(sqrt(1/(eig.L0$values+REMLE$delta)),rep(sqrt(1/REMLE$delta),nr-sum(vtids))),nr,nr,byrow=TRUE)\n }\n dfs[i,j] <- nr-q1\n }\n\n yt <- crossprod(U,yv)\n Xt <- crossprod(U,X[vrows,,drop=FALSE])\n iXX <- solve(crossprod(Xt,Xt))\n beta <- iXX%*%crossprod(Xt,yt)\n if ( !ponly ) {\n vgs[i,j] <- REMLE$vg\n ves[i,j] <- REMLE$ve\n REMLs[i,j] <- REMLE$REML\n }\n stats[i,j] <- beta[q1]/sqrt(iXX[q1,q1]*REMLE$vg)\n }\n else {\n if ( is.null(Z) ) {\n vtids <- vrows & vids\n eig.L0 <- emma.eigen.L.wo.Z(K[vtids,vtids,drop=FALSE])\n yv <- ys[j,vtids]\n nr <- sum(vtids)\n REMLE <- emma.REMLE(yv,X[vtids,,drop=FALSE],K[vtids,vtids,drop=FALSE],NULL,ngrids,llim,ulim,esp)\n U <- eig.L0$vectors * matrix(sqrt(1/(eig.L0$values+REMLE$delta)),nr,nr,byrow=TRUE)\n Xt <- crossprod(U,X[vtids,,drop=FALSE])\n dfs[i,j] <- nr-q1\n }\n else {\n vtids <- as.logical(colSums(Z[vrows,,drop=FALSE])) & vids\n vtrows <- vrows & as.logical(rowSums(Z[,vids,drop=FALSE]))\n eig.L0 <- emma.eigen.L.w.Z(Z[vtrows,vtids,drop=FALSE],K[vtids,vtids,drop=FALSE])\n yv <- ys[j,vtrows]\n nr <- sum(vtrows)\n REMLE <- emma.REMLE(yv,X[vtrows,,drop=FALSE],K[vtids,vtids,drop=FALSE],Z[vtrows,vtids,drop=FALSE],ngrids,llim,ulim,esp)\n U <- eig.L0$vectors * matrix(c(sqrt(1/(eig.L0$values+REMLE$delta)),rep(sqrt(1/REMLE$delta),nr-sum(vtids))),nr,nr,byrow=TRUE)\n Xt <- crossprod(U,X[vtrows,,drop=FALSE])\n dfs[i,j] <- nr-q1\n }\n yt <- crossprod(U,yv)\n iXX <- solve(crossprod(Xt,Xt))\n beta <- iXX%*%crossprod(Xt,yt)\n if ( !ponly ) {\n vgs[i,j] <- REMLE$vg\n ves[i,j] <- REMLE$ve\n REMLs[i,j] <- REMLE$REML\n }\n stats[i,j] <- beta[q1]/sqrt(iXX[q1,q1]*REMLE$vg)\n \n }\n }\n ps[i,] <- 2*pt(abs(stats[i,]),dfs[i,],lower.tail=FALSE) \n }\n } \n }\n if ( ponly ) {\n return (ps)\n }\n else {\n return (list(ps=ps,REMLs=REMLs,stats=stats,dfs=dfs,vgs=vgs,ves=ves))\n } \n}\n\nemma.REML.t <- function(ys, xs, K, Z=NULL, X0 = NULL, ngrids=100, llim=-10, ulim=10, esp=1e-10, ponly = FALSE) {\n if ( is.null(dim(ys)) || ncol(ys) == 1 ) {\n ys <- matrix(ys,1,length(ys))\n }\n if ( is.null(dim(xs)) || ncol(xs) == 1 ) {\n xs <- matrix(xs,1,length(xs))\n }\n if ( is.null(X0) ) {\n X0 <- matrix(1,ncol(ys),1)\n }\n \n g <- nrow(ys)\n n <- ncol(ys)\n m <- nrow(xs)\n t <- ncol(xs)\n q0 <- ncol(X0)\n q1 <- q0 + 1\n \n stopifnot(nrow(K) == t)\n stopifnot(ncol(K) == t)\n stopifnot(nrow(X0) == n)\n\n if ( !ponly ) {\n REMLs <- matrix(nrow=m,ncol=g)\n vgs <- matrix(nrow=m,ncol=g)\n ves <- matrix(nrow=m,ncol=g)\n }\n dfs <- matrix(nrow=m,ncol=g)\n stats <- matrix(nrow=m,ncol=g)\n ps <- matrix(nrow=m,ncol=g)\n\n if ( sum(is.na(ys)) == 0 ) {\n eig.L <- emma.eigen.L(Z,K)\n\n x.prev <- vector(length=0)\n\n for(i in 1:m) {\n vids <- !is.na(xs[i,])\n nv <- sum(vids)\n xv <- xs[i,vids]\n\n if ( ( mean(xv) <= 0 ) || ( mean(xv) >= 1 ) ) {\n if ( !ponly ) {\n vgs[i,] <- rep(NA,g)\n ves[i,] <- rep(NA,g)\n dfs[i,] <- rep(NA,g)\n REMLs[i,] <- rep(NA,g)\n stats[i,] <- rep(NA,g)\n }\n ps[i,] = rep(1,g)\n \n }\n else if ( identical(x.prev, xv) ) {\n if ( !ponly ) {\n vgs[i,] <- vgs[i-1,]\n ves[i,] <- ves[i-1,]\n dfs[i,] <- dfs[i-1,]\n REMLs[i,] <- REMLs[i-1,]\n stats[i,] <- stats[i-1,]\n }\n ps[i,] <- ps[i-1,]\n }\n else {\n if ( is.null(Z) ) {\n X <- cbind(X0[vids,,drop=FALSE],xs[i,vids])\n eig.R1 = emma.eigen.R.wo.Z(K[vids,vids],X)\n }\n else {\n vrows <- as.logical(rowSums(Z[,vids])) \n X <- cbind(X0[vrows,,drop=FALSE],Z[vrows,vids,drop=FALSE]%*%t(xs[i,vids,drop=FALSE]))\n eig.R1 = emma.eigen.R.w.Z(Z[vrows,vids],K[vids,vids],X)\n }\n \n for(j in 1:g) {\n if ( nv == t ) {\n REMLE <- emma.REMLE(ys[j,],X,K,Z,ngrids,llim,ulim,esp,eig.R1)\n if ( is.null(Z) ) {\n U <- eig.L$vectors * matrix(sqrt(1/(eig.L$values+REMLE$delta)),t,t,byrow=TRUE)\n dfs[i,j] <- nv - q1\n }\n else {\n U <- eig.L$vectors * matrix(c(sqrt(1/(eig.L$values+REMLE$delta)),rep(sqrt(1/REMLE$delta),n-t)),n,n,byrow=TRUE)\n dfs[i,j] <- n - q1\n }\n yt <- crossprod(U,ys[j,])\n Xt <- crossprod(U,X)\n iXX <- solve(crossprod(Xt,Xt))\n beta <- iXX%*%crossprod(Xt,yt)\n \n if ( !ponly ) {\n vgs[i,j] <- REMLE$vg\n ves[i,j] <- REMLE$ve\n REMLs[i,j] <- REMLE$REML\n }\n stats[i,j] <- beta[q1]/sqrt(iXX[q1,q1]*REMLE$vg)\n }\n else {\n if ( is.null(Z) ) {\n eig.L0 <- emma.eigen.L.wo.Z(K[vids,vids])\n nr <- sum(vids)\n yv <- ys[j,vids]\n REMLE <- emma.REMLE(yv,X,K[vids,vids,drop=FALSE],NULL,ngrids,llim,ulim,esp,eig.R1)\n U <- eig.L0$vectors * matrix(sqrt(1/(eig.L0$values+REMLE$delta)),nr,nr,byrow=TRUE)\n dfs[i,j] <- nr - q1\n }\n else {\n eig.L0 <- emma.eigen.L.w.Z(Z[vrows,vids,drop=FALSE],K[vids,vids]) \n yv <- ys[j,vrows]\n nr <- sum(vrows)\n tv <- sum(vids)\n REMLE <- emma.REMLE(yv,X,K[vids,vids,drop=FALSE],Z[vrows,vids,drop=FALSE],ngrids,llim,ulim,esp,eig.R1)\n U <- eig.L0$vectors * matrix(c(sqrt(1/(eig.L0$values+REMLE$delta)),rep(sqrt(1/REMLE$delta),nr-tv)),nr,nr,byrow=TRUE)\n dfs[i,j] <- nr - q1\n }\n yt <- crossprod(U,yv)\n Xt <- crossprod(U,X)\n iXX <- solve(crossprod(Xt,Xt))\n beta <- iXX%*%crossprod(Xt,yt)\n if (!ponly) {\n vgs[i,j] <- REMLE$vg\n ves[i,j] <- REMLE$ve\n REMLs[i,j] <- REMLE$REML\n }\n stats[i,j] <- beta[q1]/sqrt(iXX[q1,q1]*REMLE$vg)\n }\n }\n ps[i,] <- 2*pt(abs(stats[i,]),dfs[i,],lower.tail=FALSE)\n }\n }\n }\n else {\n eig.L <- emma.eigen.L(Z,K)\n eig.R0 <- emma.eigen.R(Z,K,X0)\n \n x.prev <- vector(length=0)\n \n for(i in 1:m) {\n vids <- !is.na(xs[i,])\n nv <- sum(vids)\n xv <- xs[i,vids]\n\n if ( ( mean(xv) <= 0 ) || ( mean(xv) >= 1 ) ) {\n if (!ponly) {\n vgs[i,] <- rep(NA,g)\n ves[i,] <- rep(NA,g)\n REMLs[i,] <- rep(NA,g)\n dfs[i,] <- rep(NA,g)\n }\n ps[i,] = rep(1,g)\n } \n else if ( identical(x.prev, xv) ) {\n if ( !ponly ) {\n stats[i,] <- stats[i-1,]\n vgs[i,] <- vgs[i-1,]\n ves[i,] <- ves[i-1,]\n REMLs[i,] <- REMLs[i-1,]\n dfs[i,] <- dfs[i-1,]\n }\n ps[i,] = ps[i-1,]\n }\n else {\n if ( is.null(Z) ) {\n X <- cbind(X0,xs[i,])\n if ( nv == t ) {\n eig.R1 = emma.eigen.R.wo.Z(K,X)\n }\n }\n else {\n vrows <- as.logical(rowSums(Z[,vids,drop=FALSE]))\n X <- cbind(X0,Z[,vids,drop=FALSE]%*%t(xs[i,vids,drop=FALSE]))\n if ( nv == t ) {\n eig.R1 = emma.eigen.R.w.Z(Z,K,X)\n } \n }\n\n for(j in 1:g) {\n vrows <- !is.na(ys[j,])\n if ( nv == t ) {\n yv <- ys[j,vrows]\n nr <- sum(vrows)\n if ( is.null(Z) ) {\n if ( nr == n ) {\n REMLE <- emma.REMLE(yv,X,K,NULL,ngrids,llim,ulim,esp,eig.R1)\n U <- eig.L$vectors * matrix(sqrt(1/(eig.L$values+REMLE$delta)),n,n,byrow=TRUE) \n }\n else {\n eig.L0 <- emma.eigen.L.wo.Z(K[vrows,vrows,drop=FALSE])\n REMLE <- emma.REMLE(yv,X[vrows,,drop=FALSE],K[vrows,vrows,drop=FALSE],NULL,ngrids,llim,ulim,esp)\n U <- eig.L0$vectors * matrix(sqrt(1/(eig.L0$values+REMLE$delta)),nr,nr,byrow=TRUE)\n }\n dfs[i,j] <- nr-q1\n }\n else {\n if ( nr == n ) {\n REMLE <- emma.REMLE(yv,X,K,Z,ngrids,llim,ulim,esp,eig.R1)\n U <- eig.L$vectors * matrix(c(sqrt(1/(eig.L$values+REMLE$delta)),rep(sqrt(1/REMLE$delta),n-t)),n,n,byrow=TRUE) \n }\n else {\n vtids <- as.logical(colSums(Z[vrows,,drop=FALSE]))\n eig.L0 <- emma.eigen.L.w.Z(Z[vrows,vtids,drop=FALSE],K[vtids,vtids,drop=FALSE])\n REMLE <- emma.REMLE(yv,X[vrows,,drop=FALSE],K[vtids,vtids,drop=FALSE],Z[vrows,vtids,drop=FALSE],ngrids,llim,ulim,esp)\n U <- eig.L0$vectors * matrix(c(sqrt(1/(eig.L0$values+REMLE$delta)),rep(sqrt(1/REMLE$delta),nr-sum(vtids))),nr,nr,byrow=TRUE)\n }\n dfs[i,j] <- nr-q1\n }\n\n yt <- crossprod(U,yv)\n Xt <- crossprod(U,X[vrows,,drop=FALSE])\n iXX <- solve(crossprod(Xt,Xt))\n beta <- iXX%*%crossprod(Xt,yt)\n if ( !ponly ) {\n vgs[i,j] <- REMLE$vg\n ves[i,j] <- REMLE$ve\n REMLs[i,j] <- REMLE$REML\n }\n stats[i,j] <- beta[q1]/sqrt(iXX[q1,q1]*REMLE$vg)\n }\n else {\n if ( is.null(Z) ) {\n vtids <- vrows & vids\n eig.L0 <- emma.eigen.L.wo.Z(K[vtids,vtids,drop=FALSE])\n yv <- ys[j,vtids]\n nr <- sum(vtids)\n REMLE <- emma.REMLE(yv,X[vtids,,drop=FALSE],K[vtids,vtids,drop=FALSE],NULL,ngrids,llim,ulim,esp)\n U <- eig.L0$vectors * matrix(sqrt(1/(eig.L0$values+REMLE$delta)),nr,nr,byrow=TRUE)\n Xt <- crossprod(U,X[vtids,,drop=FALSE])\n dfs[i,j] <- nr-q1\n }\n else {\n vtids <- as.logical(colSums(Z[vrows,,drop=FALSE])) & vids\n vtrows <- vrows & as.logical(rowSums(Z[,vids,drop=FALSE]))\n eig.L0 <- emma.eigen.L.w.Z(Z[vtrows,vtids,drop=FALSE],K[vtids,vtids,drop=FALSE])\n yv <- ys[j,vtrows]\n nr <- sum(vtrows)\n REMLE <- emma.REMLE(yv,X[vtrows,,drop=FALSE],K[vtids,vtids,drop=FALSE],Z[vtrows,vtids,drop=FALSE],ngrids,llim,ulim,esp)\n U <- eig.L0$vectors * matrix(c(sqrt(1/(eig.L0$values+REMLE$delta)),rep(sqrt(1/REMLE$delta),nr-sum(vtids))),nr,nr,byrow=TRUE)\n Xt <- crossprod(U,X[vtrows,,drop=FALSE])\n dfs[i,j] <- nr-q1\n }\n yt <- crossprod(U,yv)\n iXX <- solve(crossprod(Xt,Xt))\n beta <- iXX%*%crossprod(Xt,yt)\n if ( !ponly ) {\n vgs[i,j] <- REMLE$vg\n ves[i,j] <- REMLE$ve\n REMLs[i,j] <- REMLE$REML\n }\n stats[i,j] <- beta[q1]/sqrt(iXX[q1,q1]*REMLE$vg)\n \n }\n }\n ps[i,] <- 2*pt(abs(stats[i,]),dfs[i,],lower.tail=FALSE) \n }\n } \n }\n if ( ponly ) {\n return (ps)\n }\n else {\n return (list(ps=ps,REMLs=REMLs,stats=stats,dfs=dfs,vgs=vgs,ves=ves))\n }\n}\n\n", "meta": {"hexsha": "cf42a4965ac818711798427ac75f521ea0e0facf", "size": 42607, "ext": "r", "lang": "R", "max_stars_repo_path": "emma.r", "max_stars_repo_name": "kevinfrsartori/GWAS", "max_stars_repo_head_hexsha": "9a7bdaf9099873524e20905425291c6ddd210f51", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 9, "max_stars_repo_stars_event_min_datetime": "2017-07-23T02:06:00.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-15T14:15:26.000Z", "max_issues_repo_path": "emma.r", "max_issues_repo_name": "kevinfrsartori/GWAS", "max_issues_repo_head_hexsha": "9a7bdaf9099873524e20905425291c6ddd210f51", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "emma.r", "max_forks_repo_name": "kevinfrsartori/GWAS", "max_forks_repo_head_hexsha": "9a7bdaf9099873524e20905425291c6ddd210f51", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 12, "max_forks_repo_forks_event_min_datetime": "2016-08-09T16:59:12.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-24T21:04:13.000Z", "avg_line_length": 33.3388106416, "max_line_length": 181, "alphanum_fraction": 0.4865632408, "num_tokens": 15358, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.3913626123668349}} {"text": "#######################################################################################################\n# Kalman filter and smoother function based on Koopman and Durbin's KFAS package\n# y_t = Z_t * alpha_t + eps_t (observation equation)\n# alpha_t+1 = T_t * alpha_t + R_t * eta_t(transition equation)\n# Note the different time indexing for transition equation\n# The y_t,y_{t-1} stacked vector with parameters vectors reconfigured to output the\n# smoothed lag-1 covariances needed by the EM algorithm\n#######################################################################################################\nMARSSkfas <- function(MLEobj, only.logLik = FALSE, return.lag.one = TRUE, return.kfas.model = FALSE) {\n MODELobj <- MLEobj[[\"marss\"]]\n control <- MLEobj[[\"control\"]]\n diffuse <- MODELobj[[\"diffuse\"]]\n model.dims <- attr(MODELobj, \"model.dims\")\n\n n <- model.dims$data[1]\n TT <- model.dims$data[2]\n m <- model.dims$x[1]\n g1 <- model.dims$Q[1]\n h1 <- model.dims$R[1]\n l1 <- model.dims$L[1]\n par.1 <- parmat(MLEobj, t = 1)\n t.B <- matrix(par.1$B, m, m, byrow = TRUE)\n # create the YM matrix\n YM <- matrix(as.numeric(!is.na(MODELobj$data)), n, TT)\n\n # Make sure the missing vals in yt are NAs if there are any\n yt <- MODELobj$data\n yt[!YM] <- as.numeric(NA)\n\n # Stack the y so that we can get the lag-1 covariance smoother from the Kalman filter output\n # stack.yt=rbind(yt[,1:TT,drop=FALSE],cbind(NA,yt[,1:(TT-1),drop=FALSE]))\n # stack.yt=t(stack.yt)\n\n # KFS needs time going down rows so yt can be properly converted to ts object\n yt <- t(yt)\n\n # Build the Zt matrix which is n x (m+1) or n x (m+1) x T; (m+1) because A is in Z\n if (model.dims$Z[3] == 1 & model.dims$A[3] == 1) {\n # not time-varying\n Zt <- cbind(par.1$Z, par.1$A)\n stack.Zt <- matrix(0, n, 2 * (m + 1))\n stack.Zt[1:n, 1:(m + 1)] <- Zt\n } else {\n Zt <- array(0, dim = c(n, m + 1, TT))\n stack.Zt <- array(0, dim = c(n, 2 * (m + 1), TT))\n pars <- parmat(MLEobj, c(\"Z\", \"A\"), t = 1:TT)\n Zt[1:n, 1:m, ] <- pars$Z\n Zt[1:n, m + 1, ] <- pars$A\n stack.Zt[1:n, 1:(m + 1), ] <- Zt\n }\n\n # Build the Tt matrix which is (m+1) x (m+1) or (m+1) x (m+1) x T; (m+1) because x has extra row of 1s (for the A)\n # Tt=cbind(rbind(parList$B,matrix(0,1,m)),matrix(c(parList$U,1),m+1,1))\n if (model.dims$B[3] == 1 & model.dims$U[3] == 1) {\n # not time-varying\n Tt <- cbind(rbind(par.1$B, matrix(0, 1, m)), matrix(c(par.1$U, 1), m + 1, 1))\n stack.Tt <- matrix(0, 2 * (m + 1), 2 * (m + 1))\n stack.Tt[1:(m + 1), 1:(m + 1)] <- Tt\n stack.Tt[(m + 2):(2 * m + 2), 1:(m + 1)] <- diag(1, m + 1)\n } else {\n Tt <- array(0, dim = c(m + 1, m + 1, TT))\n stack.Tt <- array(0, dim = c(2 * (m + 1), 2 * (m + 1), TT))\n pars <- parmat(MLEobj, c(\"B\", \"U\"), t = 1:TT)\n # pars uses i+1 because in KFAS x(t)=B(t-1)x(t-1) versus MARSS where x(t)=B(t)x(t-1)\n # KFAS sets prior on x(1) so recursions start at x(2); thus B(0) never appears in the KFAS recursions\n Tt[1:m, 1:m, 1:(TT - 1)] <- pars$B[, , 2:TT]\n Tt[1:m, m + 1, 1:(TT - 1)] <- pars$U[, , 2:TT]\n Tt[m + 1, m + 1, ] <- 1\n # in KFAS T[,,TT] is not used since x(T)=B(t-1)x(t-1) is the last computation\n # Set to 0 since is.SSModel does like NA in any parameters\n Tt[, , TT] <- 0\n stack.Tt[(m + 2):(2 * m + 2), 1:(m + 1), ] <- diag(1, m + 1)\n stack.Tt[1:(m + 1), 1:(m + 1), ] <- Tt\n stack.Tt[, , TT] <- 0 # see comment above re setting TT value\n }\n\n # Build the Ht (R) matrix which is n x n or n x n x T\n if (model.dims$R[3] == 1) {\n # not time-varying\n Ht <- tcrossprod(par.1$H %*% par.1$R, par.1$H)\n } else {\n Ht <- array(0, dim = c(n, n, TT))\n for (i in 1:TT) {\n Ht[, , i] <- tcrossprod(parmat(MLEobj, \"H\", t = i)$H %*% parmat(MLEobj, \"R\", t = i)$R, parmat(MLEobj, \"H\", t = i)$H)\n }\n }\n\n # Build the Qt matrix which is g1 x g1 or g1 x g1 x T;\n if (model.dims$Q[3] == 1) {\n # not time-varying\n Qt <- par.1$Q\n stack.Qt <- matrix(0, 2 * g1, 2 * g1)\n stack.Qt[1:g1, 1:g1] <- Qt\n } else {\n # See notes for Tt re differences in parameter indexing for the process equation\n Qt <- array(0, dim = c(g1, g1, TT))\n stack.Qt <- array(0, dim = c(2 * g1, 2 * g1, TT))\n for (i in 1:(TT - 1)) {\n # i+1 since in KFAS my B(t) equals B(t-1)\n Qt[, , i] <- parmat(MLEobj, \"Q\", t = i + 1)$Q\n stack.Qt[1:g1, 1:g1, i] <- Qt[, , i]\n }\n # see comments on setting of T re TT value; TT value never appears in the KFAS recursions\n # but is.SSModel check does not like any NAs in the parameters\n Qt[, , TT] <- 0\n stack.Qt[, , TT] <- 0\n }\n\n # build the Rt (G) matrix; process error is G(t)%*%w(t); extra row at bottom for for U (1s row in x)\n if (model.dims$G[3] == 1) {\n # not time-varying\n Rt <- matrix(0, m + 1, g1)\n Rt[1:m, 1:g1] <- par.1$G\n stack.Rt <- matrix(0, 2 * (m + 1), 2 * g1)\n stack.Rt[1:(m + 1), 1:g1] <- Rt\n } else {\n # See notes for Tt re differences in parameter indexing for the process equation\n Rt <- array(0, dim = c(m + 1, g1, TT))\n stack.Rt <- array(0, dim = c(2 * (m + 1), 2 * g1, TT))\n for (i in 1:(TT - 1)) {\n # i+1 since in KFAS my B(t) equals B(t-1)\n Rt[, , i] <- matrix(0, m + 1, g1)\n Rt[1:m, 1:g1, i] <- parmat(MLEobj, \"G\", t = i + 1)$G\n stack.Rt[1:(m + 1), 1:g1, i] <- Rt[, , i]\n }\n # see comments on setting of T re TT value; TT value never appears in the KFAS recursions\n # but is.SSModel check does not like any NAs in the parameters\n Rt[, , TT] <- 0\n stack.Rt[, , TT] <- 0\n }\n\n # Build the a1 and P1 matrices\n # First compute x10 and V10 if tinitx=0\n if (MODELobj$tinitx == 0) { # Compute needed x_1 | x_0\n # B(1),U(1), and Q(1) correct here since equivalent to B(0), etc in KFAS terminology\n x00 <- par.1$x0\n V00 <- tcrossprod(par.1$L %*% par.1$V0, par.1$L)\n x10 <- par.1$B %*% x00 + par.1$U # Shumway and Stoffer treatment of initial states\n V10 <- par.1$B %*% V00 %*% t.B + par.1$Q # eqn 6.20\n } else {\n x10 <- par.1$x0\n x00 <- matrix(10, m, 1) # dummy; not defined\n V10 <- par.1$V0\n V00 <- diag(0, m) # dummy; not defined\n }\n a1 <- rbind(x10, 1)\n stack.a1 <- rbind(x10, 1, x00, 1)\n if (diffuse) {\n P1inf <- matrix(0, m + 1, m + 1)\n P1inf[1:m, 1:m] <- V10\n stack.P1inf <- matrix(0, 2 * (m + 1), 2 * (m + 1))\n stack.P1inf[1:m, 1:m] <- V10\n stack.P1inf[(m + 2):(2 * m + 1), (m + 2):(2 * m + 1)] <- V00\n P1 <- matrix(0, m + 1, m + 1)\n stack.P1 <- matrix(0, 2 * (m + 1), 2 * (m + 1))\n } else {\n P1inf <- matrix(0, m + 1, m + 1)\n stack.P1inf <- matrix(0, 2 * (m + 1), 2 * (m + 1))\n P1 <- matrix(0, m + 1, m + 1)\n P1[1:m, 1:m] <- V10\n # P1 is the var-cov matrix for the stacked x1,x0\n # it is matrix(c(V10,B*V00,V00*t(B),V00),2,2)\n # x1=B*x0+U+w; in the var-cov mat looks like\n # E[x1*t(x1)] E[(Bx0+U+w1)*t(x0)] - E[x1]*E[x1] E[(Bx0+U+w1)]E[t(x0)]\n # E[x0*t(Bx0+U+w1)] E[x0*t(x0)] E[(Bx0+U+w1)]E[t(x0)] - E[x0]E[t(x0)]\n stack.P1 <- matrix(0, 2 * (m + 1), 2 * (m + 1))\n stack.P1[1:m, 1:m] <- V10\n stack.P1[(m + 2):(2 * m + 1), (m + 2):(2 * m + 1)] <- V00\n stack.P1[1:m, (m + 2):(2 * m + 1)] <- par.1$B %*% V00\n stack.P1[(m + 2):(2 * m + 1), 1:m] <- V00 %*% t(par.1$B)\n }\n\n if (!return.lag.one) {\n kfas.model <- SSModel(yt ~ -1 + SSMcustom(Z = Zt, T = Tt, R = Rt, Q = Qt, a1 = a1, P1 = P1, P1inf = P1inf), H = Ht)\n } else {\n kfas.model <- SSModel(yt ~ -1 + SSMcustom(Z = stack.Zt, T = stack.Tt, R = stack.Rt, Q = stack.Qt, a1 = stack.a1, P1 = stack.P1, P1inf = stack.P1inf), H = Ht)\n }\n\n if (only.logLik) {\n return(list(logLik = logLik(kfas.model)))\n }\n # This works because I do not allow the location of 0s on the diagonal of R or Q to be time-varying\n if (n == 1) {\n diag.R <- unname(par.1$R)\n } else {\n diag.R <- unname(par.1$R)[1 + 0:(n - 1) * (n + 1)]\n }\n\n if (any(diag.R == 0)) { # because KFAS 1.0.4 added a warning message\n ks.out <- suppressWarnings(KFS(kfas.model, simplify = FALSE))\n } else {\n ks.out <- KFS(kfas.model, simplify = FALSE)\n } # simplify=FALSE so 1.0.0 returns LL\n # because 1.0.0 has time down columns instead of across rows\n if (packageVersion(\"KFAS\") != \"0.9.11\") {\n ks.out$a <- t(ks.out$a)\n ks.out$alphahat <- t(ks.out$alphahat)\n }\n\n VtT <- ks.out$V[1:m, 1:m, , drop = FALSE]\n Vtt1 <- ks.out$P[1:m, 1:m, 1:TT, drop = FALSE]\n if (!return.lag.one) {\n Vtt1T <- NULL\n } else {\n Vtt1T <- ks.out$V[1:m, (m + 2):(2 * m + 1), , drop = FALSE]\n }\n # zero out rows cols as needed when R diag = 0\n # Check that if any R are 0 then model is solveable\n if (any(diag.R == 0)) {\n VtT[abs(VtT) < .Machine$double.eps] <- 0\n Vtt1[abs(Vtt1) < .Machine$double.eps] <- 0\n if (return.lag.one) Vtt1T[abs(Vtt1T) < .Machine$double.eps] <- 0\n }\n\n x10T <- ks.out$alphahat[1:m, 1, drop = FALSE]\n V10T <- matrix(VtT[, , 1], m, m)\n if (MODELobj$tinitx == 1) {\n x00 <- matrix(NA, m, 1)\n V00 <- matrix(NA, m, m)\n x0T <- x10T\n V0T <- V10T\n } else { # MODELobj$tinitx==0\n Vtt1.1 <- sub3D(Vtt1, t = 1)\n Vinv <- pcholinv(Vtt1.1)\n if (m != 1) Vinv <- symm(Vinv) # to enforce symmetry after chol2inv call\n J0 <- V00 %*% t.B %*% Vinv # eqn 6.49 and 1s on diag when Q=0; Here it is t.B[1]\n xtT.1 <- ks.out$alphahat[1:m, 1, drop = FALSE]\n x0T <- x00 + J0 %*% (ks.out$alphahat[1:m, 1, drop = FALSE] - ks.out$a[1:m, 1, drop = FALSE]) # eqn 6.47\n V0T <- V00 + J0 %*% (VtT[, , 1] - Vtt1[, , 1]) * t(J0) # eqn 6.48\n }\n\n if (!return.kfas.model) kfas.model <- NULL\n\n # not using ks.out$v (Innov) and ks.out$F (Sigma) since I think there might be a bug (I misunderstand KFAS) when R is not diagonal.\n rtn.list <- list(\n xtT = ks.out$alphahat[1:m, , drop = FALSE],\n VtT = VtT,\n Vtt1T = Vtt1T,\n x0T = x0T,\n V0T = V0T,\n x10T = ks.out$alphahat[1:m, 1, drop = FALSE],\n V10T = V10T,\n x00T = x00,\n V00T = V00,\n Vtt = \"Use MARSSkfss to get Vtt\",\n Vtt1 = Vtt1,\n J = \"Use MARSSkfss to get J\",\n J0 = \"Use MARSSkfss to get J0\",\n Kt = \"Use MARSSkfss to get Kt\",\n xtt1 = ks.out$a[1:m, 1:TT, drop = FALSE],\n xtt = \"Use MARSSkfss to get xtt\",\n Innov = \"Use MARSSkfss to get Innov\",\n Sigma = \"Use MARSSkfss to get Sigma\",\n kfas.model = kfas.model,\n logLik = ks.out$logLik,\n ok = TRUE,\n errors = NULL\n )\n # apply names\n X.names <- attr(MODELobj, \"X.names\")\n for(el in c(\"xtT\", \"xtt1\", \"x0T\", \"x00T\", \"x10T\")) rownames(rtn.list[[el]]) <- X.names\n return(rtn.list)\n}\n", "meta": {"hexsha": "e6761d46139810a7b3ffd7e607aa0dd35d93f9f5", "size": 10476, "ext": "r", "lang": "R", "max_stars_repo_path": "R/MARSSkfas.r", "max_stars_repo_name": "clward/MARSS", "max_stars_repo_head_hexsha": "15107975132196b08bd9322e306c2f41d93931f9", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2020-05-01T00:14:40.000Z", "max_stars_repo_stars_event_max_datetime": "2020-05-01T00:14:40.000Z", "max_issues_repo_path": "R/MARSSkfas.r", "max_issues_repo_name": "clward/MARSS", "max_issues_repo_head_hexsha": "15107975132196b08bd9322e306c2f41d93931f9", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/MARSSkfas.r", "max_forks_repo_name": "clward/MARSS", "max_forks_repo_head_hexsha": "15107975132196b08bd9322e306c2f41d93931f9", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.6818181818, "max_line_length": 161, "alphanum_fraction": 0.5349369989, "num_tokens": 4370, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.39114959334010435}} {"text": "# update:2022.01.15\r\nlibrary(shiny)\r\nlibrary(shinydashboard)\r\nlibrary(plotly)\r\n\r\n\r\nsidebarPanel2 <- function (..., out = NULL, width = 4) \r\n{\r\n div(class = paste0(\"col-sm-\", width), \r\n tags$form(class = \"well\", ...),\r\n out\r\n )\r\n}\r\n\r\ntheme_basic <- function() {\r\n fill.colour <- \"white\"\r\n theme_classic() +\r\n theme(plot.background = element_rect(fill = fill.colour)) +\r\n theme(panel.background = element_rect(fill = fill.colour)) +\r\n theme(panel.grid.major = element_line(colour = \"grey95\")) +\r\n theme(panel.grid.major.x = element_blank()) +\r\n theme(axis.line = element_blank()) +\r\n theme(axis.ticks.x = element_blank()) +\r\n theme(axis.ticks.y = element_line(colour = \"grey95\")) +\r\n theme(text = element_text(colour = \"grey20\"))\r\n}\r\n#------------ ui-app.R ------------ ---\r\n#------------ ui-header & sidebar -----\r\nheader <- dashboardHeader(title = \"Probability\")\r\nsidebar <- dashboardSidebar(width = NULL,disable = FALSE,## 可以把邊邊關起來 \r\n sidebarMenu(\r\n menuItem(\"Summary\", tabName = \"Page0\", icon = icon(\"list\")),\r\n menuItem(\"Basic Probability\", tabName = \"Page1\", icon = icon(\"list\")),\r\n menuItem(\"Discrate\", tabName = \"Page2\", icon = icon(\"chart-bar\")),\r\n menuItem(\"Continuous\", tabName = \"Page3\", icon = icon(\"chart-area\"))\r\n # menuItem(\"About\",tabName = \"final\", icon = icon(\"address-card\"))\r\n # ref of icon : https://fontawesome.com/v5.15/icons \r\n ))\r\n#------------ ui-Body content -----\r\nbody <- dashboardBody(\r\n tags$head(tags$style(HTML('\r\n /* logo */\r\n .skin-blue .main-header .logo {\r\n background-color: #204969;\r\n font-family: \"monospace\", Times, \"Times New Roman\", serif;\r\n font-weight: bold;\r\n font-size: 24px;\r\n }\r\n /* logo when hovered */\r\n .skin-blue .main-header .logo:hover {\r\n background-color: #FFB6C1;\r\n }\r\n /* navbar (rest of the header) */\r\n .skin-blue .main-header .navbar {\r\n background-color: #f4b943;\r\n }\r\n /* main sidebar */\r\n .skin-blue .main-sidebar {\r\n background-color: #204969;\r\n font-size: 16px; \r\n }\r\n /* body */\r\n .content-wrapper, .right-side {\r\n background-color: #fff7f7;\r\n }\r\n /* boxboxbox */\r\n ') #HTML\r\n ) # tags$style\r\n ), #tags$head\r\n tabItems(\r\n #-------------- Page0 ------------- \r\n tabItem(tabName = \"Page0\",\r\n # Boxes need to be put in a row (or column)\r\n fluidRow(\r\n box(title = \"Definitions\",width = 12,\r\n solidHeader = FALSE, \r\n collapsible = FALSE,\r\n uiOutput(\"summary\")\r\n ) # box\r\n ) # fluidRow\r\n ), # tabItem\r\n #-------------- Page1 ------------- \r\n tabItem(tabName = \"Page1\",\r\n fluidRow(\r\n box(title = \"Flipping a coin\", width = 6,\r\n collapsible = FALSE,\r\n sidebarPanel2(\r\n out = h6(\"A classic example of a probabilistic experiment is a fair coin toss, \r\n in which the two possible outcomes are heads or tails. In this case,\r\n The probability of flipping a head or a tail is 1/2.\"),\r\n \"Flip the coin:\",\r\n # sliderInput(\"n_coin\",\"number\",\r\n # value = 1,\r\n # min = 1,\r\n # max = 1000),\r\n hr(),\r\n actionButton(\"action1\", \"Flip the coin\"),\r\n hr(),\r\n actionButton(\"action2\", \"Flip 100 times\")\r\n ), # sidebarPanel2\r\n mainPanel(plotOutput(\"plot_coin\"))\r\n ),\r\n box(title = \"Rolling a dice\", width = 6,\r\n collapsible = FALSE,\r\n sidebarPanel(width = 4,\r\n \"Roll the dice:\",\r\n sliderInput(\"n_dice\",\"number\",\r\n value = 1,\r\n min = 1,\r\n max = 1000)\r\n ),\r\n mainPanel(plotOutput(\"plot_dice\"))\r\n )\r\n )\r\n # ,\r\n # fluidRow(\r\n # box(title = \"coin\", width = 6,\r\n # collapsible = FALSE,\r\n # tableOutput(\"data_coin\")\r\n # )\r\n # )\r\n \r\n ),\r\n #-------------- Page2 ------------- \r\n tabItem(tabName = \"Page2\",\r\n # #----------- radioButtons ----------------------\r\n # fluidRow(\r\n # box(title = \"Discrate\",width = 4,\r\n # status = \"warning\",\r\n # solidHeader = FALSE, \r\n # collapsible = FALSE,\r\n # \"Choose one of the following major discrete distributions.\",\r\n # br(),\r\n # radioButtons(\"dist1\", \"Distribution type:\",\r\n # c(\"Binomial\",\"Negative Binomial\",\r\n # \"Geometric\",\"Poisson\"))\r\n # ),\r\n # box(title = \"Definitions\",width = 8,\r\n # status = \"warning\",\r\n # solidHeader = FALSE, \r\n # collapsible = FALSE,\r\n # uiOutput(\"txt1\")\r\n # # htmlOutput(\"txt1\")\r\n # # verbatimTextOutput(\"txt1\")\r\n # )\r\n # ),\r\n #----------- bin ------------------------------------\r\n fluidRow(\r\n box(title = \"Binomial\", width = 6,\r\n status = \"warning\",\r\n collapsible = TRUE,\r\n sidebarPanel(width = 4,\r\n sliderInput(\"n\",\"number\",\r\n value = 10,\r\n min = 10,\r\n max = 100),\r\n sliderInput(\"p\",\r\n \"Probability\",\r\n value = 0.6,\r\n min = 0,\r\n max = 1)\r\n ),\r\n mainPanel(plotOutput(\"plot_bin1\"))\r\n ),\r\n #----------- nb ------------------------------------\r\n box(title = \"Negative Binomial\",width = 6,\r\n status = \"warning\",\r\n solidHeader = FALSE, \r\n collapsible = TRUE,\r\n sidebarPanel(width = 4,\r\n sliderInput(\"r\",\"number\",\r\n value = 10,\r\n min = 1,\r\n max = 100),\r\n sliderInput(\"p_nb\",\"Probability\",\r\n value = 0.6,\r\n min = 0,\r\n max = 1)),\r\n mainPanel(plotOutput(\"plot_nb1\")))\r\n ),\r\n #----------- geo ------------------------------------\r\n fluidRow(\r\n box(title = \"Geometric\",width = 6,\r\n status = \"warning\", solidHeader = FALSE, \r\n collapsible = TRUE,\r\n sidebarPanel(width = 4, \r\n sliderInput(\"p_geo\",\"Probability\",\r\n value = 0.6,\r\n min = 0.1,\r\n max = 1)\r\n ),\r\n mainPanel(plotOutput(\"plot_geo1\"))\r\n ),\r\n #----------- Poi ------------------------------------\r\n box(title = \"Poisson\",width = 6,\r\n status = \"warning\", solidHeader = FALSE, \r\n collapsible = TRUE,\r\n sidebarPanel(width = 4, \r\n sliderInput(\"lambda\",\"lambda\",\r\n value = 2,\r\n min = 0.1,\r\n max = 50)\r\n ),\r\n mainPanel(plotOutput(\"plot_poi1\"))\r\n )\r\n )\r\n ),\r\n #-------------- Page3 ------------- \r\n tabItem(tabName = \"Page3\",\r\n # fluidRow(\r\n # box(title = \"Continuous\",width = 4,\r\n # solidHeader = FALSE, \r\n # collapsible = FALSE,\r\n # \"Choose one of the following major continuous distributions.\",\r\n # br(),\r\n # radioButtons(\"dist2\", \"Distribution type:\",\r\n # c(\"Uniform\",\"Exponential\",\"Normal\"))\r\n # ),\r\n # box(title = \"Definitions\",width = 8,solidHeader = FALSE, \r\n # collapsible = FALSE,\r\n # uiOutput(\"txt2\")\r\n # )\r\n # ),\r\n #----------- unif ------------------------------------\r\n fluidRow(\r\n box(title = \"Uniform\", width = 6,\r\n collapsible = TRUE,\r\n sidebarPanel(width = 4,\r\n # numericInput(\"min\", \"Minimum\", 2),\r\n # numericInput(\"max\", \"Maximum\", 5)\r\n sliderInput(\"unifRange\", \"Range\",\r\n min = 0, max = 20,\r\n value = c(2, 5))\r\n ),\r\n mainPanel(plotOutput(\"plot_unif1\"))\r\n ),\r\n \r\n \r\n \r\n \r\n #----------- Exponential ------------------------------------\r\n box(title = \"Exponential \",width = 6,\r\n solidHeader = FALSE, \r\n collapsible = TRUE,\r\n sidebarPanel(width = 4,\r\n sliderInput(\"lambda2\",\"lambda\",\r\n value = 2,\r\n min = 0.1,\r\n max = 5,\r\n step = 0.1)\r\n ),\r\n mainPanel(plotOutput(\"plot_exp1\")))\r\n ),\r\n #----------- Normal ------------------------------------\r\n fluidRow(\r\n box(title = \"Normal\", width = 6,\r\n collapsible = TRUE,\r\n sidebarPanel(width = 4, \r\n sliderInput(\"mu\",\"mu\",\r\n value = 175,\r\n min = 0,\r\n max = 200,\r\n step = 0.1),\r\n sliderInput(\"sigma\",\"sigma\",\r\n value = 6,\r\n min = 0.1,\r\n max = 50,\r\n step = 0.1)\r\n ),\r\n mainPanel(plotOutput(\"plot_norm1\"))\r\n )\r\n )\r\n ),\r\n #-------------- final ------------- \r\n tabItem(tabName = \"final\",\r\n # fluidRow(\r\n # column(width = 4,\r\n # box(\r\n # title = \"Updata:2022/01/07\", width = NULL, solidHeader = TRUE, status = \"warning\"\r\n # )\r\n # )\r\n # ),\r\n fluidRow(\r\n infoBox(\"Updata\", \"2022/01/07\", icon = icon(\"edit\"), fill = FALSE,color = \"light-blue\")\r\n ) # fluidRow\r\n ) #tabItem\r\n ) # tabItems\r\n) # dashboardBody\r\n#------------ ui -----\r\nui <- dashboardPage(header, sidebar, body)\r\n\r\n#------------ server -----\r\nserver <- function(input, output, session) {\r\n #------------ txt0 -----\r\n output$summary <- renderUI({\r\n withMathJax(includeHTML(\"dis_formula\\\\Summary.html\"))\r\n })\r\n #------------ coin ------------\r\n # https://ithelp.ithome.com.tw/articles/10196754\r\n ##\r\n v <- reactiveValues(times = NULL)\r\n observeEvent(input$action1, {\r\n v$times <- trunc(runif(1, min = 1, max = 3))\r\n })\r\n observeEvent(input$action2, {\r\n v$times <- trunc(runif(100, min = 1, max = 3))\r\n }) \r\n\r\n output$plot_coin <- renderPlot({\r\n if (is.null(v$times)) return()\r\n # count <- table(trunc(runif(1, min = 1, max = 3)))\r\n count <- table(v$times)\r\n sums <- integer(2)\r\n if(nrow(count)>1){\r\n sums <- count\r\n }else{\r\n ifelse(names(count)==\"1\",\r\n sums[1] <- as.numeric(count),\r\n sums[2] <- as.numeric(count))\r\n }\r\n \r\n # count <- as.numeric(table(trunc(runif(1, min = 1, max = 3))))[1:2]\r\n # count <- as.numeric(table(v$times))[1:2]\r\n # count[which(is.na(count))] <- 0\r\n \r\n dice <- data.frame(number = c(\"Heads\",\"Tails\"), \r\n count = sums) %>%\r\n mutate(p = (count / sum(count)), theoretical = (1/2)) \r\n \r\n \r\n title <- paste(\"Probability Distribution of coin\")\r\n ggplot(dice) + theme_basic() + \r\n geom_bar(aes(x = number, y = p),\r\n stat = \"identity\", position = \"dodge\",\r\n fill = c(\"#a2d2ff\",\"#bee1e6\"))+\r\n ggtitle(title)+\r\n geom_hline(yintercept=1/2, linetype=\"dashed\", color = \"red\")+\r\n # scale_x_continuous(labels = 1:2, breaks = 1:2)+\r\n scale_y_continuous(limits = c(0, max(dice$p)+0.05),\r\n breaks = seq(0, max(dice$p)+0.05, by = 0.1)) \r\n })\r\n # output$plot_coin <- renderPlot({\r\n # sums <- integer(2)\r\n # for (i in 1:input$n_coin) {\r\n # # \"roll\" number between 1 and 6; add together\r\n # outcome <- trunc(runif(1, min = 1, max = 3))\r\n # # count result\r\n # sums[outcome] <- sums[outcome] + 1\r\n # }\r\n # # prepare a data frame for graphing\r\n # dice <- data.frame(number = c(\"Heads\",\"Tails\"), count = sums[1:2]) %>%\r\n # mutate(p = (count / sum(count)), theoretical = (1/2)) \r\n # \r\n # \r\n # title <- paste(\"Probability Distribution of coin\")\r\n # ggplot(dice) + theme_basic() + \r\n # geom_bar(aes(x = number, y = p),\r\n # stat = \"identity\", position = \"dodge\",\r\n # fill = c(\"#ff9e00\",\"#00b4d8\"))+\r\n # ggtitle(title)+\r\n # # scale_x_continuous(labels = 1:2, breaks = 1:2)+\r\n # scale_y_continuous(limits = c(0, max(dice$p)+0.05),\r\n # breaks = seq(0, max(dice$p)+0.05, by = 0.1)) \r\n # })\r\n \r\n \r\n # https://stackoverflow.com/questions/61287106/how-to-create-a-table-in-a-reactive-object-in-shiny\r\n \r\n\r\n \r\n # output$data_coin <- renderTable({\r\n # tableData$d1\r\n # })\r\n\r\n #------------ dice ------------\r\n output$plot_dice <- renderPlot({\r\n sums <- integer(6)\r\n for (i in 1:input$n_dice) {\r\n # \"roll\" number between 1 and 6; add together\r\n outcome <- trunc(runif(1, min = 1, max = 7))\r\n # count result\r\n sums[outcome] <- sums[outcome] + 1\r\n }\r\n # prepare a data frame for graphing\r\n dice <- data.frame(number = 1:6, count = sums[1:6]) %>%\r\n mutate(p = (count / sum(count)), theoretical = (1/6)) \r\n \r\n \r\n title <- paste(\"Probability Distribution of dice\")\r\n ggplot(dice) + theme_basic() + \r\n geom_bar(aes(x = number, y = p),\r\n stat = \"identity\", position = \"dodge\",\r\n fill = c(\"#cdb4db\",\"#ffc8dd\",\"#ffafcc\",\"#bde0fe\",\"#a2d2ff\",\"#bee1e6\"))+\r\n ggtitle(title)+\r\n scale_x_continuous(labels = 1:6, breaks = 1:6)+\r\n scale_y_continuous(limits = c(0, max(dice$p)),\r\n breaks = seq(0, max(dice$p), by = 0.05))+ \r\n geom_hline(yintercept=1/6, linetype=\"dashed\", color = \"red\")\r\n })\r\n #------------ button -------\r\n ## ## 以下為反應分配按鈕,程式碼過長\r\n ## n <- 0\r\n ## observe({\r\n ## dist1 <- input$dist1\r\n ## n <- n+1\r\n ## if (!is.null(dist1)) {\r\n ## if (dist1=='dummy') showActions ()\r\n ## else {\r\n ## if (dist1=='Binomial')\r\n ## output$txt1 <- renderUI({\r\n ## withMathJax(paste(input$dist1,\"\\n\",\r\n ## \"$$f(x)=\\\\binom{n}{x}p^{x}(1-p)^{n-x}$$\",\"\\n\",\r\n ## \"$$\\\\text{E}(X)=np$$\",\"\\n\",\r\n ## \"$$\\\\text{Var}(X)=np(1-p)$$\"))\r\n ## \r\n ## })\r\n ## if (dist1=='Negative Binomial') \r\n ## output$txt1 <- renderUI({\r\n ## withMathJax(paste(input$dist1,\"\\n\",\r\n ## \"$$f(x)=\\\\binom{x+r-1}{r-1}p^{r}(1-p)^{x}$$\",\"\\n\",\r\n ## \"$$\\\\text{E}(X)=\\\\frac{rp}{1-p}$$\",\"\\n\",\r\n ## \"$$\\\\text{Var}(X)=\\\\frac{rp}{(1-p)^2}$$\"))\r\n ## \r\n ## })\r\n ## if (dist1=='Geometric') \r\n ## output$txt1 <- renderText (paste (input$dist1, \"action C\"))\r\n ## if (dist1=='Poisson') \r\n ## output$txt1 <- renderText (paste (input$dist1, \"action C\"))\r\n ## }\r\n ## } \r\n ## })\r\n \r\n #------------ txt1 -----\r\n output$txt1 <- renderUI({\r\n ## 會無法出現表格\r\n ## withMathJax(includeMarkdown(paste0(\"C:\\\\Users\\\\user\\\\R\\\\R_2021\\\\prob\\\\dis_formula\\\\\",input$dist1,\".md\")))\r\n \r\n # withMathJax(includeHTML(paste0(\"C:\\\\Users\\\\user\\\\R\\\\R_2021\\\\prob\\\\dis_formula\\\\\",input$dist1,\".html\")))\r\n withMathJax(includeHTML(paste0(\"dis_formula\\\\\",input$dist1,\".html\")))\r\n })\r\n #------------ txt2 -----\r\n output$txt2 <- renderUI({\r\n ## withMathJax(includeMarkdown(paste0(\"C:\\\\Users\\\\user\\\\R\\\\R_2021\\\\prob\\\\dis_formula\\\\\",input$dist1,\".md\")))\r\n \r\n # withMathJax(includeHTML(paste0(\"C:\\\\Users\\\\user\\\\R\\\\R_2021\\\\prob\\\\dis_formula\\\\\",input$dist2,\".html\")))\r\n \r\n withMathJax(includeHTML(paste0(\"dis_formula\\\\\",input$dist2,\".html\")))\r\n })\r\n #------------ Bin(n,p) #####\r\n output$plot_bin1 <- renderPlot({\r\n x <- seq(from = 0,to = input$n,by = 1) #成功次數\r\n plot(x,dbinom(x,size = input$n, prob=input$p), # \r\n pch=16,type=\"h\", #type='l'\r\n main = paste(\"Binomial ( n=\",input$n,\", p=\",input$p,\")\"),\r\n ylab='Probability',\r\n xlab ='x',\r\n lwd=4,\r\n col=\"deepskyblue\")\r\n })\r\n #------------ NB(r,p) #####\r\n output$plot_nb1 <- renderPlot({\r\n x <- seq(from = 0,to = input$r,by = 1) #成功次數\r\n plot(x,dbinom(x,size = input$r, prob=input$p_nb), # \r\n pch=16,type=\"h\", \r\n main = paste(\"Negative Binomial ( r=\",input$r,\", p=\",input$p_nb,\")\"),\r\n ylab='Probability',\r\n xlab ='x',\r\n lwd=4,\r\n col=\"deepskyblue\")\r\n })\r\n #------------ geo(p) #####\r\n output$plot_geo1 <- renderPlot({\r\n x <- seq(from = 0,to = 30,by = 1)\r\n plot(x,dgeom(x, prob=input$p_geo), # \r\n type = 'h', \r\n main = paste(\"Geometric ( p=\",input$p_geo,\")\"),\r\n ylab = 'Probability',\r\n xlab = 'x',\r\n lwd=4,\r\n col=\"deepskyblue\")\r\n })\r\n #------------ Poisson (λ) #####\r\n output$plot_poi1 <- renderPlot({\r\n x <- seq(from = 0,to = 30,by = 1)\r\n plot(x,dpois(x, lambda = input$lambda), # \r\n type = 'h', #type='o'\r\n main = paste(\"Poisson ( λ=\",input$lambda,\")\"),\r\n ylab = 'Probability',\r\n xlab = 'x',\r\n lwd=4,\r\n col=\"deepskyblue\")\r\n })\r\n #------------ unif (a,b) #####\r\n output$plot_unif1 <- renderPlot({\r\n \r\n # x <- seq(from = input$min-0.5,to = input$max+0.5, length=100)\r\n # plot(x,dunif(x,input$min,input$max),\r\n # type = 'l',pch=16,\r\n # main = paste(\"Unif ( a=\",input$min,\",\",\"b=\",input$max,\")\"),\r\n # ylab = 'density',\r\n # xlab = 'x',\r\n # col=\"deepskyblue\",\r\n # lwd=\"4\")\r\n \r\n x <- seq(from = min(input$unifRange)-3,to = max(input$unifRange)+3, length=100)\r\n plot(x,dunif(x,min(input$unifRange),max(input$unifRange)),\r\n type = 'l',pch=16,\r\n main = paste(\"Unif ( a=\",min(input$unifRange),\",\",\"b=\",max(input$unifRange),\")\"),\r\n ylab = 'density',\r\n xlab = 'x',\r\n col=\"deepskyblue\",\r\n lwd=\"4\")\r\n })\r\n #------------ exp (λ) ------------\r\n output$plot_exp1 <- renderPlot({\r\n \r\n x <- seq(from = min(rexp(100,input$lambda2)),to = max(rexp(100,input$lambda2)), by=0.01)\r\n plot(x,dexp(x,input$lambda2),\r\n type = 'l',pch=16,\r\n main = paste(\"Exp ( λ=\",input$lambda2,\")\"),\r\n ylab = 'density',\r\n xlab = 'x',\r\n col=\"deepskyblue\",\r\n lwd=\"4\")\r\n })\r\n #------------ N(μ,σ) #####\r\n output$plot_norm1 <- renderPlot({\r\n x <- seq(from = min(rnorm(100,input$mu,input$sigma)), to = max(rnorm(100,input$mu,input$sigma)), by = 0.1)\r\n plot(x, dnorm(x,input$mu,input$sigma), type = \"l\", \r\n ylab = \"density\",\r\n main = paste(\"Normal ( μ=\",input$mu,\",σ=\",input$sigma,\")\"),\r\n xlab = 'x',\r\n col=\"deepskyblue\",\r\n lwd=\"4\")\r\n })\r\n}\r\nshinyApp(ui, server)\r\n", "meta": {"hexsha": "d9b7d121def1ee5ac0515b1bca680166dcd4b577", "size": 21952, "ext": "r", "lang": "R", "max_stars_repo_path": "app_prob_2022_0115.r", "max_stars_repo_name": "TaraInTaiwan/Probability-Distributions", "max_stars_repo_head_hexsha": "6b965ec7d5475e079b1dbc2826b87182df1c0290", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "app_prob_2022_0115.r", "max_issues_repo_name": "TaraInTaiwan/Probability-Distributions", "max_issues_repo_head_hexsha": "6b965ec7d5475e079b1dbc2826b87182df1c0290", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "app_prob_2022_0115.r", "max_forks_repo_name": "TaraInTaiwan/Probability-Distributions", "max_forks_repo_head_hexsha": "6b965ec7d5475e079b1dbc2826b87182df1c0290", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.8029739777, "max_line_length": 113, "alphanum_fraction": 0.3840196793, "num_tokens": 5117, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5964331319177487, "lm_q2_score": 0.6548947357776795, "lm_q1q2_score": 0.39060091833632793}} {"text": "# Fit SSD to CCME data for several metals\n\n# Copyright 2017 Province of British Columbia\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and limitations under the License.\n\n\n# We compare fits for the distributions with AIC\n# Refer to https://cran.r-project.org/web/packages/fitdistrplus/vignettes/FAQ.html\n# for information on the fitdistrplus package.\n# Refer to AICcmodavg package for details on creating the AIC tables and\n# how to do model averaging.\n\n# Load the necessary libraries\nlibrary(AICcmodavg)\nlibrary(actuar) # for the burr distribution\nlibrary(FAdist) # for log-logistic\nlibrary(fitdistrplus)\nlibrary(ggplot2)\nlibrary(grid)\nlibrary(gridGraphics)\nlibrary(plyr) # for doing a separate analysi by chemical\nlibrary(VGAM) # for the gompertz, pareto, gumbel distributions\n\n\n\nsource(\"mygofstat.r\") # corrects and error in the code in the fistdistr package (groan)\n#source(\"C:/R-repositories/SSD-fitting/CCME-fits/mygofstat.r\")\n\n#load test data\nendpoints<-read.csv(\"CCME data.csv\",header=TRUE,as.is=TRUE, strip.white=TRUE)\n#endpoints<- read_csv(\"C:/R-repositories/SSD-fitting/CCME-fits/CCME data.csv\")\n\nhead(endpoints)\n\nxtabs(~Chemical, data=endpoints, exclude=NULL, na.action=na.pass)\n\n# create a directory for plots\ndir.create(file.path(\"Plots\"))\n\n\n#use descdist function from fitdistrplus package to identify candidate distributions - create a Cullen Frey graph\nsumstats <- plyr::ddply(endpoints, \"Chemical\", function(x, boot){\n # create the individual plots\n png(file.path(\"Plots\",paste(x$Chemical,\".png\",sep=\"\")), h=6, w=6, units=\"in\", res=300)\n res <- descdist(x$Conc,discrete=FALSE, boot=boot)\n dev.off()\n # return the summary statistics as a dataframe, rather than a list\n attr(res, \"class\") <- NULL # remove class attribute from results\n data.frame(res)\n}, boot=100)\n\n# summary statistics\nsumstats\n\n# create list of possible distributions (the pareto and burr distributions have been commented out of the list below because they are not included in SSD Master)\nfit.list <- list( lnorm = list(data=NULL, distr=\"lnorm\", method=\"mle\"),\n llog = list(data=NULL, distr=\"llog\", method=\"mle\"), # log logistic\n gomp = list(data=NULL, distr=\"gompertz\",method=\"mle\"),\n lgumbel= list(data=NULL, distr=\"lgumbel\",method=\"mle\"), # log gumbel\n gamma = list(data=NULL, distr=\"gamma\", method=\"mle\"), \n# pareto = list(data=NULL, distr=\"pareto\", method=\"mle\"),\n weibull= list(data=NULL, distr=\"weibull\",method=\"mle\")\n# burr = list(data=NULL, distr=\"burr\", method=\"mle\")\n )\n\n\n# define log-gumbel distribution\n# These functions are needed because this is a non-standard distribution\ndlgumbel <- function(x, location=0, scale=0, log=FALSE){ \n fx <- dgumbel(log(x), location=location, scale=scale, log=FALSE)/x\n if(log) fx <- log(fx)\n fx}\nqlgumbel <- function(p, location=0, scale=0, lower.tail=TRUE, log.p=FALSE){ \n if(log.p) p<- exp(p)\n if(!lower.tail) p <- 1-p\n exp( qgumbel(p, location=location, scale=scale))}\nplgumbel <- function(q, location=0, scale=0, lower.tail=TRUE, log.p=FALSE){ \n Fq <- pgumbel(log(q), location=location, scale=scale)\n if(!lower.tail) Fq <- 1-Fq\n if(log.p) Fq <- log(Fq)\n Fq}\nrlgumbel <- function(n, location=0, scale=0){ exp(rgumbel(n, location=location, scale=scale))}\n\n#endpoints <- endpoints[ endpoints$Chemical==\"Boron_CCME\",] # for testing to fit only one chemical\n\n# Fit each distribution from the list to each chemical\nfit.all <- plyr::dlply(endpoints, \"Chemical\", function(x, probs=c(.05,.10), nboot=1000){\n cat(\"Analyzing \", x[1,\"Chemical\"],\"\\n\")\n # fit all of the distributions in the list to this data. If\n # a distribution fitting does not converge, then it returns NULL\n dist.fits <- plyr::tryapply(fit.list, function(distr, x){\n distr$data <- x$Conc\n if(distr$distr==\"burr\"){\n distr$start <-list(shape1=4, shape2=1, rate=1)\n distr$method<- \"mme\"\n distr$order <- 1:3\n distr$memp <- function (x, order){sum(x^order)}\n }\n if(distr$distr=='gamma'){\n distr$start <- list(scale=var(x$Conc)/mean(x$Conc), \n shape=mean(x$Conc)^2/var(x$Conc)^2)\n }\n if(distr$distr == 'gompertz'){\n # use the vgam to get the parameters of the fit\n fit <- vglm(Conc~1, gompertz, data=x)\n distr$start <- list(shape=exp(unname(coef(fit)[2])), scale=exp(unname(coef(fit)[1])) )\n }\n if(distr$distr=='lgumbel'){\n distr$start <- list(location=mean(log(x$Conc)), scale=pi*sd(log(x$Conc))/sqrt(6))\n }\n if(distr$distr=='pareto'){ #use the vgam package to estimate the starting values\n fit<- vglm(Conc~1, paretoff, data=x)\n distr$start <- list(shape=exp(unname(coef(fit)))) \n distr$fix.arg<- list(scale=fit@extra$scale)\n }\n if(distr$distr==\"llog\" ){ # log=logistic\n distr$start <- list(shape=mean(log(x$Conc)), scale=pi*sd(log(x$Conc))/sqrt(3))\n }\n cat(\" Fitting \", distr$distr,\"\\n\")\n res <- do.call(\"fitdist\", distr)\n print(res)\n res\n },x=x)\n \n # Get the aic table by hand. \n aic.table <- plyr::ldply(dist.fits, function(x){\n # extract the distribution name and AIC value\n aic <- x$aic\n distname <- x$distname\n aicc <- AICcmodavg::AICc(x) # conflict with VGAM package\n nparm <- length(x$estimate)\n data.frame(distname=distname, aic=aic, k=nparm, aicc=aicc)\n })\n aic.table <- aic.table[order(aic.table$aicc),]\n aic.table$delta.aicc <- aic.table$aicc - min(aic.table$aicc)\n aic.table$weight <- round(exp(-aic.table$delta.aicc/2)/sum(exp(-aic.table$delta.aicc/2)),3)\n \n # make predictions for HC5 based on all of the distributions\n # Include a bootstrap approximation to the se of the estimates\n pred.table <- plyr::ldply(dist.fits, function(x, probs=.05, nboot=1000){\n distname <- x$distname\n pred <- quantile(x, probs)\n fit.boot <- bootdist(x, niter=nboot)\n #browser()\n se <- apply(quantile(fit.boot, probs=probs)$bootquant, 2, sd, na.rm=TRUE)\n lcl <- quantile(fit.boot, probs=probs)$quantCI[1,]\n ucl <- quantile(fit.boot, probs=probs)$quantCI[2,]\n #cat(\"pred.table\", distname, pred, se, lcl, ucl, \"\\n\")\n data.frame(distname=distname, quantile=probs, pred=unlist(pred$quantiles), se=se, lcl=unlist(lcl), ucl=unlist(ucl) )\n }, probs=probs, nboot=nboot)\n \n pred.table <- merge(pred.table, aic.table[,c(\"distname\",\"weight\")])\n \n # compute the model averaged quantiles, the model averaged lcl and ucl, and unconditional se\n q.modavg <- plyr::ddply(pred.table, \"quantile\", function(x){\n avg.pred <- sum(x$pred * x$weight)\n avg.lcl <- sum(x$lcl * x$weight)\n avg.ucl <- sum(x$ucl * x$weight)\n # get the unconditional se\n avg.u.se <- sqrt(sum(x$weight * (x$se^2 + (x$pred-avg.pred)^2)))\n data.frame(avg.pred=avg.pred, avg.u.se=avg.u.se, avg.lcl=avg.lcl, avg.ucl=avg.ucl)\n })\n q.modavg\n \n \n # make the cdf plot comparing all of the fits\n # capture the plot and save it\n # get the list of distributions that were fit\n dist.names <- plyr::laply(dist.fits, function(x) x$distname)\n cdfcomp(dist.fits, xlogscale=TRUE, legendtext=dist.names,\n main=paste(\"Empirical and theoretical CDF's - \",x[1,\"Chemical\"],sep=\"\"),\n fitcol=c(\"red\",\"blue\",\"darkgreen\",\"black\",\"darkblue\",\"cyan\",\"violet\"),\n fitlty=1:3)\n gridGraphics::grid.echo()\n cdf.comp.plot <- grid::grid.grab()\n \n #compute the goodmess of fit statistics - NOTE this does not work for burr distribution, not sure why...\n # must check to see if more than one distribution was fit - groan.\n # Also had to fix an error in compute p-value for chi2 test when df=0\n if(length(dist.fits) ==1) {gof.stat <- mygofstat(dist.fits[[1]], fitnames=dist.names)}\n if(length(dist.fits) >1 ) {gof.stat <- mygofstat(dist.fits,fitnames =dist.names)}\n# The following fails because of a bug in gofstat. See mygofstat file for details\n# if(length(dist.fits) ==1) {gof.stat <- fitdistrplus::gofstat(dist.fits[[1]], fitnames=dist.names)}\n# if(length(dist.fits) >1 ) {gof.stat <- fitdistrplus::gofstat(dist.fits,fitnames =dist.names)}\n \n # return the entire fitting stuff for this distibution\n list(Chemical=x[1,\"Chemical\"], dist.fits=dist.fits, aic.table=aic.table, pred.table=pred.table, \n q.modavg=q.modavg,\n cdf.comp.plot =cdf.comp.plot,\n gof.stat =gof.stat)\n})\n\ndisplay.results <- function(x){\n # display the results from the fitting functions\n cat(\"\\n\\n\\n\\n\\n\\n\\n\\n\\n *******************************************************************\\n\")\n cat(\"\\n\\nResults when applied to \", x$Chemical, \"\\n\")\n cat(\"\\n\\nAICc table \\n\")\n print(x$aic.table)\n \n cat(\"\\n\\nPredictions of endpoints \\n\")\n print(x$pred.table)\n \n cat(\"\\n\\nModel averaged endpoint \\n\")\n print(x$q.modavg)\n \n cat(\"\\n\\nCDF comparative plot\\n\")\n grid.newpage()\n grid.draw(x$cdf.comp.plot)\n \n cat(\"\\n\\nGoodness of fit statistics\\n\")\n print(x$gof.stat)\n \n}\n\n\n# display all of the results from all of the Chemicals\nplyr::l_ply(fit.all, display.results)\n\n# save the comparative plot\nplyr::l_ply(fit.all, function(x){\n file.name=file.path(\"Plots\",paste(x$Chemical,\"-comparative-plot.png\",sep=\"\"))\n png(file.name, h=6, w=6, units=\"in\", res=300)\n grid.newpage()\n grid.draw(x$cdf.comp.plot)\n dev.off()\n})\n\n# Make a nice plot of the estimates and ci and compare them to the CCME guidelines\n\nccme.csv<- textConnection(\n\"Chemical,n, HC5, lcl, ucl, dummy, dummy, dummy\nBoron , 28 , 1.5 , 1.2 , 1.7 , 1.2 , 0.59 , 3.20\nCadmium , 36 , 0.09 , 0.04 , 0.24 , 0.14 , 0.06 , 0.34\nChloride , 28 , 120 , 90 , 150 , 73 , 27 , 198\nEndosulfan , 12 , 0.003 , 0.0007 , 0.01 , 0.010 , 0.0012 , 0.51\nGlyphosate , 18 , 800 , 490 , 1320 , 900 , 459 , 2301\nSilver , 9 , 0.25 , 0.17 , 0.39 , 0.19 , 0.069 , 0.89\nUranium , 13 , 15 , 8.5 , 25 , 15 , 3.1 , 124\")\n\nccme <- read.csv(ccme.csv, header=TRUE, as.is=TRUE, strip.white=TRUE)\nccme$dummy <- NULL\nccme$dummy.1 <- NULL\nccme$dummy.2 <- NULL\nccme$EstType <- \"CCME\"\nccme$n <- NULL\nccme\n\n# get the estimates of HC5\nfit.hc5 <- plyr::ldply(fit.all, function(x){\n # extract the model averaged\n q <- x$q.modavg[ x$q.modavg$quantile == 0.05,]\n data.frame( HC5=q$avg.pred, lcl=q$avg.lcl, ucl=q$avg.ucl, EstType=\"ModelAvg\")\n})\n\nfit.hc5$Chemical <- gsub(\"_CCME\", \"\", fit.hc5$Chemical)\nfit.hc5quuantile <- NULL\nfit.hc5\n\nboth <- rbind(ccme, fit.hc5)\nboth\n\nlab_log10 <- function (x){\n # create nice labels for the next plot\n y <- as.character(x)\n y\n}\n\n\ncompplot <- ggplot(data=both, aes(x=Chemical, y=HC5, color=EstType))+\n geom_point( position=position_dodge(w=0.4))+\n geom_errorbar(aes(ymin=lcl, ymax=ucl), width=0.1,position=position_dodge(w=0.4))+\n scale_y_log10(labels=lab_log10)+\n #scale_color_discrete(name=\"Method\")+\n labs(x = \"Chemical\")+\n ylab(bquote('Log' ~HC[5]))+\n theme(axis.text.x = element_text(angle=45,hjust = 1))+\n scale_color_manual(labels = c(\"Least Squares\", \"MLE\"), values = c(\"red\", \"black\"))+\n guides(colour=guide_legend(\"Method\"))\ncompplot\n\nggsave(\"Plots/compplot_mod.png\", compplot, width = 5.97, height = 5.97)\n\n\n#calculating percent difference of HC5 values\nboth.hc5 <- reshape2::dcast(both, Chemical ~ EstType, value.var=\"HC5\")\n \nboth.hc5$perdiff <- abs(both.hc5$CCME - both.hc5$ModelAvg)/(both.hc5$CCME + both.hc5$ModelAvg)*2*100\nboth.hc5\nsummarize(both.hc5, \n mean.perdiff = mean(perdiff))\n\n\n#calculate width ratio (ModelAvg/CCME)\nboth$ci.width <- both$ucl - both$lcl\nboth.hc5 <- reshape2::dcast(both, Chemical ~ EstType, value.var=\"ci.width\")\n\nboth.hc5$width.ratio <- both.hc5$ModelAvg / both.hc5$CCME\nboth.hc5\nsummarize(both.hc5, \n mean.widthratio = mean(width.ratio))\n\n\n", "meta": {"hexsha": "9e03b05e99b7739750ce6b5575ef9771e9b866c4", "size": 12813, "ext": "r", "lang": "R", "max_stars_repo_path": "CCME-fits/CCME_fit.r", "max_stars_repo_name": "bcgov/SSD-methods", "max_stars_repo_head_hexsha": "8ec33c5029f8016fe24d66a127ef744b9696d1bd", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2017-04-19T05:30:14.000Z", "max_stars_repo_stars_event_max_datetime": "2017-12-01T05:50:56.000Z", "max_issues_repo_path": "CCME-fits/CCME_fit.r", "max_issues_repo_name": "bcgov/SSD-methods", "max_issues_repo_head_hexsha": "8ec33c5029f8016fe24d66a127ef744b9696d1bd", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2018-03-01T22:58:58.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-05T19:13:14.000Z", "max_forks_repo_path": "CCME-fits/CCME_fit.r", "max_forks_repo_name": "bcgov/SSD-methods", "max_forks_repo_head_hexsha": "8ec33c5029f8016fe24d66a127ef744b9696d1bd", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2017-12-01T04:03:46.000Z", "max_forks_repo_forks_event_max_datetime": "2017-12-01T04:03:46.000Z", "avg_line_length": 41.0673076923, "max_line_length": 161, "alphanum_fraction": 0.6281120737, "num_tokens": 3846, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191460821871, "lm_q2_score": 0.5506073655352404, "lm_q1q2_score": 0.3903911641383588}} {"text": "\n# Bilan hydrique d'une vigne enherb?e\n# X.Delpuech (IFV) d'apres F.Celette, A. Ripoche, 2009\n# S.Roux : quelques modifications pour param?trage, lisibilit?\n#######################\n\n\n###############################\n# DEFINITION DES SOUS-FONCTIONS\n\n\n#######\n# Fonction Somme de temp?rature base cumsumb(vecteur temp?rature, base, ligne de d?but, ligne de fin)\n# base : definit la valeur de base pour la somme des temp?ratures, par d?faut = 10\n# x : definit le vecteur d'entr?e\n# debut : definit la ligne de debut du calcul, par d?faut = 1\n# fin : definit la ligne de fin du calcul, par d?faut la derni?re ligne de x\n\ncumsumb<-function(x,base=10,debut=1,fin=length(x)) \n{\n\tsomTb<-vector(mode=\"numeric\",length = length(x)) #cree un vecteur vide du m?me nombre de ligne que le vecteur d'entr?e x\n\tifelse (x[debut]>base,somTb[debut]<-(x[debut]-base),somTb[debut]<-0) # Calcul la premi?re valeur de la somme de Temp en base\n\tfor (i in (debut+1):fin)\n\t{\n\t\tifelse (x[i]>base, somTb[i]<-(somTb[i-1]+x[i]-base), somTb[i]<-somTb[i-1])\n\t} # Calcul des SomTb de la ligne 2 ? la fin des donn?es m?t?o\n\treturn(somTb)\n}\n\n########\n# Fonctions calcul du seuil de ruissellement Sr(CN)\n\n# Fonction calcul du seuil de ruissellement (p5j,cn2,p5j1,p5j2)\nSeuilR<-function(p5j,cn2,p5j1,p5j2)\n{\n\tcn1 = (4.2*cn2)/(10-0.058*cn2)\n\tcn3 = (23*cn2)/(10+0.13*cn2)\n\t\n\t#calcul du seuil de ruissellement\n\tif (p5jp5j2)\n\t\t\tres = 254*(100/cn3-1) \n\t\telse\n\t\t\tres = 254*(100/cn2-1) \n\t}\n\treturn(res)\n\t\t\n}\n\n# Fonction calcul du ruissellement Rs(pluie,seuil ruissellement)\nRuiss<-function(P,sr) # P = pluie en mm , sr = seuil de ruissellement\n{\n\tif (P<0.2*sr) y<-0\n\telse y<-((P-0.2*sr)^2/(P+0.8*sr))\n\treturn (y)\n}\n###############################\n# param?trage par defaut\n\n\nnominal=list(p=0.6,\n\t\tTonte=\"N\", \t\t\t\t\t\t\t# caractere {O,N} d'activation des tontes aux dates prevues (renint LAI)(si \"N\", tontes automatique /LAI)\n\t\tnbtonte=c(2,2,2,0,0,0,0), \t\t\t# D?finit le nombre de tonte chaque ann?e de simulation\n\t\tinn=0.3, \t\t\t\t\t\t\t# D?finit l?INN de l?herbe\n\t\tirri=\"N\", \t\t\t\t\t\t\t# caractere {O,N} d'activation de l?irrigation qui branche la colonne \"IR\" du fichier meteo \n\t\tdtonte=rep(\"29/03\",10), \t\t\t# date des tontes activ? par le parametre \"Tonte\" \n\t\tdbr=rep(\"26/03\",10), \t\t\t\t# dates de d?marrage de la v?g?tation de la vigne (en nombre >=sup?rieur ou ?gal au nombre d?ann?es simul?es)\n\t\tarretTr=\"01/11\", \t\t\t\t\t# date d?arr?t de transpiration de la vigne\n\t\tddkmax=600, \t\t\t\t\t\t# nombre de degr? jour pour atteindre le Kmax\n\t\treinit=\"N\",\t\t\t\t\t\t\t# caractere {O,N} pour reinitialiser les stocks d'eau en debut d'ann?e\n\t\tpir=0, \t\t\t\t\t\t\t\t# Permet d?attribuer un CN diff?rent (donn? par CN_Ruiss2) ? l?inter-rang m?me en absence d?enherbement. \n\t\tseuilpeff=2,\t\t\t\t\t\t# seuil de pluie efficace\n\t\tkmax=rep(0.43,10),\t\t\t\t\t# coefficient d?interception du rayonnement de la vigne\n\t\tlevee=\"01/01\",\t\t\t\t\t\t# date de lev?e de l?enherbement \n\t\tflagRuiss=\"O\",\t\t\t\t\t\t# utilisation du module de ruissellement \"O\" active\n\t\tCN_Ruiss=94,\t\t\t\t\t\t# CN (ruissellement) sous le rang\n\t\tCN_Ruiss2=84,\t\t\t\t\t\t# CN (ruissellement) dans l?inter-rang\n\t\therblairate=0.9,\t\t\t\t\t# LAI rate de l?enherbement\n\t\tLAIinit=0.5,\t\t\t\t\t\t# LAI initial de l?enherbement\n\t\tLAIres=0.3,\t\t\t\t\t\t\t# LAI r?siduel de l?enherbement apr?s une tonte\n\t\tLLSmin=700,\t\t\t\t\t\t\t# LLSmin de l?herbe\n\t\tLAItonte=3,\t\t\t\t\t\t\t# LAI ? partir duquel on d?clenche une tonte automatiquement\n\t\tU=2.7,\t\t\t\t\t\t\t\t# param?tre U d??vaporation du sol\n\t\tb1_evap=14,\t\t\t\t\t\t\t# param?tre b1_evap d??vaporation du sol\n\t\tb2_evap=0.15,\t\t\t\t\t\t# param?tre b2_evap d??vaporation du sol\n\t\tFTSWhregultr=0.6,\t\t\t\t\t# FTSW du compartiment herbe ? partir de laquelle l?herbe r?gule sa transpiration\n\t\tFTSWhregulLAI=0.9,\t\t\t\t\t# FTSW du compartiment herbe ? partir de laquelle l?herbe r?gule son LAI\n\t\tTTSWh=129,\t\t\t\t\t\t\t# TTSW du compartiment herbe\n\t\tTTSWv=224,\t\t\t\t\t\t\t# TTSW du compartiment vigne\n\t\tFTSWvregulTR=0.4,\t\t\t\t\t# FTSW du compartiment vigne ? partir de laquelle la vigne r?gule sa transpiration\n\t\tASWhinit=70.92,\t\t\t\t\t\t# quantit? d?eau dans le compartiment vigne en d?but de simulation\n\t\tASWvinit=178.18,\t\t\t\t\t\t# quantit? d?eau dans le compartiment herbe en d?but de simulation\n\t\tformat_date=\"%d/%m/%Y\" # format des dates dans le fichier m?t?o d'entr?e\n\t\t)\n\n\n###############################\n# FONCTION BH\nwalis.model.single<-function( param, meteo)\t\n{ \n\n\t###############################\n\t## FONCTION DE BILAN HYDRIQUE\n\n\tif(param$p!=0) param$pir<-param$p\n\n\t# DEFINITION PARAMETRE DU MODELE\n\n\tdat<-as.POSIXlt(strptime(meteo$Date,param$format_date))\n\t#\n\t# Nombre d'ann?e : \"an\" donne le nombre d'ann?es dans le fichier\n ans<-unique(dat$year) # donne le vecteur des ann?es du fichier\n an<-length(ans) # donne le nombre d'ann?e dans le fichier\n\t\n\t# jdeb donne les lignes de d?but de chaque ann?e\t\n jj<-as.POSIXlt(dat)$yday # vecteur des jours julien\n ll<-c(1:dim(meteo)[1]) # vecteur indice des lignes\n jdeb<-ll[jj==0]\n if (an>1 & jj[1]>1) jdeb=c(1,jdeb)\n jdeb[1]<-1 # au cas ou l'anne ne commence pas au 01/01\n jdeb[an+1]<-(dim(meteo)[1]+1)\n\n\n\t# Calcul des lignes correspondant aux dates du BH (avec cette m?thode, il y a un d?calage d'un jour les ann?es non bisextiles, \n\t#il faudrait rajouter les ann?es...)\n\t# la fonction as.POSIXlt()$yday donne le jour julien de la date\n\tleveejj\t\t<-as.POSIXlt(as.Date(param$levee,\"%d/%m\"))$yday\n\tdbrjj\t\t<-as.POSIXlt(as.Date(param$dbr,\"%d/%m\"))$yday\n\tarretTrjj\t<-as.POSIXlt(as.Date(param$arretTr,\"%d/%m\"))$yday\n\ttontejj\t\t<-as.POSIXlt(as.Date(param$dtonte,\"%d/%m\"))$yday\n\tLdbr\t\t<-c(1:an)\n\tLtonte\t\t<-c(1:sum(param$nbtonte[1:an]))\n\n# Calcul des indices d?bourrement\n# pour la premiere annee, si la date de debourrement est anterieure au premier jour du fichier\nif ((dbrjj[1]-jj[1])<0)\n{\ndbrjj[1]<-jj[1] # for?age au premier jour\nprint (\"Attention : date de dbr pour l'annee 1 forcee au 1er jour\")\n} \n# au cas ou la date de debourrement est posterieure a la fin du fichier\nfor (i in 1:an)\n{\nif (max(jj[dat$year==ans[i]])-dbrjj[i]<0) # si la date de dbr est posterieur a la fin du fichier\n{\ndbrjj[i]<-max(jj[dat$year==ans[i]])\nprint(\"Attention : date de dbr de la derniere annee forcee au dernier jour\")\n}\nLdbr[i]<-ll[dat$year==ans[i]&jj==dbrjj[i]]\n}\n# Calcul des indices levee de l'herbe\nLlevee<-ll[jj==leveejj]\nif (an>1 & jj[1]>leveejj) Llevee=c(1,Llevee)\n\n# pour l'annee 1, il se peut que la date de lev?e soit ant?rieure au 1er jour de donn?es\n# par exemple si le fichier ne d?marre pas au 01/01 \n\tLlevee[1] <- leveejj[1]-strptime(meteo$Date[1],param$format_date)$yday\n\tif (Llevee[1]<0)\n\t{\n\t\tLlevee[1]<-1\n\t\tprint(\"Attention : date de levee de l'herbe pour l'annee 1 forcee au premier jour\")\n\t}\n\n## pour l'arret de transpiration\n# si le fichier meteo se termine avant la date d'arret\nLarretTr<-c(1:an)\nfor (i in 1:an)\n{\nif (max(jj[dat$year==ans[i]])-arretTrjj<0) # si la date d'arret Transpiration est posterieur a la fin du fichier\n{\nLarretTr[i]<-length(ll)\nprint(\"Attention : date d'arret de transpiration de la derniere annee forcee au dernier jour\")\n}\nif (max(jj[dat$year==ans[i]])-arretTrjj>=0)\n{\nLarretTr[i]<-ll[dat$year==ans[i]&jj==arretTrjj]\n}\n}\n\n# pour la premiere annee, si la date de tonte est anterieure au premier jour du fichier\nfor (i in 1:param$nbtonte[1])\n{\nif ((tontejj[i]-jj[1])<0)\n{\ntontejj[i]<-jj[1] # for?age au premier jour\nprint (paste(\"Attention : date de tonte n?\",i,\" pour l'annee 1 forcee au 1er jour\"))\n}\n} \ni<-1\ntt<-1\nrepeat\n{\nif (tt>an) break()\nif (i>sum(param$nbtonte)) break()\nif (max(jj[dat$year==ans[tt]])-tontejj[i]<0)\n{\nLtonte[i]<-length(ll)\nprint(paste(\"Attention : forcage date de tonte n?\",i,\" au dernier jour\"))\n}\nif (max(jj[dat$year==ans[tt]])-tontejj[i]>0)\n{\nLtonte[i]<-ll[dat$year==ans[tt]&jj==tontejj[i]]\n}\ni<-i+1\nif (i>cumsum(param$nbtonte)[tt]) tt<-tt+1\n}\n\n\t\n\t# Calcul des vecteurs somme de T?C\n\tsomTb10\t<-vector(mode=\"numeric\",length = dim(meteo)[1])\n\tfor (a in 1:an)\n\t\tsomTb10<-(somTb10+cumsumb(meteo$Temp,debut=Ldbr[a], fin=(jdeb[a+1]-1)))\n\n\n\t# Calcul de la Pluie efficace\n\tPeff<-vector(mode=\"numeric\",length=dim(meteo)[1]) #creer un vecteur vide du meme nombre de ligne que meteo\n\tfor (i in 1:dim(meteo)[1])\n\t\t\tifelse (meteo$Pluie[i]>param$seuilpeff, Peff[i]<-meteo$Pluie[i],Peff[i]<-0) # si pluie >2mm, alors Peff = pluie, sinon =0\n\t\n\t\n\t# Calcul de la Peff pour l'enherbement et la vigne\n\tPeffh<-(Peff*param$p)\n\tPeffv<-(Peff*(1-param$p))\n\n\n\t#\n\t# Somme des pluies des 5 derniers jours\n\tP5j\t\t<-vector(mode=\"numeric\",length=dim(meteo)[1]) #vecteur vide\n\tP5j[1]\t<-0\n\tfor (i in 2:5)\n\t P5j[i]\t<-P5j[i-1] + meteo$Pluie[i-1]\n\tfor (i in 6:dim(meteo)[1])\n\t P5j[i]<-(meteo$Pluie[i-5]+meteo$Pluie[i-4]+meteo$Pluie[i-3]+meteo$Pluie[i-2]+meteo$Pluie[i-1])\n\t\n\t\n\t#\n\t# Calcul du ruissellement herbe (inter rang)\n\tSeuilrui<-vector(mode=\"numeric\",length=dim(meteo)[1]) # vecteur vide \n\tRuissh<-vector(mode=\"numeric\",length=dim(meteo)[1]) #vecteur vide\n\tfor (i in 1:dim(meteo)[1]) # attribution de la valeur de ruissellement en fonction de la pluie des 5 derniers jours\n\t{\n\t\tSeuilrui[i]<-SeuilR(P5j[i],param$CN_Ruiss2,35.6,53.3)\n\t\tRuissh[i]<-Ruiss(meteo$Pluie[i],Seuilrui[i])*param$pir\n\t\tif (param$flagRuiss==\"N\") Ruissh[i]=0\n\t}\n\n\t# Calcul du seuil ruissellement vigne (rang)\n\tSeuilruiv<-vector(mode=\"numeric\",length=dim(meteo)[1]) # vecteur vide \n\tRuissv<-vector(mode=\"numeric\",length=dim(meteo)[1]) #vecteur vide\n\tfor (i in 1:dim(meteo)[1]) # attribution de la valeur de ruissellement en fonction de la pluie des 5 derniers jours\n\t{\n\t\tSeuilruiv[i]<-SeuilR(P5j[i],param$CN_Ruiss,12.7,28)\n\t\tRuissv[i]<-Ruiss(meteo$Pluie[i],Seuilruiv[i])*(1-param$pir)\n\t\tif (param$flagRuiss==\"N\") Ruissv[i]=0\n\t}\n\n\t#\n\t# Calcul de la pluie efficace - le ruissellement inter-rang (herbe) et rang (vigne)\n\tPeffh_Ruiss<-(Peffh-Ruissh)\n\tPeffv_Ruiss<-(Peffv-Ruissv)\n\n\t# Part de l'ETP enherbement\n\tETPh<-(meteo$ETP*param$p)\n\n\t#\n\t# Calcul de Temp base 0 ? partir de la lev?e de l'enherbement\n\tTb0<-rep(0,dim(meteo)[1]) \n\tfor (a in 1:an)\n\t\tfor (i in Llevee[a]:(jdeb[a+1]-1))\n\t\t\tifelse(meteo$Temp[i]>0,Tb0[i]<-meteo$Temp[i],Tb0[i]<-0)\n\n\n\t# Calcul du kvigne estim?\n\tkv<-rep(0,dim(meteo)[1]) #vecteur vide\n\tfor (a in 1:an)\n\t\tfor (i in Ldbr[a]:LarretTr[a])\n\t\t{\n\t\t\tkv[i]<-param$kmax[a]\n\t\t\tif (somTb10[i](LarretTr[a]-15) & i<(length(ll)-15)) # \n\t\t\t\tkv[i]<-(param$kmax[a]-param$kmax[a]*min(1,1-(LarretTr[a]-i)/15)) # decroissance lineaire ? partir de 15j avant l'arr?t de transpiration\n\t\t}\n\n\t#\n\t# Calcul de INN\n\tINN<-rep(0,dim(meteo)[1])\n\tINN<-INN+param$inn # ? ce stade de d?veloppement, la valeur de INN est fix? par d?faut ? 0.3\n\t\n\t#\n\t# Calcul de Es0\n\tEs0<-(meteo$ETP*(1-kv)*(1-param$p))\n\t#\n\t# CALCUL du groupe evaporation du sol\n\tb_evap\t<-(0.5*param$b1_evap*param$b2_evap)\n\t\n\tBHSn\t<-rep(0,dim(meteo)[1])\n\tESn1\t<-rep(0,dim(meteo)[1])\n\tSES0\t<-rep(0,dim(meteo)[1])\n\tESn2\t<-rep(0,dim(meteo)[1])\n\tESn\t\t<-rep(0,dim(meteo)[1])\n\t\n\tBHSn[1]\t<-(param$U*(1-param$p))\n\tESn1[1]\t<-Es0[1]\n\tESn[1]\t<-(ESn1[1]+ESn2[1])\n\tj<-1\n\trepeat\n\t{\n\t\tj<-(j+1)\n\t\tif (j>dim(meteo)[1]) break()\n\t\tESn1[j]<-(min(Es0[j],BHSn[j-1]))\n\t\tif (ESn1[j]dim(meteo)[1]) break()\n\n\t\t# Calcul de la s?nescence folaire de l'herbe\n\t\tcrherbe[j]\t<-(param$herblairate*1.71*0.001*min(18,Tb0[j])^2*KLAI[j-1]*INN[j-1])\n\t\tSTb0[j]\t\t<-STb0[j-1]+Tb0[j]\n\t\tif (STb0[j-1]>param$LLSmin | LAI[j-1]==param$LAIres) LAIsen[j]<-LAI[j-1] else LAIsen[j]<-LAIsen[j-1]\n\t\tif (STb0[j-1]>param$LLSmin) STb0[j]<-0\n\t\tseneherbe[j]<-(LAIsen[j]*max(0,Tb0[j]/param$LLSmin))\n\t\t\n\t\t#gestion de la dynamique du LAI incluant les eventuelles tontes\n\t\tif (LAI[j-1]>param$LAItonte) \n\t\t\tLAI[j]<-param$LAIres \n\t\telse \n\t\t\tLAI[j]<-max(0,LAI[j-1]+crherbe[j]-seneherbe[j])\n\t\tif (j==Ltonte[tont] & param$Tonte==\"O\") \n\t\t{\n\t\t\tLAI[j]<-param$LAIres\n\t\t\tSTb0[j]<-0\n\t\t\ttont<-(tont+1)\n\t\t}\n\t\tif (tont>sum(param$nbtonte)) \n\t\t\ttont<-sum(param$nbtonte)\n\n\t\tKh[j]\t<-(0.95*(1-exp(-0.6*LAI[j])))\n\t\tETRh[j]\t<-(ETPh[j]*(1-kv[j])*Kh[j]*Ktransp[j-1])\n\t\tShv[j]\t<-min(1,FTSWtot[j-1]/param$FTSWvregulTR) # Effet Stress hydrique sur vigne\n\t\tif (j0\n g=rollapply(fc,10,sum)\n \n ###\n FD_RealSeries=g\n FD_CensusSeries=rollapply(f_tree_tsyear(this_tree,this_fire)$scars>0,10,sum)\n ###\n \n \n # Shuffle this_tree so the ordered trees have a random subset within them, or else all the dead ones will be at the bottom\n this_tree$shuffler=sample(dim(this_tree)[1])\n \n ## Calculate a summary of the number of scars per tree, for filtering\n this_tree=group_by(this_tree,ID)\n \n scar_count=summarise(this_tree,count=length(YBP),MFI=f_tree_MFIhelper(YBP),shuffler=first(shuffler))\n scar_count=arrange(scar_count,desc(count),shuffler)\n scar_count=as.data.frame(scar_count)\n scar_count=subset(scar_count,is.finite(scar_count$MFI))\n \n this_tree=as.data.frame(this_tree)\n \n ## Targeted subsets\n FD_T_500 = rollapply(f_tree_tsyear(subset(this_tree,this_tree$ID %in% scar_count[1:500,]$ID),this_fire)$scars>0,10,sum)\n FD_T_250 = rollapply(f_tree_tsyear(subset(this_tree,this_tree$ID %in% scar_count[1:250,]$ID),this_fire)$scars>0,10,sum)\n FD_T_100 = rollapply(f_tree_tsyear(subset(this_tree,this_tree$ID %in% scar_count[1:100,]$ID),this_fire)$scars>0,10,sum)\n FD_T_50 = rollapply(f_tree_tsyear(subset(this_tree,this_tree$ID %in% scar_count[1:50,]$ID),this_fire)$scars>0,10,sum)\n FD_T_25 = rollapply(f_tree_tsyear(subset(this_tree,this_tree$ID %in% scar_count[1:25,]$ID),this_fire)$scars>0,10,sum)\n FD_T_10 = rollapply(f_tree_tsyear(subset(this_tree,this_tree$ID %in% scar_count[1:10,]$ID),this_fire)$scars>0,10,sum)\n \n ## Random subsets\n FD_R_500 = rollapply(f_tree_tsyear(this_tree[sample(dim(this_tree)[1],500),],this_fire)$scars>0,10,sum)\n FD_R_250 = rollapply(f_tree_tsyear(this_tree[sample(dim(this_tree)[1],250),],this_fire)$scars>0,10,sum)\n FD_R_100 = rollapply(f_tree_tsyear(this_tree[sample(dim(this_tree)[1],100),],this_fire)$scars>0,10,sum)\n FD_R_50 = rollapply(f_tree_tsyear(this_tree[sample(dim(this_tree)[1],50),],this_fire)$scars>0,10,sum)\n FD_R_25 = rollapply(f_tree_tsyear(this_tree[sample(dim(this_tree)[1],25),],this_fire)$scars>0,10,sum)\n FD_R_10 = rollapply(f_tree_tsyear(this_tree[sample(dim(this_tree)[1],10),],this_fire)$scars>0,10,sum)\n \n ################### Now area burnt\n \n field_size=dim(this_fire)[1] * dim(this_fire)[2]\n fc=apply(this_fire,MARGIN=3,FUN=sum)\n g=fc/field_size\n \n ###\n AB_RealSeries=g\n AB_CensusSeries=f_tree_tsyear(this_tree,this_fire)$perc\n ###\n \n AB_T_500 = f_tree_tsyear(subset(this_tree,this_tree$ID %in% scar_count[1:500,]$ID),this_fire)$perc\n AB_T_250 = f_tree_tsyear(subset(this_tree,this_tree$ID %in% scar_count[1:250,]$ID),this_fire)$perc\n AB_T_100 = f_tree_tsyear(subset(this_tree,this_tree$ID %in% scar_count[1:100,]$ID),this_fire)$perc\n AB_T_50 = f_tree_tsyear(subset(this_tree,this_tree$ID %in% scar_count[1:50,]$ID),this_fire)$perc\n AB_T_25 = f_tree_tsyear(subset(this_tree,this_tree$ID %in% scar_count[1:25,]$ID),this_fire)$perc\n AB_T_10 = f_tree_tsyear(subset(this_tree,this_tree$ID %in% scar_count[1:10,]$ID),this_fire)$perc\n \n ## Random subsets\n AB_R_500 = f_tree_tsyear(this_tree[sample(dim(this_tree)[1],500),],this_fire)$perc\n AB_R_250 = f_tree_tsyear(this_tree[sample(dim(this_tree)[1],250),],this_fire)$perc\n AB_R_100 = f_tree_tsyear(this_tree[sample(dim(this_tree)[1],100),],this_fire)$perc\n AB_R_50 = f_tree_tsyear(this_tree[sample(dim(this_tree)[1],50),],this_fire)$perc\n AB_R_25 = f_tree_tsyear(this_tree[sample(dim(this_tree)[1],25),],this_fire)$perc\n AB_R_10 = f_tree_tsyear(this_tree[sample(dim(this_tree)[1],10),],this_fire)$perc\n \n ## bind it\n \n t_FD=data.frame(ID=rep(idx,length(FD_RealSeries)),year=seq_along(FD_RealSeries),SPLIT_YEAR=rep(data_frame$SPLIT_YEAR[idx],length(FD_RealSeries)),FD_RealSeries,FD_CensusSeries,FD_T_500,FD_T_250,FD_T_100,FD_T_50,FD_T_25,FD_T_10,FD_R_500,FD_R_250,FD_R_100,FD_R_50,FD_R_25,FD_R_10)\n t_AB=data.frame(ID=rep(idx,length(AB_RealSeries)),year=seq_along(AB_RealSeries),SPLIT_YEAR=rep(data_frame$SPLIT_YEAR[idx],length(AB_RealSeries)),AB_RealSeries,AB_CensusSeries,AB_T_500,AB_T_250,AB_T_100,AB_T_50,AB_T_25,AB_T_10,AB_R_500,AB_R_250,AB_R_100,AB_R_50,AB_R_25,AB_R_10)\n \n FD_frame=rbind(FD_frame,t_FD)\n AB_frame=rbind(AB_frame,t_AB)\n }\n \n FD_frame=subset(FD_frame,ID>0)\n AB_frame=subset(AB_frame,ID>0)\n \n write.csv(FD_frame,paste0(wd,run,\"/FD_timeseries_\",count_dead,\".csv\"))\n write.csv(AB_frame,paste0(wd,run,\"/AB_timeseries_\",count_dead,\".csv\"))\n}\n\n\n\n\n# Do the narrow/wide \ntd_vec=c(\"e2_range_narrow\",\"e2_range_wide\")\nforeach(i=iter(td_vec),.packages=c(\"dplyr\",\"zoo\")) %dopar% calc_stats(working_dir,i)\n\n#for(i in td_vec){\n# print(i)\n# calc_stats(working_dir,i)\n#}\n\n", "meta": {"hexsha": "a46e0a98e643c49a8f501af7f8b41b13f4f42e1d", "size": 5981, "ext": "r", "lang": "R", "max_stars_repo_path": "calc_moving_stats.r", "max_stars_repo_name": "ozjimbob/FireScar", "max_stars_repo_head_hexsha": "da4b1a8c5ef13427e01c057e80c7c09cb3d6882f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-01-03T05:25:44.000Z", "max_stars_repo_stars_event_max_datetime": "2020-01-03T05:47:55.000Z", "max_issues_repo_path": "calc_moving_stats.r", "max_issues_repo_name": "ozjimbob/FireScar", "max_issues_repo_head_hexsha": "da4b1a8c5ef13427e01c057e80c7c09cb3d6882f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "calc_moving_stats.r", "max_forks_repo_name": "ozjimbob/FireScar", "max_forks_repo_head_hexsha": "da4b1a8c5ef13427e01c057e80c7c09cb3d6882f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.3106060606, "max_line_length": 281, "alphanum_fraction": 0.7318174218, "num_tokens": 2044, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7431680086124812, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.388989258386258}} {"text": "# James Rekow\r\n\r\naggBaseCaseDOCCreatorSameCohort = function(M = 40, N = 20, iStrength = 1, univ = 1, intIx = NULL,\r\n sigmaMax = 0.1, thresholdMult = 10 ^ (-2), maxSteps = 10 ^ 4,\r\n tStep = 10 ^ (-2), intTime = 1, interSmplMult = 0.01,\r\n lambda = NULL, numDOC = 10){\r\n \r\n # ARGS: numDOC - number of DOCs from which the aggregate points should be assembled\r\n #\r\n # RETURNS: aggDOCDF - an aggregate DOC comprised of points from numDOC number of cohorts\r\n # with streamlined interaction steps (e.g. there is a completely connected\r\n # subset of interacting samples and a constellation of non-interacting samples\r\n # that don't interact at all). Each point also has a replicate ID associated with\r\n # it that tracks which replicate it was from, and the number of interacting\r\n # samples (0, 1, or 2) corresponding to it (e.g. if two interacting samples\r\n # are compared to create a DOC point this number would be 2)\r\n \r\n source(\"DOCProcedure.r\")\r\n source(\"cohortCreator.r\")\r\n source(\"eulerIntegrate.r\")\r\n source(\"intraCohortInteraction_optimizedBaseCase.r\")\r\n \r\n # set default value of lambda\r\n if(is.null(lambda)){\r\n \r\n lambda = -0.5 * M * log(0.5)\r\n \r\n } # end if\r\n \r\n # let half of the samples be interacting samples\r\n numI = floor(M / 2)\r\n \r\n # if intIx is not specified, randomly select half of the samples to interact\r\n if(is.null(intIx)){\r\n \r\n numI = floor(M / 2)\r\n intIx = sample(1:M, numI)\r\n \r\n } # end if\r\n \r\n # create a numerical vector with 1's in positions with the indices of interacting elements\r\n # and 0's elsewhere\r\n intSmpls = rep(0, M)\r\n intSmpls[intIx] = 1\r\n \r\n # create a matrix whose columns are each unique pair of sample indices\r\n pairMat = combn(M, 2)\r\n \r\n # function to count the number of interacting samples in a vector of sample indices\r\n intCounter = function(ixVec) sum(intSmpls[ixVec])\r\n \r\n # numerical vector of the number of samples in each sample pair that were interacting samples\r\n intCount = apply(pairMat, 2, intCounter)\r\n \r\n # used to determine if the system is near equilibrium\r\n threshold = {thresholdMult * tStep} ^ 2\r\n \r\n # define integrator function to apply eulerIntegrate with desired parameter vals\r\n integrator = function(smpl){\r\n return(eulerIntegrate(smpl, threshold = threshold, maxSteps = maxSteps, tStep = tStep))\r\n } # end integrator function\r\n \r\n # create cohort\r\n chrt = cohortCreator(M = M, N = N, iStrength = iStrength, univ = univ, sigmaMax = sigmaMax)\r\n \r\n # integrate samples in the cohort and store the abundance vectors in a list\r\n abdList = lapply(chrt, integrator)\r\n \r\n produceDOCDF = function(n){\r\n \r\n # simulate intra-cohort interaction if lambda > 0\r\n if(lambda > 0){\r\n \r\n # update the abundances of each sample in the cohort\r\n for(i in 1:M){\r\n chrt[[i]][[1]] = abdList[[i]]\r\n } # end for\r\n \r\n # simulate intra-cohort interactions\r\n intAbdList = intraCohortInteraction_optimizedBaseCase(intIx = intIx, chrt = chrt, M = M, N = N,\r\n lambda = lambda, threshold = threshold,\r\n maxSteps = maxSteps, tStep = tStep,\r\n intTime = intTime,\r\n interSmplMult = interSmplMult)\r\n \r\n } # end if\r\n \r\n # create DOC\r\n doc = DOCProcedure(intAbdList)\r\n \r\n # store data in a data frame\r\n DOCDF = data.frame(replicateID = n, intCount = intCount, over = doc$x, diss = doc$y)\r\n \r\n return(DOCDF)\r\n \r\n } # end produceDOC function\r\n \r\n # create a list of replicate data frames\r\n DOCDFList = lapply(as.list(1:numDOC), produceDOCDF)\r\n \r\n # aggregate data from the replicates\r\n aggDOCDF = Reduce(rbind, DOCDFList)\r\n \r\n # make the intCount variable a factor (mostly for plotting purposes)\r\n aggDOCDF$intCount = as.factor(aggDOCDF$intCount)\r\n \r\n return(aggDOCDF)\r\n \r\n} # end aggBaseCaseDOCCreatorSameCohort function\r\n", "meta": {"hexsha": "4d56228d0ae07e39596c744b0903130ae2ae43c1", "size": 4345, "ext": "r", "lang": "R", "max_stars_repo_path": "aggBaseCaseDOCCreatorSameCohort.r", "max_stars_repo_name": "JamesRekow/Ben_Dalziel_Contract_Work_Files_9_29_2017", "max_stars_repo_head_hexsha": "b7a3b167650471d0ae5356d1d2a036bde771778c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "aggBaseCaseDOCCreatorSameCohort.r", "max_issues_repo_name": "JamesRekow/Ben_Dalziel_Contract_Work_Files_9_29_2017", "max_issues_repo_head_hexsha": "b7a3b167650471d0ae5356d1d2a036bde771778c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "aggBaseCaseDOCCreatorSameCohort.r", "max_forks_repo_name": "JamesRekow/Ben_Dalziel_Contract_Work_Files_9_29_2017", "max_forks_repo_head_hexsha": "b7a3b167650471d0ae5356d1d2a036bde771778c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 39.5, "max_line_length": 105, "alphanum_fraction": 0.5882623705, "num_tokens": 1095, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.72487026428967, "lm_q2_score": 0.5350984286266116, "lm_q1q2_score": 0.3878769393795591}} {"text": "# Script for phylogeny dating\n\n# 1. Ne estimation ################################################################################################\ndata <- read.csv(\"mutation_rate.txt\", sep =\" \", header=FALSE)\n\naverage=mean(data[,2])\naverage\nne= 0.00247 /(4*mu)\n\n# 2. Dating phylogeny ################################################################################################\nlibrary(RColorBrewer)\nlibrary(dplyr)\nlibrary(ape)\nlibrary(phytools)\n\ngt_m = 11\n# Distances\nd_Pongo_abelii <- 0.0162551430672998\nd_Homo_sapiens <- 0.00577676246248343\nd_Pan_troglodytes <- 0.00612226407385174\nd_h_c <- 0.00928793113723326\nd_ape <- 0.0111854267754341\nd_Macaca_mulatta <-0.00260875810745442\nd_Macaca_f <- 0.0022282726931979\nd_macaca_macaca <-0.00464525362885664\nd_baboon <- 0.00686281100087727\nd_maca_bab <- 0.00399650084545229\nd_Chlorocebus_sabaeus <- 0.0111626595169656\nd_m_g <- 0.0246717581129659\n\n# Using only the new estimated on the branches in question\nmu_rhesus= ((4.8399 + 1.8364 *12+ 4.6497+ 0.3042 *10)*(1-0.10887096774193548)/(2*2351302179*(1-0.04020232294960846)))\nmu_m = (mu_rhesus/11)*1000000\nmu_rhesus_min= ((25.158457+5.065827)*(1-0.10887096774193548)/(2*2351302179*(1-0.04020232294960846)))\nCI_min= (mu_rhesus_min/11)*1000000\nmu_rhesus_max= ((28.59583+10.317069)*(1-0.10887096774193548)/(2*2351302179*(1-0.04020232294960846)))\nCI_max= (mu_rhesus_max/11)*1000000\n\n# Macaca-macaca\nt_m = (d_Macaca_mulatta)/(mu_m)\nt_m_min = (d_Macaca_mulatta)/(CI_min)\nt_m_max = (d_Macaca_mulatta)/(CI_max)\n# Macaca-baboon\nt_m_b = (d_Macaca_mulatta+d_macaca_macaca)/(mu_m)\nt_m_b_min = (d_Macaca_mulatta+d_macaca_macaca)/(CI_min)\nt_m_b_max = (d_Macaca_mulatta+d_macaca_macaca)/(CI_max)\n# Macaca-green\nt_m_g = (d_Macaca_mulatta+d_macaca_macaca+d_maca_bab)/(mu_m)\nt_m_g_min = (d_Macaca_mulatta+d_macaca_macaca+d_maca_bab)/(CI_min)\nt_m_g_max = (d_Macaca_mulatta+d_macaca_macaca+d_maca_bab)/(CI_max)\n\n# Macaca with great apes\nt_m_a = (d_Macaca_mulatta+d_macaca_macaca+d_maca_bab+d_m_g)/(mu_m)\nt_m_a_min = (d_Macaca_mulatta+d_macaca_macaca+d_maca_bab+d_m_g)/(CI_min)\nt_m_a_max = (d_Macaca_mulatta+d_macaca_macaca+d_maca_bab+d_m_g)/(CI_max)\n\n##\n# Babon rate:\nmu_b = 0.549e-9*1000000\nd_baboon/mu_b\n# Green rate:\nmu_g = 1.11e-9*1000000\nd_Chlorocebus_sabaeus/mu_g\n# Homo:\nmu_h= 0.43e-9*1000000\n(d_ape+d_h_c+d_Homo_sapiens)/mu_h\n# Chimp\nmu_c= 0.64e-9*1000000\n(d_ape+d_h_c+d_Pan_troglodytes)/mu_c\n\n# Model\nmu_nwm=2.7e-9*1000000\n(d_Macaca_mulatta+d_macaca_macaca)/mu_m\n(d_maca_bab+d_m_g)/mu_g\nd_maca_bab/mu_g\nd_m_g/mu_nwm\n\n####\ntree_t_new_reg<-read.tree(\"tree_timed_rhesus_estimate_last_reg.nwk\")\ntree_t_topo<-read.tree(\"tree_timed_rhesus_estimate_topo_reg.nwk\")\ntree_t_sp<-read.tree(\"tree_timed_rhesus_estimate_sp_reg.nwk\")\n\nCI= rbind(c(t_m_a_min,t_m_a_max),\n c(t_m_g_min,t_m_g_max),\n c(t_m_b_min,t_m_b_max),\n c(t_m_min,t_m_max))\n\n# speciation\nminus_m=(2*79874*11)/1000000\nminus_cat=(2*355000*11)/1000000\n\nsp_t_m = t_m -minus_m\nsp_t_m_a =t_m_a-minus_cat\n\n#\npng(\"phylo_diff_sp_n_reg_last.png\", width = 1200, height = 750)\npar(xaxt=\"n\",yaxt=\"n\",mar=c(5.1,6.1,2.1,2), mgp=c(5, 1.5, 0))\nplotTree.errorbars(tree_t_new_reg, CI, fsize=3, ftype=\"off\", lwd=10, bar.width=0, cex=2.5, xlab=\"\",ylab=\"\", at=seq(0,45,by=5))\n#\npolygon(c(sp_t_m,sp_t_m,t_m,t_m), c(1,2,2,1), col = \"gray80\", border=\"gray80\")\npolygon(c(sp_t_m_a,sp_t_m_a,t_m_a,t_m_a), c(3.13,5,5,3.13), col = \"gray80\", border=\"gray80\")\n#\naxis(1, at=seq(0,55,by=5), cex.axis=2)\n#\nabline(v=60, lty=2, lwd=4, col=\"gray65\")\nabline(v=55, lty=2, lwd=4, col=\"gray65\")\nabline(v=50, lty=2, lwd=4, col=\"gray65\")\nabline(v=45, lty=2, lwd=4, col=\"gray65\")\nabline(v=40, lty=2, lwd=4, col=\"gray65\")\nabline(v=35, lty=2, lwd=4, col=\"gray65\")\nabline(v=30, lty=2, lwd=4, col=\"gray65\")\nabline(v=25, lty=2, lwd=4, col=\"gray65\")\nabline(v=20, lty=2, lwd=4, col=\"gray65\")\nabline(v=15, lty=2, lwd=4, col=\"gray65\")\nabline(v=10, lty=2, lwd=4, col=\"gray65\")\nabline(v=5, lty=2, lwd=4, col=\"gray65\")\nabline(v=0, lty=2, lwd=4, col=\"gray65\")\n#\nlines(c(50.09,50.09),c(5,3.15), lwd=10, col=\"gray52\")\nlines(c(2.45,2.45),c(1,2), lwd=10, col=\"gray52\")\npoints(c(50.09),c(4.06), lwd=15,pch=20, col=\"navy\")\npoints(c(2.45),c(1.5), lwd=15,pch=20, col=\"navy\")\npar(new=TRUE)\npar(xaxt=\"n\",yaxt=\"n\",mar=c(5.1,5.1,2.1,2), mgp=c(5, 1.5, 0))\n## ftype= \"reg\" \"i\" \"b\"\nplotTree.errorbars(tree_t_new_reg, CI, fsize=3, ftype=\"i\", lwd=10, bar.width=20, cex=2.5, xlab=\"\",ylab=\"\", at=seq(0,45,by=5),bar.col=\"darkgreen\")\n##plotTree.errorbars(tree_t_sp, CI, fsize=3, ftype=\"i\", lwd=10, bar.width=20, cex=2.5, xlab=\"\",ylab=\"\", at=seq(0,45,by=5),bar.col=\"darkblue\")\n##CI_s=rbind(cbind(50.09,50.09),c(18.13,18.13),c(11.69,11.69),c(2.45,2.45))\n##plotTree.errorbars(tree_t_sp, CI_s, fsize=3, ftype=\"i\", lwd=10,bar.width=20, cex=2.5, xlab=\"\",ylab=\"\", at=seq(0,45,by=5),bar.col=\"darkblue\")\n#\npar(xaxt=\"s\",yaxt=\"s\",font.lab=4)\naxis(1, at=seq(0,60,by=5), cex.axis=2)\n#\ntext(c(10,19.5,30,58.2), c(1.35,2.1,2.98,3.915),labels = c(\"Macaca\", \"Papionini\", \"Cercopithecidae\", \"Catarrhini\"), font=1, cex=2.3)\ntext(c(10,58.2), c(1.2,3.765),labels = c(expression(\"(N\"[e]*\" = 79,874)\"), expression(\"(N\"[e]*\" = 355,000)\")), font=2, cex=1.6)\ntext(c(-0.1,-2), c(1.62,1.48),labels = c(expression(\"T\"[d]*\"=4.20\"),expression(\"T\"[s]*\"=2.45\")), col=c(\"darkgreen\",\"navy\"), font=2, cex=1.8)\ntext(c(6.5), c(2.4),labels = c(expression(\"T\"[d]*\"=11.69\")), col=c(\"darkgreen\"), font=2, cex=1.8)\ntext(c(13), c(3.28),labels = c(expression(\"T\"[d]*\"=18.13\")), col=c(\"darkgreen\"), font=2, cex=1.8)\ntext(c(52.5,45.5), c(4.17,3.9),labels = c(expression(\"T\"[d]*\"=57.90\"),expression(\"T\"[s]*\"=50.09\")), col=c(\"darkgreen\",\"navy\"), font=2, cex=1.8)\n#\n# add fossils:\npoints(c(22,22,33.5), c(3.12,5,4.05), pch=4, lwd=5, col=\"red\")\ntext(c(28,22,33.5), c(3.22,5.1,4.15),labels = c(\"Victoriapithecus\", \"Proconsul\", \"Aegyptopithecus\"), , col=c(\"red\"), font=3, cex=1.8)\ndev.off()\n\n# 3. compare estimate with literature ######################################################################################################################\ndiv_me <- c(4.20,11.69,18.13,57.90)\ndiv_lit_nucl <- c(3.53, 8.13, 11.5, 31.6)\ndiv_lit_mito <- c(3.44, 12.17, 14.09, 32.12)\n\npng(\"estimation_dif_met.png\", width = 1300, height = 850)\npar(mar=c(9,15,4,2), mgp=c(3, 3, 0))\nplot(div_lit_mito, div_me, type='o', pch=19, lwd=4, xlim=c(0,60), ylim=c(0,60), xlab=\"\", ylab=\"\",\n cex=3, cex.lab=2.5, cex.axis=2.5, xaxt=\"n\", yaxt=\"n\", lty=1)\nlines(div_lit_nucl, div_me, type='o', pch=19, lwd=4, xlab=\"\", ylab=\"\", cex=3, cex.lab=2.5, cex.axis=2.5, xaxt=\"n\", yaxt=\"n\", lty=1, col=\"gray60\")\nabline(0,1, lwd=2, lty=1, col=\"black\")\npoints(div_lit_mito, div_me, pch=21, lwd=3, cex=4, cex.lab=2.5, cex.axis=2.5, col=1, bg=c(\"aquamarine4\", \"firebrick1\", \"dodgerblue4\", \"darkgoldenrod2\"))\npoints(div_lit_nucl, div_me, pch=21, lwd=3, cex=4, cex.lab=2.5, cex.axis=2.5, col=\"gray60\", bg=c(\"aquamarine4\", \"firebrick1\", \"dodgerblue4\", \"darkgoldenrod2\"))\ntext(c(7.5, 18, 6.5, 38),c(1, 11.5, 26.5, 56), labels=c(\"Macaca\", \"Papionini\", \"Cercopithecidae\",\"Catarrhini\"),\n font=c(4,2,2,2), cex=3, col=c(\"aquamarine4\", \"firebrick1\", \"dodgerblue4\", \"darkgoldenrod2\"))\naxis(1, cex.axis=4)\naxis(2, cex.axis=4, las=2)\nmtext(\"Time (in Mya) from the molecular clock\", 1, line=7, cex=4)\nmtext(\"Time (in Mya) from our estimate\", 2, line=9, cex=4)\nlegend(\"topleft\", c(expression(\"T\"[divergence]*\" compare to mitochondrial data\"), expression(\"T\"[divergence]*\" compare to nuclear data\")), col=c(\"black\", \"gray60\"), lty=c(1,1), lwd=3, cex=2, bty = \"n\")\ndev.off()\n\n\n", "meta": {"hexsha": "3b5b911efc683a60ffcf45646231eac6f823dda7", "size": 7456, "ext": "r", "lang": "R", "max_stars_repo_path": "7_analysis/phylogeny.r", "max_stars_repo_name": "lucieabergeron/germline_mutation_rate", "max_stars_repo_head_hexsha": "c15e92e7ded4a353f262f384ecba45c508cdaf43", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "7_analysis/phylogeny.r", "max_issues_repo_name": "lucieabergeron/germline_mutation_rate", "max_issues_repo_head_hexsha": "c15e92e7ded4a353f262f384ecba45c508cdaf43", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "7_analysis/phylogeny.r", "max_forks_repo_name": "lucieabergeron/germline_mutation_rate", "max_forks_repo_head_hexsha": "c15e92e7ded4a353f262f384ecba45c508cdaf43", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.1183431953, "max_line_length": 201, "alphanum_fraction": 0.65625, "num_tokens": 3264, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.833324607730178, "lm_q2_score": 0.46490157137338844, "lm_q1q2_score": 0.3874139195978723}} {"text": "library (gsubfn) \nsetwd('/src/r')\nsource('Melting.r')\nsource('Refreezing.r')\nsource('Snowaccumulation.r')\nsource('Snowdensity.r')\nsource('Snowdepth.r')\nsource('Snowdepthtrans.r')\nsource('Snowdry.r')\nsource('Snowmelt.r')\nsource('Snowwet.r')\nsource('Tavg.r')\nsource('Tempmax.r')\nsource('Tempmin.r')\nsource('Preciprec.r')\n\nmodel_snow <- function (jul = 0,\n Tmf = 0.0,\n SWrf = 0.0,\n tsmax = 0.0,\n precip = 0.0,\n DKmax = 0.0,\n trmax = 0.0,\n tmax = 0.0,\n ps_t1 = 0.0,\n Sdepth_t1 = 0.0,\n Sdry_t1 = 0.0,\n Swet_t1 = 0.0,\n rho = 100.0,\n Kmin = 0.0,\n Pns = 100.0,\n tmaxseuil = 0.0,\n tminseuil = 0.0,\n tmin = 0.0,\n prof = 0.0,\n E = 0.0){\n #'- Name: Snow -Version: 1.0, -Time step: 1\n #'- Description:\n #' * Title: Snow model\n #' * Author: STICS\n #' * Reference: Snow paper\n #' * Institution: STICS\n #' * Abstract: Snow\n #'- inputs:\n #' * name: jul\n #' ** description : current day of year for the calculation\n #' ** inputtype : variable\n #' ** variablecategory : auxiliary\n #' ** datatype : INT\n #' ** default : 0\n #' ** min : 0\n #' ** max : 366\n #' ** unit : d\n #' ** uri : \n #' * name: Tmf\n #' ** description : threshold temperature for snow melting \n #' ** inputtype : parameter\n #' ** parametercategory : constant\n #' ** datatype : DOUBLE\n #' ** default : 0.0\n #' ** min : 0.0\n #' ** max : 5000.0\n #' ** unit : degC\n #' ** uri : \n #' * name: SWrf\n #' ** description : degree-day temperature index for refreezing\n #' ** inputtype : parameter\n #' ** parametercategory : constant\n #' ** datatype : DOUBLE\n #' ** default : 0.0\n #' ** min : 0.0\n #' ** max : 5000.0\n #' ** unit : mmW/degC/d\n #' ** uri : \n #' * name: tsmax\n #' ** description : maximum daily air temperature (tmax) below which all precipitation is assumed to be snow\n #' ** inputtype : parameter\n #' ** parametercategory : constant\n #' ** datatype : DOUBLE\n #' ** default : 0.0\n #' ** min : 0.0\n #' ** max : 1000\n #' ** unit : degC\n #' ** uri : \n #' * name: precip\n #' ** description : current precipitation\n #' ** inputtype : variable\n #' ** variablecategory : auxiliary\n #' ** datatype : DOUBLE\n #' ** default : 0.0\n #' ** min : 0.0\n #' ** max : 5000.0\n #' ** unit : mmW\n #' ** uri : \n #' * name: DKmax\n #' ** description : difference between the maximum and the minimum melting rates\n #' ** inputtype : parameter\n #' ** parametercategory : constant\n #' ** datatype : DOUBLE\n #' ** default : 0.0\n #' ** min : 0.0\n #' ** max : 5000.0\n #' ** unit : mmW/degC/d\n #' ** uri : \n #' * name: trmax\n #' ** description : tmax above which all precipitation is assumed to be rain\n #' ** inputtype : parameter\n #' ** parametercategory : constant\n #' ** datatype : DOUBLE\n #' ** default : 0.0\n #' ** min : 0.0\n #' ** max : 5000.0\n #' ** unit : degC\n #' ** uri : \n #' * name: tmax\n #' ** description : current maximum air temperature\n #' ** inputtype : variable\n #' ** variablecategory : auxiliary\n #' ** datatype : DOUBLE\n #' ** default : 0.0\n #' ** min : 0.0\n #' ** max : 5000.0\n #' ** unit : degC\n #' ** uri : \n #' * name: ps_t1\n #' ** description : density of snow cover in previous day\n #' ** inputtype : variable\n #' ** variablecategory : state\n #' ** datatype : DOUBLE\n #' ** default : 0.0\n #' ** min : 0.0\n #' ** max : 100.0\n #' ** unit : kg/m**3\n #' ** uri : \n #' * name: Sdepth_t1\n #' ** description : snow cover depth Calculation in previous day\n #' ** inputtype : variable\n #' ** variablecategory : state\n #' ** datatype : DOUBLE\n #' ** default : 0.0\n #' ** min : 0.0\n #' ** max : 5000.0\n #' ** unit : m\n #' ** uri : \n #' * name: Sdry_t1\n #' ** description : water in solid state in the snow cover in previous day\n #' ** inputtype : variable\n #' ** variablecategory : state\n #' ** datatype : DOUBLE\n #' ** default : 0.0\n #' ** min : 0.0\n #' ** max : 500.0\n #' ** unit : mmW\n #' ** uri : \n #' * name: Swet_t1\n #' ** description : water in liquid state in the snow cover in previous day\n #' ** inputtype : variable\n #' ** variablecategory : state\n #' ** datatype : DOUBLE\n #' ** default : 0.0\n #' ** min : 0.0\n #' ** max : 100.0\n #' ** unit : mmW\n #' ** uri : \n #' * name: rho\n #' ** description : The density of the new snow fixed by the user\n #' ** inputtype : parameter\n #' ** parametercategory : constant\n #' ** datatype : DOUBLE\n #' ** default : 100\n #' ** min : \n #' ** max : \n #' ** unit : kg/m**3\n #' ** uri : \n #' * name: Kmin\n #' ** description : minimum melting rate on 21 December\n #' ** inputtype : parameter\n #' ** parametercategory : constant\n #' ** datatype : DOUBLE\n #' ** default : 0.0\n #' ** min : 0.0\n #' ** max : 5000.0\n #' ** unit : mmW/degC/d\n #' ** uri : \n #' * name: Pns\n #' ** description : density of the new snow\n #' ** inputtype : parameter\n #' ** parametercategory : constant\n #' ** datatype : DOUBLE\n #' ** default : 100.0\n #' ** min : \n #' ** max : \n #' ** unit : cm/m\n #' ** uri : \n #' * name: tmaxseuil\n #' ** description : maximum temperature when snow cover is higher than prof\n #' ** inputtype : parameter\n #' ** parametercategory : constant\n #' ** datatype : DOUBLE\n #' ** default : 0.0\n #' ** min : \n #' ** max : \n #' ** unit : degC\n #' ** uri : \n #' * name: tminseuil\n #' ** description : minimum temperature when snow cover is higher than prof\n #' ** inputtype : parameter\n #' ** parametercategory : constant\n #' ** datatype : DOUBLE\n #' ** default : 0.0\n #' ** min : 0.0\n #' ** max : 5000.0\n #' ** unit : degC\n #' ** uri : \n #' * name: tmin\n #' ** description : current minimum air temperature\n #' ** inputtype : variable\n #' ** variablecategory : auxiliary\n #' ** datatype : DOUBLE\n #' ** default : 0.0\n #' ** min : 0.0\n #' ** max : 100.0\n #' ** unit : degC\n #' ** uri : \n #' * name: prof\n #' ** description : snow cover threshold for snow insulation \n #' ** inputtype : parameter\n #' ** parametercategory : constant\n #' ** datatype : DOUBLE\n #' ** default : 0.0\n #' ** min : 0.0\n #' ** max : 1000\n #' ** unit : cm\n #' ** uri : \n #' * name: E\n #' ** description : snow compaction parameter\n #' ** inputtype : parameter\n #' ** parametercategory : constant\n #' ** datatype : DOUBLE\n #' ** default : 0.0\n #' ** min : \n #' ** max : \n #' ** unit : mm/mm/d\n #' ** uri : \n #'- outputs:\n #' * name: M\n #' ** description : snow in the process of melting\n #' ** variablecategory : rate\n #' ** datatype : DOUBLE\n #' ** min : 0.0\n #' ** max : 500.0\n #' ** unit : mmW/d\n #' ** uri : \n #' * name: tminrec\n #' ** description : recalculated minimum temperature\n #' ** variablecategory : state\n #' ** datatype : DOUBLE\n #' ** min : 0.0\n #' ** max : 500.0\n #' ** unit : degC\n #' ** uri : \n #' * name: Sdepth\n #' ** description : snow cover depth Calculation\n #' ** variablecategory : state\n #' ** datatype : DOUBLE\n #' ** min : 0.0\n #' ** max : 500.0\n #' ** unit : m\n #' ** uri : \n #' * name: Sdry\n #' ** description : water in solid state in the snow cover\n #' ** variablecategory : state\n #' ** datatype : DOUBLE\n #' ** min : 0.0\n #' ** max : 500.0\n #' ** unit : mmW\n #' ** uri : \n #' * name: Snowaccu\n #' ** description : snowfall accumulation\n #' ** variablecategory : rate\n #' ** datatype : DOUBLE\n #' ** min : 0.0\n #' ** max : 500.0\n #' ** unit : mmW/d\n #' ** uri : \n #' * name: ps\n #' ** description : density of snow cover\n #' ** variablecategory : state\n #' ** datatype : DOUBLE\n #' ** min : 0.0\n #' ** max : 500.0\n #' ** unit : kg/m**3\n #' ** uri : \n #' * name: Swet\n #' ** description : water in liquid state in the snow cover\n #' ** variablecategory : state\n #' ** datatype : DOUBLE\n #' ** min : 0.0\n #' ** max : 500.0\n #' ** unit : mmW\n #' ** uri : \n #' * name: tavg\n #' ** description : mean temperature\n #' ** variablecategory : auxiliary\n #' ** datatype : DOUBLE\n #' ** min : 0.0\n #' ** max : 500.0\n #' ** unit : degC\n #' ** uri : \n #' * name: Mrf\n #' ** description : liquid water in the snow cover in the process of refreezing\n #' ** variablecategory : rate\n #' ** datatype : DOUBLE\n #' ** min : 0.0\n #' ** max : 500.0\n #' ** unit : mmW/d\n #' ** uri : \n #' * name: tmaxrec\n #' ** description : recalculated maximum temperature\n #' ** variablecategory : state\n #' ** datatype : DOUBLE\n #' ** min : 0.0\n #' ** max : 500.0\n #' ** unit : degC\n #' ** uri : \n #' * name: preciprec\n #' ** description : recalculated precipitation\n #' ** variablecategory : state\n #' ** datatype : DOUBLE\n #' ** min : 0.0\n #' ** max : 500.0\n #' ** unit : mmW\n #' ** uri : \n #' * name: Snowmelt\n #' ** description : Snow melt\n #' ** variablecategory : state\n #' ** datatype : DOUBLE\n #' ** min : 0.0\n #' ** max : 500.0\n #' ** unit : m\n #' ** uri : \n #' * name: Sdepth_cm\n #' ** description : snow cover depth in cm\n #' ** variablecategory : state\n #' ** datatype : DOUBLE\n #' ** min : 0.0\n #' ** max : 500.0\n #' ** unit : cm\n #' ** uri : \n Snowaccu <- model_snowaccumulation(tsmax, tmax, trmax, precip)\n ps <- model_snowdensity(ps_t1, Sdepth_t1, Sdry_t1, Swet_t1)\n tavg <- model_tavg(tmin, tmax)\n M <- model_melting(jul, Tmf, DKmax, Kmin, tavg)\n Mrf <- model_refreezing(tavg, Tmf, SWrf)\n Snowmelt <- model_snowmelt(ps, M)\n Sdry <- model_snowdry(Sdry_t1, Snowaccu, Mrf, M)\n Sdepth <- model_snowdepth(Snowmelt, Sdepth_t1, Snowaccu, E, rho)\n Swet <- model_snowwet(Swet_t1, precip, Snowaccu, Mrf, M, Sdry)\n Sdepth_cm <- model_snowdepthtrans(Sdepth, Pns)\n preciprec <- model_preciprec(Sdry_t1, Sdry, Swet, Swet_t1, Sdepth_t1, Sdepth, Mrf, precip, Snowaccu, rho)\n tminrec <- model_tempmin(Sdepth_cm, prof, tmin, tminseuil, tmaxseuil)\n tmaxrec <- model_tempmax(Sdepth_cm, prof, tmax, tminseuil, tmaxseuil)\n return (list (\"M\" = M,\"tminrec\" = tminrec,\"Sdepth\" = Sdepth,\"Sdry\" = Sdry,\"Snowaccu\" = Snowaccu,\"ps\" = ps,\"Swet\" = Swet,\"tavg\" = tavg,\"Mrf\" = Mrf,\"tmaxrec\" = tmaxrec,\"preciprec\" = preciprec,\"Snowmelt\" = Snowmelt,\"Sdepth_cm\" = Sdepth_cm))\n}", "meta": {"hexsha": "623b3a35b3267264e1a7a0adcb89a9a82b83691a", "size": 17931, "ext": "r", "lang": "R", "max_stars_repo_path": "src/r/STICS_SNOW/SnowComponent.r", "max_stars_repo_name": "Crop2ML-Catalog/STICS_SNOW", "max_stars_repo_head_hexsha": "26ed2a9a30e068d72d5589b1dc64916c1b07fa09", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/r/STICS_SNOW/SnowComponent.r", "max_issues_repo_name": "Crop2ML-Catalog/STICS_SNOW", "max_issues_repo_head_hexsha": "26ed2a9a30e068d72d5589b1dc64916c1b07fa09", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/r/STICS_SNOW/SnowComponent.r", "max_forks_repo_name": "Crop2ML-Catalog/STICS_SNOW", "max_forks_repo_head_hexsha": "26ed2a9a30e068d72d5589b1dc64916c1b07fa09", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.260989011, "max_line_length": 241, "alphanum_fraction": 0.3043332776, "num_tokens": 3727, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7341195385342971, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.3871133628049177}} {"text": "#' @title\n#' Calculate the ordering of events\n#'\n#' @description\n#' For each event, we generate distributions of time of event occurance using profiles within clusters. These distributions are then pair wise compared and the results of all comparisons are represented in the graph space, where events are the graph nodes, and the directional edges represent that the source node event occurs significantly early than the target node. This graph is then utilized to generate the ordering.\n#'\n#' @param list_Tc List of matrices, where each matrix contains time course data for each 'ome'.\n#' @param list_clusters List of vectors, one for each 'ome', where the order of the 'ome' should be similar to that in list_Tc. Each of these vectors contains a cluster label (assumed to be numeric and starting from 1). The length and order of the genes in these clusters should also be similar to the order in the matricies provided in list_Tc.\n#' @param list_events List of matricies, where each matrix contains the time regions (and events for the centroid) generated by running the \\code{calcEvents} function.\n#' @param list_timeMap List of vectors, one for each 'ome', where each vector indicates the time point at which each of the 'omic' data sets were measured. For example, if a phosphoproteomics data set was measured at basal, 2minutes and 5minutes, and a proteomics data set was measured at basal, 3minutes and 5 minutes, then list_timeMap=[c(0,1,3), c(0,2,3)] (phosphoproteomics, then proteomics).\n#' @param test The test used to compare the event time distributions. The choice is between a parametric or a non-parametric test:\n#' \\describe{\n#' \t\t\\item{\\code{wilcox}}{Choosing this will result in event times being compared using the Mann Whitney U test}\n#' \t\t\\item{\\code{t-test}}{Choosing this will result in event times being compared using the Students t-test}\n#' }\n#' @param fdrSignif The significance cutoff for FDR correction, performed after pairwise comparisons of the event times.\n#' @param incrEventTh Value between 0 and 1, to define the threshold at which a phosphorylation (or increasing) event occurs. Here, a threshold of 0 corresponds to the minimum value within an interval. (Such an event is designated as 1).\n#' @param decrEventTh Value between 0 and 1, to define the threshold at which a dephosphorylation (or decreasing) event occurs. A threshold of 0 corresponds to the maximum value within an interval. (Such an event is designated as -1).\n#'\n#'\n#' @return A list with four named objects ($mat_events_withOrder, $individEventOrder, $signifs, $test) is returned, which encodes the order of the events and the clusters.\n#'\n#'\n#' @importFrom methods is\n#' @importFrom stats p.adjust wilcox.test t.test\n#' @importFrom nem transitive.reduction\n#' @importFrom igraph graph_from_adjacency_matrix adjacent_vertices V are.connected vertex_connectivity\n#'\n#' @seealso \\code{\\link[e1071]{cmeans}} for clustering time profiles, \\code{\\link{calcEvents}} for identifying events.\n#'\n#' @export\ncalculateOrder_combined <- function(list_Tc, list_clusters, list_events, list_timeMap, test=\"wilcox\", fdrSignif=0.05, incrEventTh=0.5, decrEventTh=0.5){\n\n\t# stopifnot(is(list_Tc, \"list\"), length(list_Tc) > 0, (length(clusters) == nrow(Tc)), is(mat_events, \"matrix\"), (fdrSignif >0 && fdrSignif <= 1 ), (incrEventTh >= 0 && incrEventTh <= 1), (decrEventTh >= 0 && decrEventTh <= 1))\n\n\tif (!(test == eventOrderTest$param) && !(test == eventOrderTest$nonParam)){\n\t\tstop(paste(\"Test \", test, \" not recognized.\", sep=\"\"))\n\t}\n\n\tlist_list_distributions = list()\n\tevents_combined = list_events[[1]]\n\n\tfor (i in 1:length(list_Tc)){\n\t\t# 1. split into sub matricies\n\t\tlist_splitMat = splitIntoSubMatrices(list_Tc[[i]], list_clusters[[i]])\n\n\t\t# 2. getDistOfAllEvents\n\t\tlist_distributions = getDistOfAllEvents_v3(list_events[[i]], list_splitMat, incrEventTh, decrEventTh, list_timeMap[[i]])\n\n\t\t# 3. Combine all distributions\n\t\tlist_list_distributions = c(list_list_distributions, list_distributions)\n\n\t\t# 4. Renumber and combine mat_events.\n\t\tif (i == 1){\n\t\t\tevents_combined[,Col_events$combinedDatasetNum] <- rep(i, nrow(events_combined))\n\t\t}\n\t\telse {\n\t\t\t# add dataset number\n\t\t\tlist_events[[i]][,Col_events$combinedDatasetNum] <-rep(i, nrow(list_events[[i]]))\n\n\t\t\t# adjust the cluster numbers\n\t\t\tlist_events[[i]][,Col_events$clus] <- list_events[[i]][,Col_events$clus] + max(events_combined[,Col_events$clus])\n\n\t\t\t# add to the events matrix.\n\t\t\tevents_combined <- rbind(events_combined, list_events[[i]])\n\t\t}\n\t}\n\n\n\n\t# 5. Run\n\n\tlist_pVal_stat <- list()\n\n\tif (test==eventOrderTest$nonParam){\n\t\tprint (\"Running wilcoxon test.\")\n\t\tlist_pVal_stat <- performWilcoxonSignedRankTabular(list_list_distributions)\n\n\n\t\ttitle_testType = \"(Non-parametric)\"\n\t}\n\telse {\n\t\tprint(\"Running t-test.\")\n\t\tlist_pVal_stat <- performTtestsTabular(list_list_distributions)\n\n\t\ttitle_testType = \"(Parametric)\"\n\t}\n\n\t# FDR adjustment for multiple testing.\n\tmat_pValsFDR <- matrix(stats::p.adjust(as.vector(list_pVal_stat[[1]]), method='fdr'), ncol=nrow(events_combined))\n\n\t# Convert to adjacency matrix.\n\tsignifs <- mat_pValsFDR < fdrSignif\n\tstatistic_t <- list_pVal_stat[[2]]\n\tstatistic_t[!signifs] <- NA\n\n\n\tstatistic_t[statistic_t > 0] <- NA\n\tstatistic_t[is.na(statistic_t)] <- 0\n\tstatistic_t[statistic_t < 0] <- 1\n\n\t# library(nem) # for trasitive reduction\n\t# library(igraph) # for adjacency matrix\n\treducted <- nem::transitive.reduction(statistic_t)\n\tnet = igraph::graph_from_adjacency_matrix(reducted, mode=\"directed\")\n\n\tlist_eventsOrder <- getEventsOrderInGraph(reducted, net) # computing the order of the events in the mat_events based on a bfs search.\n\tlist_eventsOrder <- adjustEvents(list_eventsOrder, signifs)\n\n\n\tmat_events_withOrder <- appendOrder(events_combined, list_eventsOrder)\n\n\tres <- list(mat_events_withOrder, list_eventsOrder, signifs, test)\n\tnames(res) <- c(\"mat_events_withOrder\", \"individEventOrder\", \"signifs\", \"test\")\n\treturn (res)\n\n\n}\n\n\n\n#' @title\n#' Visualize the order of events for a multiomics data set.\n#'\n#' @description\n#' A plot depicting the temporal order of events is generated. The order is shown using two visualizations, event maps (top) and event sparklines (bottom). The event sparkline is a summary of the event map.\n#'\n#' @param theOrder A list containing information regarding the order of events and clusters generated via the \\code{calculateOrder} function.\n#'\n#'\n#' @return A plot containing the ordered clusters by occurance of first event is generated (see description).\n#'\n#'\n#' @importFrom methods is\n#' @importFrom graphics plot segments axis rect text lines\n#' @importFrom shape Arrows\n#'\n#' @seealso \\code{\\link{calculateOrder}}\n#'\n#' @export\nvisualizeOrder_combined <- function(theOrder){\n# Visualise the ordering of events\n\n\tstopifnot(is(theOrder, \"list\"), length(theOrder) == 4)\n\n\n\tmat_events_withOrder <- theOrder$mat_events_withOrder\n\tlist_eventsOrder <- theOrder$individEventOrder\n\tsignifs <- theOrder$signifs\n\ttest <- theOrder$test\n\n\ttitle_testType = \"\"\n\t## Getting other things ready for plotting\n\n\tif (test==eventOrderTest$nonParam){\n\t\ttitle_testType = \"(Non-parametric)\"\n\t}\n\telse {\n\t\ttitle_testType = \"(Parametric)\"\n\t}\n\n\n\n\t# plotting constants\n\tsigEventsDiff_x = 0.5\n\tnonSigEventsDiff_x = 0.25\n\n\teventPtGraph_y = -1\n\tyLabelInit = -1.8\n\tyLabelSpace = 0.5\n\n\tlineDiff_y = 1\n\n\t# graphXStart = -1\n\teventStart_x = 0\n\n\tblockSpacingFmEvent_x = sigEventsDiff_x/2\n\tblockStart_x = eventStart_x - blockSpacingFmEvent_x\n\n\n\t#x_lineStart, y_lineStart, y_lineDecr, x_incr_sig, x_incr_nonSig\n\n\tyPos_eventPts = -1\n\n\t# plotting values\n\n\tlist_blocks <- getRectBlock(list_eventsOrder, signifs)\n\t# print(list_blocks)\n\n\n\tmat_eventPoints <- getTheClusLines(mat_events_withOrder, list_eventsOrder, signifs, list_blocks, eventStart_x, sigEventsDiff_x, nonSigEventsDiff_x, lineDiff_y)\n\n\n\teventEnd_x = max(as.numeric(mat_eventPoints[,cols_matFifty$col_x])) # + blockSpacingFmEvent_x\n\tblockEnd_x = eventEnd_x + blockSpacingFmEvent_x\n\n\tmat_bgRects <- getRectPoints(mat_eventPoints, list_blocks, blockStart_x, blockSpacingFmEvent_x)\n\n\n\n\t# mat_eventPoints <- adjustByBgRects(mat_bgRects, list_eventsOrder, mat_eventPoints)\n\n\n\tmat_grayLines <- getGrayLines(mat_eventPoints, signifs)\n\n\n\n\n\n\tmat_grayLines_v2 <- getGrayLines_v2(list_eventsOrder, mat_eventPoints, signifs)\n\n\n\n\n\tmat_clusConnLines <- getClusConnLines(mat_eventPoints, blockStart_x, blockEnd_x)\n\n\t# make all the down clusConnLines to opaque\n\tmat_clusConnLines <- makeDecrBarOpaque(mat_clusConnLines, TRUE)\n\n\n\n\n\n\n\n\t# a set of points to set up the graph.\n\t# print(mat_eventPoints)\n\tgraphics::plot(mat_eventPoints[,cols_matFifty$col_x], mat_eventPoints[,cols_matFifty$col_y], asp=NA, yaxt=\"n\", lwd=0.25, col=colors_orderedEvents$incr, pch=\".\", xlab=\"Temporal order\", ylab=\"Clusters\", main=paste(\"Temporal order of events in clusters\", title_testType, sep=\"\"), xlim=c(eventStart_x, eventEnd_x), ylim=c(-4, max(as.numeric(mat_eventPoints[,cols_matFifty$col_clus]))), xaxt=\"n\", bty=\"n\", cex.main = 0.8) #,\n\t# print(\"over here..\")\n\t# background gray rectangles.\n\tif (nrow(mat_bgRects) > 0){\n\t\tfor (rowNum in 1:nrow(mat_bgRects)){\n\t\t\tif (rowNum%%2 == 1){\n\t\t\t\tgraphics::rect(mat_bgRects[rowNum,1], lineDiff_y/2, mat_bgRects[rowNum,2], max(as.numeric(mat_eventPoints[,cols_matFifty$col_clus])) + (lineDiff_y/2), col = \"#ededed\", border=NA)\n\t\t\t}\n\n\t\t}\n\t}\n\n\n\tgraphics::segments(x0=as.numeric(mat_grayLines[,cols_clusPlotObjs$col_x0]), y0=as.numeric(mat_grayLines[,cols_clusPlotObjs$col_y0]), x1=as.numeric(mat_grayLines[,cols_clusPlotObjs$col_x1]), y1=as.numeric(mat_grayLines[,cols_clusPlotObjs$col_y1]), col=\"#808080\", lty=\"dotted\", lwd=0.5)\n\t# C99999\n\n\n\n\t# rect(-0.5, 0, 0.5, 17.5, col = \"yellow\", border=\"#ededed\")\n\n\t# the cluster lines\n\tgraphics::segments(x0=as.numeric(mat_clusConnLines[,cols_clusPlotObjs$col_x0]), y0=as.numeric(mat_clusConnLines[,cols_clusPlotObjs$col_y0]), x1=as.numeric(mat_clusConnLines[,cols_clusPlotObjs$col_x1]), y1=as.numeric(mat_clusConnLines[,cols_clusPlotObjs$col_y1]), col=mat_clusConnLines[,cols_clusPlotObjs$col_col], lwd=16, lend=2)\n\n\n\t# the events (arrows) within a graph\n\n\t# print(mat_events_withOrder)\n\t# print(max(mat_events_withOrder[,Col_events$combinedDatasetNum]))\n\t# print(mat_eventPoints)\n\t# return ()\n\n\n\n\t# gray lines in events points maps\n\tstraightGrayLines = mat_grayLines_v2[mat_grayLines_v2[,cols_grayLines_v2$col_isSemiCirc] == FALSE,]\n\tgraphics::segments(x0=as.numeric(straightGrayLines[,cols_grayLines_v2$col_x0]), y0=rep(yPos_eventPts, length(straightGrayLines)), x1=as.numeric(straightGrayLines[,cols_grayLines_v2$col_x1]), y1=rep(yPos_eventPts, length(straightGrayLines)), lwd=1, col=\"#A2A2A2\") #, lty=\"dotted\")\n\n\t# gray curves in events points map\n\tmat_curvePoints = mat_grayLines_v2[mat_grayLines_v2[,cols_grayLines_v2$col_isSemiCirc] == TRUE,,drop=FALSE]\n\n\tif (length(mat_curvePoints) > 0 && nrow(mat_curvePoints) > 0){\n\t\tfor (i in 1:nrow(mat_curvePoints)){\n\t\t\tlist_pts = calcCurves(mat_curvePoints[i, cols_grayLines_v2$col_x0], mat_curvePoints[i, cols_grayLines_v2$col_x1], -1)\n\t\t\tgraphics::lines(list_pts[[1]], list_pts[[2]], col=\"#A2A2A2\")\n\t\t}\n\t}\n\n\t## plotting arrows in event map & event sparkline.\n\n\t# printing up and down events (in arc events map)\n\ty_adjust = 0.15\n\n\tfor (i in 1:length(Color_multiomics)) {\n\n\t\tmat_upEvents = mat_eventPoints[mat_eventPoints[,cols_matFifty$col_dir] == Color_multiomics[[i]]$incr,]\n\n\t\tmat_downEvents = mat_eventPoints[mat_eventPoints[,cols_matFifty$col_dir] == Color_multiomics[[i]]$decr,]\n\n\t\t### Event map.\n\t\t## arrow bottoms\n\t\tshape::Arrows(x0=as.numeric(mat_upEvents[,cols_matFifty$col_x]), x1=as.numeric(mat_upEvents[,cols_matFifty$col_x]), y0=as.numeric(mat_upEvents[,cols_matFifty$col_y])-0.01-0.2, y1=as.numeric(mat_upEvents[,cols_matFifty$col_y])-0.01, arr.type=\"triangle\", arr.length=0.01, arr.width=0.01, col=Color_multiomics[[i]]$incr, lwd=2, lend=2, arr.adj=0)\n\n\t\tshape::Arrows(x0=as.numeric(mat_downEvents[,cols_matFifty$col_x]), x1=as.numeric(mat_downEvents[,cols_matFifty$col_x]), y0=as.numeric(mat_downEvents[,cols_matFifty$col_y])+0.25, y1=as.numeric(mat_downEvents[,cols_matFifty$col_y])+0.25-0.2, arr.type=\"triangle\", arr.length=0.01, arr.width=0.01, col=Color_multiomics[[i]]$decr, lwd=2, lend=2, arr.adj=0)\n\n\n\t\t## arrow bottoms\n\t\tshape::Arrows(x0=as.numeric(mat_upEvents[,cols_matFifty$col_x]), x1=as.numeric(mat_upEvents[,cols_matFifty$col_x]), y0=as.numeric(mat_upEvents[,cols_matFifty$col_y])-0.01-0.2, y1=as.numeric(mat_upEvents[,cols_matFifty$col_y])-0.01, arr.type=\"triangle\", arr.length=0.01, arr.width=0.01, col=Color_multiomics[[i]]$incr, lwd=2, lend=2, arr.adj=0)\n\n\t\tshape::Arrows(x0=as.numeric(mat_downEvents[,cols_matFifty$col_x]), x1=as.numeric(mat_downEvents[,cols_matFifty$col_x]), y0=as.numeric(mat_downEvents[,cols_matFifty$col_y])+0.25, y1=as.numeric(mat_downEvents[,cols_matFifty$col_y])+0.25-0.2, arr.type=\"triangle\", arr.length=0.01, arr.width=0.01, col=Color_multiomics[[i]]$decr, lwd=2, lend=2, arr.adj=0)\n\n\n\n\n\t\t## sharp arrow heads\n\t\tshape::Arrows(x0=as.numeric(mat_upEvents[,cols_matFifty$col_x]), x1=as.numeric(mat_upEvents[,cols_matFifty$col_x]), y0=as.numeric(mat_upEvents[,cols_matFifty$col_y])-0.01-0.2, y1=as.numeric(mat_upEvents[,cols_matFifty$col_y])-0.01, arr.type=\"triangle\", arr.length=0.13, arr.width=0.15, col=Color_multiomics[[i]]$incr, arr.adj=0, segment=FALSE)\n\n\t\tshape::Arrows(x0=as.numeric(mat_downEvents[,cols_matFifty$col_x]), x1=as.numeric(mat_downEvents[,cols_matFifty$col_x]), y0=as.numeric(mat_downEvents[,cols_matFifty$col_y])+0.25, y1=as.numeric(mat_downEvents[,cols_matFifty$col_y])+0.25-0.2, arr.type=\"triangle\", arr.length=0.13, arr.width=0.15, col=Color_multiomics[[i]]$decr, arr.adj=0, segment=FALSE)\n\n\n\n\t\t### Event sparkline\n\n\t\t## arrow bottom lines\n\t\tshape::Arrows(x0=as.numeric(mat_upEvents[,cols_matFifty$col_x]), x1=as.numeric(mat_upEvents[,cols_matFifty$col_x]), y0=rep(-1.2, nrow(mat_upEvents)), y1=rep(-1, nrow(mat_upEvents)), arr.type=\"triangle\", arr.length=0.01, arr.width=0.01, col=Color_multiomics[[i]]$incr, lwd=2, lend=2, arr.adj=0)\n\n\t\tshape::Arrows(x0=as.numeric(mat_downEvents[,cols_matFifty$col_x]), x1=as.numeric(mat_downEvents[,cols_matFifty$col_x]), y0=rep(-0.8, nrow(mat_downEvents)), y1=rep(-1, nrow(mat_downEvents)), arr.type=\"triangle\", arr.length=0.01, arr.width=0.01, col=Color_multiomics[[i]]$decr, lwd=2, lend=2, arr.adj=0)\n\n\t\t## sharp arrow heads\n\t\tshape::Arrows(x0=as.numeric(mat_upEvents[,cols_matFifty$col_x]), x1=as.numeric(mat_upEvents[,cols_matFifty$col_x]), y0=rep(-1.2, nrow(mat_upEvents)), y1=rep(-1, nrow(mat_upEvents)), arr.type=\"triangle\", arr.length=0.13, arr.width=0.15, col=Color_multiomics[[i]]$incr, arr.adj=0, segment=FALSE)\n\n\t\tshape::Arrows(x0=as.numeric(mat_downEvents[,cols_matFifty$col_x]), x1=as.numeric(mat_downEvents[,cols_matFifty$col_x]), y0=rep(-0.8, nrow(mat_downEvents)), y1=rep(-1, nrow(mat_downEvents)), arr.type=\"triangle\", arr.length=0.13, arr.width=0.15, col=Color_multiomics[[i]]$decr, arr.adj=0, segment=FALSE)\n\t}\n\n\n\tvec_labels <- getYaxisLabels(mat_eventPoints)\n\tmat_labels <- adjustLabelsByDataset(mat_events_withOrder, vec_labels)\n\n\n\t# axis labels on sides 2 and 4.\n\tMap(axis, side=2, at=seq(1,nrow(mat_labels)), col.axis=rev(mat_labels[,Col_labels$color]), labels=rev(mat_labels[,Col_labels$label]), lwd=0, las=1)\n\tgraphics::axis(2,at=seq(1,nrow(mat_labels)),labels=FALSE, col=NA)\n\n\tMap(axis, side=4, at=seq(1,nrow(mat_labels)), col.axis=rev(mat_labels[,Col_labels$color]), labels=rev(mat_labels[,Col_labels$label]), lwd=0, las=1)\n\tgraphics::axis(4,at=seq(1,nrow(mat_labels)),labels=FALSE, col=NA)\n\n\n\n\t# graphics::axis(side=4, las=1, at=seq(1,length(vec_labels)), labels=rev(vec_labels), cex=0.02, col = NA ) #, col.ticks = 1)\n\n\t# x label text.\n\tmat_xLabelsClus <- getXaxisLabels(list_eventsOrder, mat_eventPoints, signifs, list_blocks, eventStart_x, sigEventsDiff_x, nonSigEventsDiff_x, yLabelInit, yLabelSpace);\n\tprint(as.numeric(mat_xLabelsClus[,3]))\n\n\tmat_xLabels <- adjustLabelsByDataset(mat_events_withOrder, as.numeric(mat_xLabelsClus[,3]))\n\n\tmat_xLabelsClus[,3] <- mat_xLabels[,Col_labels$label]\n\n\tgraphics::text(x=as.numeric(mat_xLabelsClus[,1]), y=as.numeric(mat_xLabelsClus[,2]), labels=mat_xLabelsClus[,3], offset=0, cex=0.5, col=mat_xLabelsClus[,4])\n\n\n}\n\n\nadjustLabelsByDataset_forMat <- function(mat_events_withOrder, vec_labels){\n\tmat_labels = matrix(ncol=2, nrow=length(vec_labels))\n\n\n\tfor (i in 1:length(vec_labels)){\n\t\t# print(vec_labels[i])\n\t\tdatasetNums <- mat_events_withOrder[mat_events_withOrder[,Col_events$clus] == vec_labels[i],Col_events$combinedDatasetNum]\n\n\n\t\tdsNum = datasetNums[1]\n\n\t\tif (dsNum > 1) {\n\t\t\ttheRows <- mat_events_withOrder[,Col_events$combinedDatasetNum] == (dsNum - 1)\n\n\t\t\tmaxClusNumOfPrev <- max(mat_events_withOrder[theRows, Col_events$clus])\n\n\n\t\t\tadjustedClusNum <- vec_labels[i] - maxClusNumOfPrev\n\n\t\t\tmat_labels[i, Col_labels$label] = adjustedClusNum\n\t\t\tmat_labels[i, Col_labels$color] = Color_multiomics[[dsNum]]$incr\n\n\t\t\t# print(paste(vec_labels[i], dsNum, maxClusNumOfPrev, adjustedClusNum))\n\n\n\t\t}\n\t\telse{\n\t\t\tmat_labels[i, Col_labels$label] = vec_labels[i]\n\t\t\tmat_labels[i, Col_labels$color] = Color_multiomics[[dsNum]]$incr\n\n\t\t}\n\n\t}\n\n\treturn(mat_labels)\n}\n\nadjustLabelsByDataset <- function(mat_events_withOrder, vec_labels){\n\tmat_labels = matrix(ncol=2, nrow=length(vec_labels))\n\n\n\tfor (i in 1:length(vec_labels)){\n\t\t# print(vec_labels[i])\n\t\tdatasetNums <- mat_events_withOrder[mat_events_withOrder[,Col_events$clus] == vec_labels[i],Col_events$combinedDatasetNum]\n\n\n\t\tdsNum = datasetNums[1]\n\n\t\tif (dsNum > 1) {\n\t\t\ttheRows <- mat_events_withOrder[,Col_events$combinedDatasetNum] == (dsNum - 1)\n\n\t\t\tmaxClusNumOfPrev <- max(mat_events_withOrder[theRows, Col_events$clus])\n\n\n\t\t\tadjustedClusNum <- vec_labels[i] - maxClusNumOfPrev\n\n\t\t\tmat_labels[i, Col_labels$label] = adjustedClusNum\n\t\t\tmat_labels[i, Col_labels$color] = Color_multiomics[[dsNum]]$incr\n\n\t\t\t# print(paste(vec_labels[i], dsNum, maxClusNumOfPrev, adjustedClusNum))\n\n\n\t\t}\n\t\telse{\n\t\t\tmat_labels[i, Col_labels$label] = vec_labels[i]\n\t\t\tmat_labels[i, Col_labels$color] = Color_multiomics[[dsNum]]$incr\n\n\t\t}\n\n\t}\n\n\treturn(mat_labels)\n}\n\n\n\n\n#############################\n\ngetDistOfAllEvents_v3 <- function(mat_fiftyPoints, list_matrices, phosTh, dephosTh, timeMap){\n\tlist_distributions <- list()\n\n\tfor (eventNum in 1:nrow(mat_fiftyPoints)){\n\t\t# print(paste(\"Eventnum \", eventNum, \"--------------------------------------------------------------------\"))\n\t\tstartTp <- mat_fiftyPoints[eventNum, cols_matFifty_v2$startTp]\n\t\tendTp <- mat_fiftyPoints[eventNum, cols_matFifty_v2$endTp]\n\t\tdist <- genDistForEvent_v2(list_matrices[[mat_fiftyPoints[eventNum,cols_matFifty_v2$clus]]], mat_fiftyPoints[eventNum, cols_matFifty_v2$dir], mat_fiftyPoints[eventNum, cols_matFifty_v2$startTp], mat_fiftyPoints[eventNum, cols_matFifty_v2$endTp], phosTh, dephosTh, timeMap)\n\n\t\tlist_distributions[[length(list_distributions) + 1]] <- dist\n\t}\n\n\treturn(list_distributions)\n}\n\ngenDistForEvent_v2 <- function(clusMat, dir, startTp, endTp, phosTh, dephosTh, timeMap){\n\tmat_distribution <- matrix(ncol=4)\n\n\n\tfor (profNum in 1:nrow(clusMat)){\n\n\t\tif ((dir == 1 && clusMat[profNum, startTp] < clusMat[profNum, endTp]) || (dir == -1 && clusMat[profNum, startTp] > clusMat[profNum, endTp])){\n\t\t\t# direction holds; do calculation, and save.\n\t\t\t# print(clusMat[profNum, startTp:endTp])\n\n\t\t\tcrossPt <- calcCrossing_v4(clusMat[profNum, startTp:endTp], dir, (startTp -1), phosTh, dephosTh, timeMap)\n\n\t\t\tmat_distribution <- addToMatrix(mat_distribution, profNum, crossPt[1], crossPt[2], dir)\n\n\t\t}\n\t\telse{\n\t\t\tmat_distribution <- addToMatrix(mat_distribution, profNum, NA, NA, dir)\n\t\t}\n\t}\n\n\tmat_distribution <- mat_distribution[-1,, drop=FALSE]\n\treturn (mat_distribution)\n}\n\n\n\ncalcCrossing_v4 <- function(region, dir, offset, phosTh, dephosTh, timeMap){\n\n\tx_50 <- -1 # initial time\n\ty_50 <- -1 # initial th_point\n\n\ty_max <- max(region)\n\ty_min <- min(region)\n\n\tif (dir == 1){\n\t\ty_10Percent <- (y_max - y_min) * phosTh\n\t\ty_50 <- y_min + y_10Percent\n\t}\n\telse{\n\t\ty_10Percent <- (y_max - y_min) * (1- dephosTh)\n\t\ty_50 <- y_min + y_10Percent\n\t}\n\n\n\te = 0.0001 # due to calculation some round error when threshold is 0.\n\t# find intervals and store\n\tfor (j in 2:length(region)){\n\n\t\tif (dir == 1 && ( (y_50 >= region[j-1] && y_50 <= region[j]) || abs(y_50 - region[j-1]) < e || abs(y_50 - region[j]) < e )){\n\t\t\t# 50 is crossed here in phos direction\n\t\t\t# print(paste(\"Orig\", (offset+j-1), \" \", offset+j))\n\t\t\tx_50 <- getMidX_v2(timeMap[(offset+j-1)], region[j-1], timeMap[offset+j], region[j], y_50)\n\t\t\t# mat_fiftyPoints <- addToMatrix(mat_fiftyPoints, clusNum, x_50, y_50, 1)\n\t\t}\n\t\telse if (dir == -1 && ( (y_50 <= region[j-1] && y_50 >=region[j]) || abs(y_50 - region[j-1]) < e || abs(y_50 - region[j]) < e ) ){\n\t\t\t# 50 is crossed here in dephos direction\n\t\t\t# getMidX()\n\t\t\t# print(paste(\"Orig\", (offset+j-1), \" \" , offset+j))\n\t\t\tx_50 <- getMidX_v2(timeMap[(offset+j-1)], region[j-1], timeMap[offset+j], region[j], y_50)\n\t\t\t# mat_fiftyPoints <- addToMatrix(mat_fiftyPoints, clusNum, x_50, y_50, -1)\n\n\t\t}\n\t}\n\n\treturn (c(x_50, y_50))\n}\n\n\ngetMidX_v2 <- function(x1, y1, x2, y2, y_50){\n\n\tm <- (y2 - y1)/(x2 - x1)\n\tx_50 <- x1 + ((y_50 - y1)/m)\n\n\t# print(paste(x1, \" \", x2, \" \", x_50))\n\treturn (x_50)\n}\n", "meta": {"hexsha": "3e946981a6dd7c95a19ab14c25ea6774555de217", "size": 21159, "ext": "r", "lang": "R", "max_stars_repo_path": "R/orderedEvents_combined.r", "max_stars_repo_name": "ODonoghueLab/Minardo-Model", "max_stars_repo_head_hexsha": "8ad697ba495f96eb5420c94f0863ab56541ddaf0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2020-11-25T03:08:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-09-29T10:14:50.000Z", "max_issues_repo_path": "R/orderedEvents_combined.r", "max_issues_repo_name": "ODonoghueLab/Minardo-Model", "max_issues_repo_head_hexsha": "8ad697ba495f96eb5420c94f0863ab56541ddaf0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2020-04-08T09:47:48.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-23T02:36:36.000Z", "max_forks_repo_path": "R/orderedEvents_combined.r", "max_forks_repo_name": "ODonoghueLab/Minardo-Model", "max_forks_repo_head_hexsha": "8ad697ba495f96eb5420c94f0863ab56541ddaf0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.6122840691, "max_line_length": 422, "alphanum_fraction": 0.7342974621, "num_tokens": 6583, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6959583376458153, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.38588834306756126}} {"text": "#Title: Fitting decay curve 6time\n#Auther: Naoto Imamachi\n#ver: 1.0.0\n#Date: 2014-08-29\n\n#Time############################\nargs <- commandArgs(trailingOnly = T)\nfilename <- args[1]\nhour_list <- args[2] \n#hour_list <- \"0,1,2,4,8,12\"\nhour <- unlist(strsplit(hour_list,\",\"))\nhour <- as.numeric(hour)\nfirst_sample <- 5 - 1\nlast_sample <- 5 + length(hour) - 1 - 1\n\nfitting_optim_siRNA <- function(i){\nfname <- paste(i,\"_rel_normalized.fpkm_table\",sep=\"\")\noutput <- paste(i,\"_rel_normalized_cal.fpkm_table\",sep=\"\")\nall_data <- read.table(fname,row.names=1,header=T,sep=\"\\t\")\nsample_id <- row.names(all_data)\n\ncat(\"id\",\"value\",\"model1\",\"cor1\",\"a_1\",\"half1_1\",\"half1_2\",\"AIC1\",\"model2\",\"cor2\",\"a_2\",\"b_2\",\"half2\",\n \"AIC2\",\"model3\",\"cor3\",\"a_3\",\"b_3\",\"c_3\",\"half3\",\"AIC3\",sep=\"\\t\",file=output)\ncat(\"\\n\",file=output,append=T)\n\nfor(x in sample_id){\n\tmRNA <- all_data[x,]\n\tmRNA <- as.numeric(mRNA)\n\tmRNA <- mRNA[first_sample:last_sample] \n\tdat <- data.frame(hour,mRNA)\n\tdat <- dat[dat$mRNA > 0,]\n\tdat_point <- length(dat$mRNA)\n\tcat(x,\"\\t\",sep=\"\",file=output,append=T)\n \n if(mRNA[1] >= 1){\n\tif(dat_point >= 3){\n\t\tcat(\"ok\",\"\\t\",sep=\"\",file=output,append=T)\n\t\tsize <- length(dat[,\"mRNA\"])\n \n\t\t#model1:y = exp(-a * t)\n\t\toptim1 <- function(x){\n\t\t\tmRNA_exp <- exp(-x * dat[,\"hour\"])\n\t\t\tsum((dat[,\"mRNA\"]-mRNA_exp)^2)\n\t\t}\n\n\t\tout1 <- optim(1,optim1)\n\t\tmin1 <- out1$value\n\t\ta_1 <- out1$par[1]\n\t\thalf1_1 <- log(2) / a_1\n \n\t\tmodel1_pred <- function(x){\n\t\t\tmRNA_exp <- exp(-x * dat[,\"hour\"])\n\t\t\t(cor(mRNA_exp,dat[,\"mRNA\"],method=\"pearson\"))^2\n\t\t}\n\t\tcor1 <- model1_pred(a_1)\n\n\t\tmodel1_half <- function(x){\n\t\t\tmRNA_half <- exp(- a_1 * x)\n\t\t\t(mRNA_half - 0.5)^2\n\t\t}\n\t\t\n\t\tout1 <- optim(1,model1_half)\n\t\thalf1_2 <- out1$par\n\t\tmRNA_pred <- exp(- a_1 * dat[,\"hour\"])\n\t\ts2 <- sum((dat[,\"mRNA\"] - mRNA_pred )^2 )/ size\n\t\tAIC1 <- size * log(s2)+ 2 * 0\n \n\t\tcat(min1,cor1,a_1,half1_1,half1_2,AIC1,sep=\"\\t\",file=output,append=T)\n\t\tcat(\"\\t\",file=output,append=T)\n \n\t\t#model2:y = A * exp(-b * t) + c\n\t\toptim2 <- function(x){\n\t\t\tmRNA_exp <- (1.0 - x[2]) * exp(-x[1] * dat[,\"hour\"]) + x[2]\n\t\t\tsum((dat[,\"mRNA\"]-mRNA_exp)^2)\n\t\t}\n\n\t\tout2 <- optim(c(1,0),optim2)\n\t\tmin2 <- out2$value\n\t\ta_2 <- out2$par[1]\n\t\tb_2 <- out2$par[2]\n\n\t\tmodel2_pred <- function(a,b){\n\t\t\tmRNA_exp <- (1- b) * exp(-a * dat[,\"hour\"]) + b\n\t\t\t(cor(mRNA_exp,dat[,\"mRNA\"],method=\"pearson\"))^2\n\t\t}\n\n\t\tcor2 <- model2_pred(a_2,b_2)\n\n\t\tmodel2_half <- function(x){\n\t\t\tmRNA_half <- (1 - b_2) * exp(- a_2 * x) + b_2\n\t\t\t(mRNA_half - 0.5)^2\n\t\t}\n\t\t\n\t\tout2 <- optim(1,model2_half)\n\t\thalf2 <- out2$par\n \n if(b_2 >= 0.5){\n half2 <- Inf\n }\n \n mRNA_pred <- (1 - b_2) * exp(- a_2 * dat[,\"hour\"]) + b_2\n s2 <- sum((dat[,\"mRNA\"] - mRNA_pred )^2 )/ size\n AIC2 <- size * log(s2)+ 2 * 1\n\n\t\tcat(min2,cor2,a_2,b_2,half2,AIC2,sep=\"\\t\",file=output,append=T)\n\t\tcat(\"\\t\",file=output,append=T)\n\n\t\t#model3:y = A * exp(-b * t) + (1 - A) * exp (-c * t)\n\n\t\toptim3 <- function(x){\n\t\t\tmRNA_exp <- x[3] * exp(-x[1] * dat[,\"hour\"]) + (1 - x[3]) * exp(- x[2] * dat[,\"hour\"])\n\t\t\tsum((dat[,\"mRNA\"]-mRNA_exp)^2)\n\t\t}\n\n\t\tout3 <- optim(c(1,1,0.1),optim3)\n\t\tmin3 <- out3$value\n\t\ta_3 <- out3$par[1]\n\t\tb_3 <- out3$par[2]\n\t\tc_3 <- out3$par[3]\n\n\t\tmodel3_pred <- function(a,b,c){\n\t\t\tmRNA_exp <- c * exp(-a * dat[,\"hour\"]) + (1 - c) * exp(- b * dat[,\"hour\"])\n\t\t\t(cor(mRNA_exp,dat[,\"mRNA\"],method=\"pearson\"))^2\n\t\t}\n\n\t\tcor3 <- model3_pred(a_3,b_3,c_3)\n\n\t\tmodel3_half <- function(x){\n\t\t\tmRNA_half <- c_3 * exp(- a_3 * x) +(1 - c_3) * exp(- b_3 * x)\n\t\t\t(mRNA_half - 0.5)^2\n\t\t}\n\t\t\n\t\tout3 <- optim(1,model3_half)\n\t\thalf3 <- out3$par\n\t\tmRNA_pred <- c_3 * exp(- a_3 * dat[,\"hour\"]) + (1 - c_3) * exp(- b_3 * dat[,\"hour\"]) \n\t\ts2 <- sum((dat[,\"mRNA\"] - mRNA_pred )^2 )/ size\n\t\tAIC3 <- size * log(s2)+ 2 * 2\n\n\t\tcat(min3,cor3,a_3,b_3,c_3,half3,AIC3,sep=\"\\t\",file=output,append=T)\n\t\tcat(\"\\n\",file=output,append=T)\n \n\t\t} else {\n\t\t\tcat(\"few_data\",\"\\n\",sep=\"\",file=output,append=T)\n\t\t\tnext\n\t\t}\n\t\t}else{\n\t\t\tcat(\"low_expresion\",\"\\n\",sep=\"\",file=output,append=T)\n\t\t\tnext;\n\t\t}\n\n}\n\n}\n\nfitting_optim_siRNA(filename) \n", "meta": {"hexsha": "feea6843df1196f194090d89720abadb89341834", "size": 4048, "ext": "r", "lang": "R", "max_stars_repo_path": "cuffnorm_BRIC-seq/C_fitting_decay_curve_6time.r", "max_stars_repo_name": "Naoto-Imamachi/NGS_data_analysis_pipeline", "max_stars_repo_head_hexsha": "f6e4622c2e78bb8aab2263a714448120559b00e2", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2018-05-29T06:34:48.000Z", "max_stars_repo_stars_event_max_datetime": "2018-10-29T14:23:42.000Z", "max_issues_repo_path": "cuffnorm_BRIC-seq/C_fitting_decay_curve_6time.r", "max_issues_repo_name": "Naoto-Imamachi/NGS_data_analysis_pipeline", "max_issues_repo_head_hexsha": "f6e4622c2e78bb8aab2263a714448120559b00e2", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "cuffnorm_BRIC-seq/C_fitting_decay_curve_6time.r", "max_forks_repo_name": "Naoto-Imamachi/NGS_data_analysis_pipeline", "max_forks_repo_head_hexsha": "f6e4622c2e78bb8aab2263a714448120559b00e2", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2018-12-01T16:09:25.000Z", "max_forks_repo_forks_event_max_datetime": "2018-12-01T16:09:25.000Z", "avg_line_length": 25.9487179487, "max_line_length": 102, "alphanum_fraction": 0.5605237154, "num_tokens": 1647, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583124210896, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.3858883290811959}} {"text": "\" Пусть вектор w создан из значений разного типа\nВыяснить правило, по которому выполняется преобразование данных разных типов,\nхранящихся в векторе. Для этого последовательно создать вектора с данными одного\nтипа, двух типов, трех типов и т.д. Перебрать все возможные сочетания типов.\"\n\n\nw <- c(2,TRUE, \"char\", 3.4)\n#Правило:\n#Logical -> integer -> double -> character\n", "meta": {"hexsha": "212286a3564fd2fd901361c98f340a71161665bb", "size": 371, "ext": "r", "lang": "R", "max_stars_repo_path": "Course II/R/pract/pract4/task3.r", "max_stars_repo_name": "GeorgiyDemo/FA", "max_stars_repo_head_hexsha": "641a29d088904302f5f2164c9b3e1f1c813849ec", "max_stars_repo_licenses": ["WTFPL"], "max_stars_count": 27, "max_stars_repo_stars_event_min_datetime": "2019-08-18T20:54:27.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-22T02:39:45.000Z", "max_issues_repo_path": "Course II/R/pract/pract4/task3.r", "max_issues_repo_name": "GeorgiyDemo/FA", "max_issues_repo_head_hexsha": "641a29d088904302f5f2164c9b3e1f1c813849ec", "max_issues_repo_licenses": ["WTFPL"], "max_issues_count": 217, "max_issues_repo_issues_event_min_datetime": "2019-09-22T14:43:25.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T13:49:18.000Z", "max_forks_repo_path": "Course II/R/pract/pract4/task3.r", "max_forks_repo_name": "GeorgiyDemo/FA", "max_forks_repo_head_hexsha": "641a29d088904302f5f2164c9b3e1f1c813849ec", "max_forks_repo_licenses": ["WTFPL"], "max_forks_count": 42, "max_forks_repo_forks_event_min_datetime": "2019-09-18T11:36:28.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-19T18:43:00.000Z", "avg_line_length": 37.1, "max_line_length": 80, "alphanum_fraction": 0.7654986523, "num_tokens": 145, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.5467381372136563, "lm_q2_score": 0.7057850340255386, "lm_q1q2_score": 0.3858795947764}} {"text": "#' Calculate PROGENy pathway scores from gene expression\n#'\n#' This function uses the linear model of pathway-responsive genes underlying\n#' the PROGENy method. It transforms a gene expression matrix with HGNC/MGI gene\n#' symbols in rows and sample names in columns into a pathway score matrix with\n#' samples in rows and pathways in columns.\n#'\n#' The publication of the method is available at:\n#' https://www.nature.com/articles/s41467-017-02391-6\n#'\n#' The supplied expression object has to contain HGNC/MGI symbols in rows. This\n#' will, in most cases (and how we originally used it), be either normalized\n#' gene expression of a microarray experiment or log-transformed (and\n#' possible variance-stabilized) counts from an RNA-seq experiment.\n#'\n#' The human and mouse model matrices consists of 14 pathways and large set of \n#' genes with an associated p-value (p-value per gene and pathway) that accounts\n#' for the importance of each gene on each pathway upon perturbation. \n#' Its coefficients are non-zero if the gene-pathway pair corresponds\n#' to the top N genes (100 by default) that were up-regulated upon stimulation\n#' of the pathway in a wide range of experiments. The value corresponds to the \n#' fitted z-score across experiments in our model fit. \n#' Only rows with at least one non-zero coefficient were included, as the rest \n#' is not used to infer pathway activity.\n#'\n#' @param expr A gene expression object with HGNC/MGI symbols in rows and \n#' samples in columns. In order to run PROGENy in single-cell \n#' RNAseq data, it also accepts Seurat and SingleCellExperiment \n#' object, taking the normalized counts for the computation. \n#' @param scale A logical value indicating whether to scale the scores of each\n#' pathway to have a mean of zero and a standard deviation of one.\n#' It does not apply if we use permutations. \n#' @param organism The model organism - \"Human\" or \"Mouse\"\n\n#' @param top The top n genes for generating the model matrix according to\n#' significance (p-value)\n#' @param perm An interger detailing the number of permutations. No \n#' permutations by default (1). When Permutations larger than 1,\n#' we compute progeny pathway scores and assesses their \n#' significance using a gene sampling-based permutation strategy, \n#' for a series of experimental samples/contrasts.\n#' @param verbose A logical value indicating whether to display a message \n#' about the number of genes used per pathway to compute \n#' progeny scores (i.e. number of genes present in the \n#' progeny model and in the expression dataset)\n#' @param z_scores Only applies if the number of permutations is greater than 1. \n#' A logical value. TRUE: the z-scores will be returned for \n#' the pathway activity estimations. FALSE: the function returns \n#' a normalized z-score value between -1 and 1. \n#' @param get_nulldist Only applies if the number of permutations is greater \n#' than 1. A logical value. TRUE: the null distributions\n#' generated to assess the signifance of the pathways scores \n#' is also returned. \n#' @param assay_name Only applies if the input is a Seurat object. It selects the\n#' name of the assay on which Progeny will be run. Default to: \n#' RNA, i.e. normalized expression values.\n#' @param return_assay Only applies if the input is a Seurat object. A logical \n#' value indicating whether to return progeny results as a new \n#' assay called Progeny in the Seurat object used as input. \n#' Default to FALSE. \n#' @param ... Additional arguments to be passed to the functions. \n#' \n#' @return A matrix with samples in rows and pathways in columns. In case\n#' we run the method with permutations and the option get_nulldist\n#' to TRUE, we will get a list with two elements. The first \n#' element is the matrix with the pathway activity as before. \n#' The second elements is the null distributions that we generate\n#' to assess the signifance of the pathways scores. \n#' @export\n#' @seealso \\code{\\link{progenyPerm}}\n#' @examples\n#' # use example gene expression matrix here, this is just for illustration\n#' gene_expression <- as.matrix(read.csv(system.file(\"extdata\", \n#' \"human_input.csv\", package = \"progeny\"), row.names = 1))\n#'\n#' # calculate pathway activities\n#' pathways <- progeny(gene_expression, scale=TRUE, \n#' organism=\"Human\", top = 100, perm = 1)\nprogeny = function(expr, scale=TRUE, organism=\"Human\", top = 100, perm = 1, \n verbose = FALSE, z_scores = FALSE, get_nulldist = FALSE, assay_name = \"RNA\", \n return_assay = FALSE, ...) {\n UseMethod(\"progeny\")\n}\n\n#' @export\nprogeny.ExpressionSet = function(expr, scale=TRUE, organism=\"Human\", top = 100,\n perm = 1, verbose = FALSE, z_scores = FALSE, get_nulldist = FALSE, ...) {\n \n progeny(Biobase::exprs(expr), scale=scale, organism=organism, top=top, \n perm = perm, verbose = verbose, z_scores = z_scores, \n get_nulldist = get_nulldist)\n}\n\n#' @export\nprogeny.Seurat = function(expr, scale=TRUE, organism=\"Human\", top = 100,\n perm = 1, verbose = FALSE, z_scores = FALSE, get_nulldist = FALSE, \n assay_name = \"RNA\", return_assay = FALSE,...) {\n \n requireNamespace(\"Seurat\")\n \n if (!is.logical(return_assay)){\n stop(\"return_assay should be a logical value\")\n }\n \n if (scale & return_assay){\n warning(\"Scale and return_assay should not be both true. \n Please use the function Seurat::ScaleData(object, assay = \\\"progeny\\\") \n to scale PROGENy scores. Scale is set to FALSE\")\n scale = FALSE\n }\n \n results <- progeny(as.matrix(Seurat::GetAssayData(expr, slot = \"data\", \n assay = assay_name)), scale=scale, organism=organism, top=top, \n perm = perm, verbose = verbose, z_scores = z_scores, \n get_nulldist = get_nulldist, assay_name = assay_name, \n return_assay = return_assay)\n \n if (return_assay){\n expr[['progeny']] = Seurat::CreateAssayObject(data = t(results))\n Seurat::Key(object = expr[['progeny']]) <- 'progeny_'\n return(expr)\n } else {\n return(results)\n }\n \n}\n\n#' @export\nprogeny.SingleCellExperiment = function(expr, scale=FALSE, organism=\"Human\", \n top = 100, perm = 1, verbose = FALSE, z_scores = FALSE, \n get_nulldist = FALSE, ...) {\n \n requireNamespace(\"SingleCellExperiment\")\n\n progeny(as.matrix(SingleCellExperiment::normcounts(expr)), scale=scale, \n organism=organism, top=top, perm = perm, verbose = verbose, \n z_scores = z_scores, get_nulldist = get_nulldist)\n}\n\n#' @export\nprogeny.matrix = function(expr, scale=TRUE, organism=\"Human\", top = 100, \n perm = 1, verbose = FALSE, z_scores = FALSE, get_nulldist = FALSE,...) {\n \n if (!is.logical(scale)){\n stop(\"scale should be a logical value\")\n }\n \n if (!(is.numeric(perm)) || perm < 1){\n stop(\"perm should be an integer value\")\n }\n \n if (!is.logical(verbose)){\n stop(\"verbose should be a logical value\")\n }\n \n if (!is.logical(z_scores)){\n stop(\"z_scores should be a logical value\")\n }\n \n if (!is.logical(get_nulldist)){\n stop(\"get_nulldist should be a logical value\")\n }\n \n if (perm == 1 && (z_scores || get_nulldist)){\n if (verbose){\n message(\"z_scores and get_nulldist are only applicable when the\n number of permutations is larger than 1.\")\n }\n }\n \n model <- getModel(organism, top=top)\n common_genes <- intersect(rownames(expr), rownames(model))\n\n if (verbose){\n number_genes <- apply(model, 2, function (x) {\n sum(rownames(model)[which (x != 0)] %in% unique(rownames(expr)))\n })\n message(\"Number of genes used per pathway to compute progeny scores:\")\n message(paste(names(number_genes),\": \", number_genes, \" (\", \n (number_genes/top)*100,\"%)\",sep = \"\",\"\\n\"))\n }\n \n if (perm==1) {\n result <- t(expr[common_genes,,drop=FALSE]) %*% \n as.matrix(model[common_genes,,drop=FALSE])\n \n if (scale && nrow(result) > 1) {\n rn <- rownames(result)\n result <- apply(result, 2, scale)\n rownames(result) <- rn\n }\n \n } else if (perm > 1) {\n expr <- data.frame(names = row.names(expr), row.names = NULL, expr)\n model <- data.frame(names = row.names(model), row.names = NULL, model)\n result <- progenyPerm(expr, model, k = perm, z_scores = z_scores, \n get_nulldist = get_nulldist)\n }\n\n return(result) \n}\n\n#' @export\nprogeny.default = function(expr, scale=TRUE, organism=\"Human\", top = 100, \n perm = 1, verbose = FALSE, z_scores = FALSE, get_nulldist = FALSE, ...) {\n stop(\"Do not know how to access the data matrix from class \", class(expr))\n}\n", "meta": {"hexsha": "cf900e5e3176c3c0eee3a541cbd9d24d9cb1bab6", "size": 9183, "ext": "r", "lang": "R", "max_stars_repo_path": "R/progeny.r", "max_stars_repo_name": "saezlab/progeny", "max_stars_repo_head_hexsha": "f617cb37e3e76c3c912099081b524eecdc3ee47e", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 41, "max_stars_repo_stars_event_min_datetime": "2017-11-19T18:07:44.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-07T13:39:31.000Z", "max_issues_repo_path": "R/progeny.r", "max_issues_repo_name": "saezlab/progeny", "max_issues_repo_head_hexsha": "f617cb37e3e76c3c912099081b524eecdc3ee47e", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 36, "max_issues_repo_issues_event_min_datetime": "2018-02-03T11:43:52.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-28T08:58:32.000Z", "max_forks_repo_path": "R/progeny.r", "max_forks_repo_name": "saezlab/progeny", "max_forks_repo_head_hexsha": "f617cb37e3e76c3c912099081b524eecdc3ee47e", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 17, "max_forks_repo_forks_event_min_datetime": "2017-10-23T06:54:03.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-29T16:41:06.000Z", "avg_line_length": 44.1490384615, "max_line_length": 81, "alphanum_fraction": 0.640313623, "num_tokens": 2233, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585903489891, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.3854992742495961}} {"text": "# Auteurs :Philippe Pieri, Benjamin Bois - INRA, Equipe Ecophysiologie et Agronomie Viticole; 71, Rue Edouard Bourlaux B.P. 81, 33 883 VILLENAVE D’ORNON Cedex- contact : bbois@bordeaux.inra.fr\n# Traduction en langage R : Xavier Delpuech, IFV, Domaine de Donadille, 30230 Rodilhan. xavier.delpuech@vignevin.com , février 2012\n# Bibliographie\n# LEBON, E., DUMAS, V., PIERI, P. and SCHULTZ, H. R., 2003. Modelling the seasonal dynamics of the soil water balance of vineyards. Functional Plant Biology 30 (6).\n# RIOU, C., PIERI, P. and CLECH, B. L., 1994. Water use of grapevines well supplied with water. Simplified expression of transpiration. Vitis 33 (3).\n# RIOU, C., VALANCOGNE, C. and PIERI, P., 1989. Un modele simple d'interception du rayonnement solaire par la vigne. Verification experimentale. Agronomie 9 (5).\n# HARGREAVES, G. H. and SAMANI, Z. A., 1982. Estimating Potential Evapotranspiration. Journal of the Irrigation and Drainage Division 108 p. 223-230.\n# HARGREAVES, G. L., HARGREAVES, G. H. and RILEY, J. P., 1985. Agricultural benefits for Senegal River Basin. Journal of Irrigation and Drainage Engineering 111 p. 111-124.\n# BRISSON, N., PERRIER, A. (1991) A semi-empirical model of bare soil evaporation for crop simulation models Water Resources Research 27, p.719-727\n###\n#### sous fonction Radiation_Interception_DI\nRadiation_Interception_DI<-function(r_lat=44.5, r_longit=0, i_year=2000, i_doy=183, d_r=1.5, hf_r=1, lf_r=0.4, \naz_r=0, poro_r=0.25, alb_f=0.22, alb_s=0.18, Dt=1800, r_rgi=20)\n{\n#Dt = 1800\n#r_lat = latitude # =44.5\n#r_longit = 0\n#az_r = azimut # =0 Azimut en degrés (ex: 0=NS ; 90=EW ; -45 = NW-SE )\n#d_r = d # =1.5 Distance inter-rang (en mètres)\n#alb_f = 0.22\n#alb_s = alb_sol # =0.18\n#i_year = n_an\n#i_doy = doy # par defaut au 1er juillet\n#r_rgi = rg # par defaut = 20\n#hf_r = hautf # =1 Hauteur de feuillage (en metres)\n#lf_r = largf # =0.4 Largeur de feuillage (en metres)\n#poro_r = poro # =0.25 Porosite min en ete, de 0 à 1 (0=aucun trou dans le feuillage)\n\n#calculates daily integrals for radiation interception by vine rows and soil in a vineyard\n#parameters\nrDt = Dt\nrLatitude = r_lat\nrLongitude = r_longit\niYear = i_year\nrOrientRangs = az_r #à l#entrée : 0 pour rangs NS, 90 pour EW et -45 pour NW-SE\n #ici en entrée, rOrientRangs en degrés : ( 0=NS ; 90=EW ) ( -45 = NW-SE )\n #passage direction des rangs à angle de la normale aux rangs avec la direction NS\nrOrientRangs = rOrientRangs + 90 #orientée de N à S\n #If rOrientRangs >= 180 Then rOrientRangs = rOrientRangs - 180 CORRIGE LE 31/03/98 :\nif (rOrientRangs >= 90) rOrientRangs = rOrientRangs - 180\n#donc angle normale = -90 pour rangs NS, 0 pour EW , 45 pour NW-SE et -45 pour NE-SW\n#orientation comme angles d#azimut solaire, à partir du Sud, négatifs le matin et positifs l#après-midi\nrEcartRangs = d_r\nrHautRang = hf_r\nrLargRang = lf_r\nrPorosite = poro_r\nrAlbedoFeuilles = alb_f\nrAlbedoSol = alb_s\n\n #variables d#entree :\niSimulDay = i_doy\nrRgiJour = r_rgi * 1000000 #MJ.m^-2 à J.m^-2\n\n# ***************************************** DEBUT JOURNEE ***************************************\n\nrSJRytGlo = 0 #intialisation des intégrales journalières Rayonnement\nrSJRytDif = 0\nrSJRytGloVigne = 0\nrSJRytGloSol = 0\nrSJAlbedoVignoble = 0\nrSJRgvRel = 0\nrSJRgsRel = 0\n\niSJtot = 0 #compteurs\niSJdiurne = 0\n\n# ***************************************** DEBUT CALCULS ***************************************\n\n# Call ParSolAnn((iYear)) #sous programmes astronomiques annuel et journaliers\n# ParSolAnn(ian) # ian as integer\n# CALCUL DES PARAMETRES SOLAIRES ANNUELS\n#\n# rOmegaRadparJour, vitesse de la Terre (radian) (par jour) integer\n# rDoyEqui, date equinoxe (jour)\n# rLongitPerigRad, longitude perigee (radian)\n# rExentr, excentricite\n# rDoyPerig, date perigee (jour)\n# rEpsilonRad, obliquite(radian)\n#\n## ian=à définir\nian=iYear\nrOmegaRadparJour = 2 * pi / 365.25636\nrDoyEqui = 80.08 + 0.2422 * (ian - 1900) - trunc((ian - 1901) / 4)\nrLongitPerigRad = -1.374953 + 0.000300051 * (ian - 1900)\nrExentr = 0.016751 - 0.00000042 * (ian - 1900)\nrDoyPerig = rDoyEqui + (rLongitPerigRad - 2 * rExentr * sin(rLongitPerigRad)) / rOmegaRadparJour\nrEpsilonRad = 0.40932 - 0.000002271 * (ian - 1900)\nian = 1\n \n# Call ParSolJour((iYear), (iSimulDay)) # remplacé par le sous-programme lui-même\n#ParSolJour(ian As Integer, iNJ As Integer)\n# Calcul de la LONGITUDE CELESTE, de la DECLINAISON du Soleil\n# (radians), de l'EQUATION du TEMPS (minutes) pour le jour iNJ de\n# de l'annee iAn.\n\n# ATTENTION\n# Ce SOUS-PROGRAMME ne peut etre executé qu'apres le SOUS-PRO-\n# GRAMME PSOLAN(iAn, ...) qui definit les parametres solaires annuels\n#\n# COMMON /PARAN/rOmegaRadparJour,rDoyEqui,rLongitPerigRad,rExentr,rDoyPerig,rEpsilonRad\n# COMMON /PARJOU/rLongitCelesteRad,rDeltaRad,rEquaTemps\nian=iYear\niNJ=iSimulDay\nrNJ = iNJ + 0.5\n# LONGITUDE CELESTE du Soleil (radians)\nrLongitCelesteRad = rLongitPerigRad + rOmegaRadparJour * (rNJ - rDoyPerig) + 2 * rExentr * sin(rOmegaRadparJour * (rNJ - rDoyPerig))\n# DECLINAISON du Soleil (radians)\nrDeltaRad = asin(sin(rLongitCelesteRad) * sin(rEpsilonRad))\n# EQUATION DU TEMPS (minutes)\nrEquaTemps = 720 / pi * (atan(tan(rLongitCelesteRad) * cos(rEpsilonRad)) - rOmegaRadparJour * (rNJ - rDoyPerig) - rLongitPerigRad)\nwhile (rEquaTemps <= -100) (rEquaTemps = rEquaTemps + 720)\n### fin sous-programme\n\n# Call ParSolJourBis((iYear), (iSimulDay)) # remplacé par le sous-programme lui-même\n# ParSolJourBis(ian As Integer, iNJ As Integer)\n# Calcul de l'HEURE de PASSAGE du Soleil au MERIDIEN, de l'HEURE du\n# LEVER et du COUCHER du Soleil (h TU), de la DUREE du JOUR (h)\n#\n# Calcul du RAYONNEMENT GLOBAL EXTRATERRESTRE (Joule.m-2). On a admis\n# une valeur de la constante solaire de 1353 watt.m-2\n#\n# Pour passer à l'heure legale, ajouter le décalage par rapport a l'heure TU\n# (ex.: en FRANCE, +1h ou +2h selon la periode de l'annee, en GUADELOUPE, -4h, etc...)\n#\n# ATTENTION\n# Avant d'utiliser ce SOUS PROGRAMME, il est indispensable\n# d'executer dans l'ordre les SOUS PROGRAMMES:\n# PSOLAN(iAn) pour definir les parametres annuels\n# PSOLJ(NJ) pour definir les parametres journaliers\n# Il faut aussi preciser le lieu en définissant\n#\n#Dim rNJ, rLatRad, rRefrac, X, a, b, C As Double\n#Global rHrMidi, rDurJour, rHrLevSol, rHrCouSol, rRytGloExtraAtmJour As Double\nian=iYear\niNJ=iSimulDay\nrNJ = iNJ + 0.5\nrLatRad = rLatitude * pi / 180\n\n#HEURE DE PASSAGE du Soleil au MERIDIEN\nrHrMidi = 12 + rLongitude / 15 + rEquaTemps / 60\n\n#Durée du jour, avec rRefrac, Correction de réfraction atmosphérique\nrRefrac = -0.0106\nif (abs(rLatitude)== 90) X=(rLatRad * (rRefrac - rDeltaRad) * 1000000) else X=(sin(rRefrac) - sin(rLatRad) * sin(rDeltaRad)) / cos(rLatRad) / cos(rDeltaRad)\nif (X==0) rDurJour = 12\nif (X<=(-1))rDurJour = 24\nif (X>(-1)&(X<0)) rDurJour = 24 * (1 + atan((1 - X * X)^0.5 / X) / pi)\nif (X>=1) rDurJour = 0\nif ((X>0)&(X<1)) rDurJour = 24 * atan((1 - X * X)^0.5 / X) / pi\n\n#HEURES de LEVER et de COUCHER du Soleil\nrHrLevSol = rHrMidi - rDurJour / 2\nrHrCouSol = rHrMidi + rDurJour / 2\n\n#RAYONNEMENT GLOBAL EXTRATERRESTRE journalier\nX = abs(rLatRad + rDeltaRad)\nif (rLatRad==0) {a=cos(rDeltaRad)\n }else {if (rDeltaRad==0) {a=cos(rLatRad)\n }else {if (X>pi/2) {b = pi\n a = b * sin(rLatRad) * sin(rDeltaRad)\n }else {if (abs(rDeltaRad-rLatRad)>pi/2) {a=0\n }else {\n C = (1 - (sin(rLatRad) * sin(rLatRad) + sin(rDeltaRad) * sin(rDeltaRad)))^0.5 / sin(rLatRad) / sin(rDeltaRad)\n b = C + atan(-C)\n if (rLatRad * rDeltaRad > 0) {b=b+pi}else{}\n a = b * sin(rLatRad) * sin(rDeltaRad)\n }\n }\n }\n }\nrRytGloExtraAtmJour = 37210000 * (1 + 0.033 * cos(rOmegaRadparJour * (rNJ - rDoyPerig))) * a\n### fin sous-programme\n\nif (rRytGloExtraAtmJour <= 0) print(\"rRytGloExtraAtmJour <= 0\")\n\n\nif (rHautRang>0) { #******************** DEBUT BOUCLE rHautRang > 0 ***********************************\n #MsgBox \"rLAI >0 := \" & rLAI & snl() & \"jour et heure = \" & iSimulDay & \" , \" & rHr\n\nrLatRad = rLatitude * pi / 180 #Latitude en radians\nrOrientRangsRad = rOrientRangs * pi / 180 #Où rOrientRangs = ANGLE NORMALE AU RANG AVEC DIRECTION NORD-->SUD (DEGRES)\n\n #Début Appel Sous-Programmes Rayonnement\n# Sub AbsDiffus()\n# ex-subroutine KDIFFU(rKdif, rKdifSol, imodel)\n# Calcul des coefficients d'interception du rayonnement diffus :\n# rKdif, rayonnement venant du ciel et rKdifSol, rayonnement venant du sol\n# 1 variante : mur poreux sauf haut et bas, ex. Vigne (issu de MODELM.FOR)\n# c porosité du feuillage rPorosite\n# common /ccultu/rEcartRangs,rHautTotMax,rHautRang,rLargRang,rOrientRangs,rAlbedoFeuilles,rAlbedoSol,rPorosite\n#Dim rKDIF1, rKDIF2, rKDIF3 As Double DECLARE en GLOBAL\n\n# ... fraction du rayonnement diffus intercepté par la masse foliaire de la vigne\n #par les parties supérieures des rangs (horizontales et non poreuses)\n rKDIF1 = rLargRang / rEcartRangs\n #facteur de forme entre 2 rangs voisins : auparavant dans sub Calcul_PAR()\n rFF0 = tan(0.5 * atan(rHautRang / (rEcartRangs - rLargRang)))\n #facteur de forme entre les parois horizontales entre les rangs, supérieure et inférieure.\n rFFdif = tan(0.5 * atan((rEcartRangs - rLargRang) / rHautRang))\n #par les parois verticales (d'abord supposées non poreuses) 'eq 16 de Riou et al., 1989\n rKDIF2 = (1 - rFFdif)\n rKDIF2 = rKDIF2 * (1 - rLargRang / rEcartRangs)\n #par les parties inférieures des rangs (horizontales et non poreuses) 'eq 20 de Riou et al., 1989\n rKDIF3 = (sin(0.5 * atan(2 * rHautRang / rLargRang))) ^ 2\n rKDIF3 = rKDIF3 - (sin(0.5 * atan(rHautRang / (rEcartRangs - rLargRang / 2)))) ^ 2\n rKDIF3 = rKDIF3 * 2 * rLargRang / rEcartRangs\n rKdif = rKDIF1 + (1 - rPorosite) * rKDIF2 + rPorosite * rKDIF3 #eq 21 de Riou et al., 1989\n rKdifSol = rKdif\n##### fin \n\n# Sub CoefAbsRytDiff()\n# ex-subroutine ARDIF (rKdif,rKdifSol,cardif,crrdif)\n# calcul des taux d'absorption (cardif) et de réflexion (crrdif) du rayt.diffus\n# common /ccultu/rEcartRangs,rHautTotMax,rHautMax,rLargMax,rOrientRangs,rAlbedoFeuilles,rAlbedoSol,rPorositeMin\nrCardif = (1 - rAlbedoFeuilles) * ((1 - rAlbedoSol * rKdifSol) * rKdif + rAlbedoSol * rKdifSol)\nrCrrdif = (rAlbedoFeuilles - rAlbedoSol * (1 - rKdifSol) - rAlbedoFeuilles * rAlbedoSol * rKdifSol / 2) * rKdif\nrCrrdif = rCrrdif + (rAlbedoSol * (1 - rKdifSol) + rAlbedoFeuilles * rAlbedoSol * rKdifSol / 2)\n# fin sub\n\n# Sub PosGeomLim()\n# Positions Géométriques Limites\n# ex-subroutine cbetal(rBetaLim, nbetal, imodel)\n# interception du Rayonnement Solaire Direct\n# calcul des nbetal valeurs de rBetaLim(),\n# rapports correspondant a des positions caracteristiques limites\n# (composante Horizontale du Rayt DIRECT sur composante Verticale)\n rBetaLim_1 = rLargRang / rHautRang\n rBetaLim_2 = (rEcartRangs - rLargRang) / rHautRang\n rBetaLim_3 = rEcartRangs / rHautRang\n rBetaLim_4 = (rEcartRangs + rLargRang) / rHautRang\n rBetaLim_5 = (2 * rEcartRangs - rLargRang) / rHautRang\n rBetaLim_6 = (2 * rEcartRangs) / rHautRang\n rBetaLim_7 = (3 * rEcartRangs) / rHautRang\n# End Sub\n\n\n # premier indice pour boucle horaire :\n #(le temps rTempsTUFirst lu dans data_H doit être en heures TU decimales et centrées)\n j = 0 #calculs à partir de 0 h\n\n# ***************************************** DEBUT BOUCLE HORAIRE ***************************************\n repeat\n {\n if (j >= trunc(24 / (rDt / 3600))) break() \n\n rHr = rDt / 3600 / 2 + j * rDt / 3600\n\n #MsgBox \"jour et heure = \" & iSimulDay & \" , \" & rHr\n\n# sous-programme ParSolHor((rHr)) #paramètre rHr = Heure TU (h)\n### ParSolHor\n# Calcul des rHautSol et rAzimSol du Soleil (degres) à l#heure rHr (en h TU)\n# du jour iNJ de l#annee iAn pour un lieu de Latitude rLatitude, de\n# Longitude rLongitude (degres), d#équation du temps rEquaTemps (minutes),\n# et de déclinaison du Soleil rDeltaRad (radians)\n#\n# ATTENTION\n# Avant l#utilisation de ce SOUS-PROGRAMME, il faut avoir executé\n# les SOUS-PROGRAMMES ParSolAnn(iAn%) et ParSolJour(iNJ%, iAn%)\n# Il faut avoir precisé le lieu par sa rLatitude et sa rLongitude (degres)\n#\nrLatRad = rLatitude * pi / 180\n# ... Calcul Heure en Temps Solaire Vrai, rHrTSV et Angle Horaire (radians), rHrRad\nrHrTSV = rHr - 12 - rLongitude / 15 - rEquaTemps / 60\nrHrRad = rHrTSV * pi / 12\n# ... Calcul de la HAUTEUR du Soleil\nX = sin(rLatRad) * sin(rDeltaRad) + cos(rLatRad) * cos(rDeltaRad) * cos(rHrRad)\nif (X < 0) rHautSol = 0 #-99.9 #le Soleil n#est pas levé\nrHautSol=ifelse ((X==1), 90, asin(X) * 180 / pi) # XD : vérifier les radians\n# ... Calcul de l'AZIMUT du Soleil\n# codage signe: Nord -180°\n# Est -90°\n# Sud 0°\n# Ouest 90°\n# Nord 180°\n#\nX = sin(rLatRad) * cos(rHrRad) - cos(rLatRad) * tan(rDeltaRad)\nif (X==0) {\nb=90\na=0\n } else { if (X<0) {\n b =180\n } else { b=0\n }\n a = atan(sin(rHrRad) / X) * 180 / pi\n }\n\nif (rHrRad==0) {\nrAzimSol = 0\n }else{ if(rHrRad < 0) {\n rAzimSol = a - b\n }else{ rAzimSol = a + b\n }\n }\n# fin sous-programme ParSolHor\n\nrHeureTSV = rHr - rLongitude / 15 - rEquaTemps / 60 #temps solaire vrai (h)\nrAHDeg = (rHeureTSV - 12) * 15 #angle horaire (degrés)\nrAHRad = rAHDeg * pi / 180 #angle horaire (radians)\nrHautSolRad = rHautSol * pi / 180 #hauteur soleil (radians)\nrAzimSolRad = rAzimSol * pi / 180 #azimut soleil (radians)\n\niSJtot = iSJtot + 1 #compteur jour\n\n #Microclimat_Feuilles #MsgBox \"Microclimat_Feuilles Terminé\"\n\n #rSJTleaf = rSJTleaf + rTleaf #mise à jour des intégrales journalières microclimat\n #rSJDefSat = rSJDefSat + rDefSat\n\nif (rHautSol>0) { #DEBUT TEST rHautSol > 0 pour partie Ryt Solaire\n#rSJTleafDiurne = rSJTleafDiurne + rTleaf #mise à jour des intégrales journ. microclimat periode diurne\n#rSJDefSatDiurne = rSJDefSatDiurne + rDefSat\niSJdiurne = iSJdiurne + 1 #compteur periode diurne\nr = 1353 * (1 + 2 * rExentr * cos(rOmegaRadparJour * iSimulDay + 0.5 - rDoyPerig))\nrRytGloExtraAtm = r * sin(rHautSol * pi / 180)\n#If bOption11 = False Then\nrRytGlo = rRytGloExtraAtm * rRgiJour / rRytGloExtraAtmJour\n#End If\n\n if (rRytGloExtraAtm>0) { #Début calcul Rayonnement Diffus\n GSG0 = rRytGlo / rRytGloExtraAtm\n }else{GSG0 = 0\n }\n\n\n #DSG = 1.09 - 2.6896 * GSG0 * GSG0 + 1.2843 * GSG0 * GSG0 * GSG0 # relation journalière à Bordeaux (CV)\n DSG = 1.09 - 2.44 * GSG0 * GSG0 + 1.084 * GSG0 * GSG0 * GSG0 # relation horaire à Bordeaux (CV)\n\n if (DSG>1) DSG = 1\n if (GSG0 >= 0.2) {\n rRytDif = rRytGlo * DSG\n rRytDir = rRytGlo - rRytDif\n } else {\n rRytDif = rRytGlo\n rRytDir = 0\n }\n\n if (rRytDif < 0) rRytDif = 0\n if (rRytDir < 0) rRytDir = 0\n\n # ... rapport composante horizontale (--> paroi verticale)\n # ... / composante verticale (--> paroi horizontale) du Ryt Direct (RDIR)\n rBeta1 = cos(rOrientRangsRad) * tan(rLatRad)\n rBeta2 = sin(rDeltaRad) * cos(rOrientRangsRad) / (sin(rHautSolRad) * cos(rLatRad))\n rBeta3 = sin(rOrientRangsRad) * cos(rDeltaRad) * sin(rAHRad) / sin(rHautSolRad)\n rBeta = abs(rBeta1 - rBeta2 + rBeta3)\n\n# Sub AbsDirect()\n# ex-subroutine kdirec(rBetaLim, nbetal, imodel, rKdir, rBeta)\n# interception du Rayonnement Solaire Direct par le feuillage\n# rBetaLim() rapports correspondant a des valeurs caracteristiques de rBeta\n# rBeta = rapport composante Horizontale du Rayt DIRECT / composante Verticale\n\n if (rBeta > rBetaLim_1) {\n if (rBeta > rBetaLim_2) {\n if (rBeta > rBetaLim_3) {\n if (rBeta > rBetaLim_4) {\n if (rBeta > rBetaLim_5) {\n if (rBeta > rBetaLim_6) {\n if (rBeta >= rBetaLim_7) {\n rKdir = (rEcartRangs - rPorosite * rPorosite * rPorosite * (rEcartRangs - rLargRang)) / rEcartRangs\n }else{\n rKdir = (rEcartRangs - rPorosite * rPorosite * (rEcartRangs - rLargRang) + rPorosite * rPorosite * (1 - rPorosite) * (rBeta * rHautRang - 2 * rEcartRangs - rLargRang)) / rEcartRangs\n }\n }else{\n rKdir = (rEcartRangs - rPorosite * rPorosite * (rBeta * rHautRang - rEcartRangs - rLargRang)) / rEcartRangs\n }\n }else{\n rKdir = (rEcartRangs - rPorosite * (2 * rEcartRangs - rLargRang - rBeta * rHautRang) - rPorosite * rPorosite * (rBeta * rHautRang - rEcartRangs - rLargRang)) / rEcartRangs\n }\n }else{\n rKdir = (rEcartRangs - rPorosite * (2 * rEcartRangs - rLargRang - rBeta * rHautRang)) / rEcartRangs\n }\n }else{\n rKdir = (rEcartRangs - rPorosite * (rBeta * rHautRang - rLargRang)) / rEcartRangs\n }\n }else{\n rKdir = ((rBeta * rHautRang + rLargRang) - rPorosite * (rBeta * rHautRang - rLargRang)) / rEcartRangs\n }\n }else{\n rKdir = ((rBeta * rHautRang + rLargRang) / rEcartRangs)\n }\n#End Sub\n\n#Sub CoefAbsRytDir()\n# ex-subroutine ARDIR(rKdifSol, rKdir, cardir, crrdir)\n# calcul des taux d'absorption (cardir) et de de réflexion (crrdir) du rayt. direct\nrCardir = (1 - rAlbedoFeuilles) * ((1 - rAlbedoSol * rKdifSol) * rKdir + rAlbedoSol * rKdifSol)\nrCrrdir = (rAlbedoFeuilles - rAlbedoSol * (1 - rKdifSol) - rAlbedoFeuilles * rAlbedoSol * rKdifSol / 2) * rKdir\nrCrrdir = rCrrdir + (rAlbedoSol * (1 - rKdifSol) + rAlbedoFeuilles * rAlbedoSol * rKdifSol / 2)\n#End Sub\n\n\n }else{ #SUITE TEST rHautSol > 0 donc ici #If rHautSol <= 0\n rHautSol = 0 #pour partie ryt sol\n rAzimSol = 0\n rRytGloExtraAtm = 0\n rRytGlo = 0\n rRytDir = 0\n rRytDif = 0\n rCardir = 0\n rCrrdir = 0\n rBeta = 0\n } #FIN TEST rHautSol > 0 pour partie Ryt Solaire\n\n rRytGloVigne = rCardir * rRytDir + rCardif * rRytDif\n rRytGloSol = (1 - rCardir - rCrrdir) * rRytDir + (1 - rCardif - rCrrdif) * rRytDif\n\n if (rRytGlo > 0) {\n rAlbedoVignoble = (rCrrdir * rRytDir + rCrrdif * rRytDif) / rRytGlo\n rRgvRel = rRytGloVigne / ((1 - rAlbedoVignoble) * rRytGlo)\n rRgsRel = rRytGloSol / ((1 - rAlbedoVignoble) * rRytGlo)\n }\n if (rRytGlo <= 0) {\n rAlbedoVignoble = 0\n rRgvRel = 0\n rRgsRel = 0\n }\n\n rSJRytGlo = rSJRytGlo + rRytGlo * rDt #Mise à Jour des Intégrales Journalières / Rayonnement\n rSJRytDif = rSJRytDif + rRytDif * rDt\n rSJRytGloVigne = rSJRytGloVigne + rRytGloVigne * rDt\n rSJRytGloSol = rSJRytGloSol + rRytGloSol * rDt\n\n\n j = j + 1\n } #FIN BOUCLE HORAIRE commencee par : Do While (j < CInt(24 / (rDt / 3600)))\n\n # ------------------------------ mise à jour des intégrales journalières (rSJ...) ---------------------\n # et sur toute la duree du fichier d#entree (rSom...)\n\n if (rSJRytGlo>0){\n rSJAlbedoVignoble = 1 - (rSJRytGloVigne + rSJRytGloSol) / rSJRytGlo #ratios journaliers / Rayonnement\n rSJRgvRel = rSJRytGloVigne / ((1 - rSJAlbedoVignoble) * rSJRytGlo)\n rSJRgsRel = rSJRytGloSol / ((1 - rSJAlbedoVignoble) * rSJRytGlo)\n }\n\n} #fin boucle if rHautRang > 0 (realisation calculs int ryt dans boucle horaire)\n\n # ------------------------------ sorties journalières ------------------------------------\n # (intégrales sur la durée de la journée)\nsor_ryt=data.frame(c(1:25)) \nsor_ryt[1,1]= iSimulDay\nsor_ryt[2,1]= iYear\nsor_ryt[3,1]= rLatitude\nsor_ryt[4,1]= rHrLevSol\nsor_ryt[5,1]= rHrCouSol\nsor_ryt[6,1]= rDurJour\nsor_ryt[7,1]= rRytGloExtraAtmJour / 1000000\nsor_ryt[8,1]= rRgiJour / 1000000\n\n if (rHautRang>0){ #donc si realisation calculs int ryt (et event. photos.) dans boucle horaire\n sor_ryt[9,1] = rEcartRangs\n sor_ryt[10,1] = az_r #comme en entrée : 0 pour rangs NS, 90 pour EW et -45 pour NW-SE\n sor_ryt[11,1] = rHautRang\n sor_ryt[12,1] = rLargRang\n sor_ryt[13,1] = rPorosite\n sor_ryt[14,1] = rPorosite\n sor_ryt[15,1] = tan(0.5 * atan(rHautRang / (rEcartRangs - rLargRang))) #Fact de Forme entre 2 rangs\n\n sor_ryt[16,1] = rSJRytGlo / 1000000\n sor_ryt[17,1] = (rSJRytGlo - rSJRytDif) / 1000000\n sor_ryt[18,1] = rSJRytDif / 1000000\n sor_ryt[19,1] = rSJRytGloVigne / 1000000\n sor_ryt[20,1] = rSJRytGloSol / 1000000\n sor_ryt[21,1] = rSJAlbedoVignoble\n sor_ryt[22,1] = rSJRgvRel\n sor_ryt[23,1] = rSJRgsRel\n sor_ryt[24,1] = iSJdiurne #nb d#intervalles utilisés pour calculer les integrales SJ (jour entier)\n sor_ryt[25,1] = iSJtot #nb d#intervalles utilisés pour calculer les integrales SJ (per. diurne)\n }else{\n for (i in 9:25) {\n sor_ryt[i,1] = 0 \n }\n } #FIN TEST If rHautRang > 0 Then\n #(=test si realisation effective des calculs d#int ryt dans boucle horaire)\n\n#résultats journaliers :\n #Cells(i_ligne, 49).Value = sor_ryt(21) #alb\n #Cells(i_ligne, 50).Value = sor_ryt(22) #k_rgv\nreturn(sor_ryt[22,1]) # retourne en sortie le kmax de la vigne\n} # fin de la fonction Radiation_Interception_DI\n\n\n", "meta": {"hexsha": "ed1432449ab75ab52adb6c671dfe198b1d6606ca", "size": 23172, "ext": "r", "lang": "R", "max_stars_repo_path": "optapp-rootR/Module_calcul_Kmax_2012.r", "max_stars_repo_name": "XavierDelpuech/walisplm", "max_stars_repo_head_hexsha": "275f04907febf1c7f24e457a0133bf3db0687895", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "optapp-rootR/Module_calcul_Kmax_2012.r", "max_issues_repo_name": "XavierDelpuech/walisplm", "max_issues_repo_head_hexsha": "275f04907febf1c7f24e457a0133bf3db0687895", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "optapp-rootR/Module_calcul_Kmax_2012.r", "max_forks_repo_name": "XavierDelpuech/walisplm", "max_forks_repo_head_hexsha": "275f04907febf1c7f24e457a0133bf3db0687895", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.7773195876, "max_line_length": 213, "alphanum_fraction": 0.5949853271, "num_tokens": 8414, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743735019594, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.38453636899680016}} {"text": "\n# Investigating Dengue RDT sensitivity and specificty requirements\n# written by Stefan Flasche using R version 3.4.4\n# results published in \"On the importance of sensitivity and the negative predictive value for a rapid dengue test\" by S. Flasche and P.G. Smith\n\n# load packages\nrequire(tidyverse)\n\n\n# Data --------------------------------------------------------------------\n\n# data: cumulative incidence over 5yrs observed in the trial and its stratification into \n# seropositive and seronegative using PRNT50 with multiple imputation (in per 100). \ndf <- tibble(no=1:8,\n randomisation = c(\"vacc\",\"vacc\",\"control\",\"control\",\"vacc\",\"vacc\",\"control\",\"control\"),\n serostatus = c(\"pos\",\"neg\",\"pos\",\"neg\",\"pos\",\"neg\",\"pos\",\"neg\"),\n outcome = c(rep(\"hosp\",4),rep(\"severe\",4)),\n incidence.ph.mid = c(.375,1.571,1.883,1.093,0.075,0.404,0.48,0.174),\n incidence.ph.lo = c(.263,1.125,1.536,.526,0.034,0.218,0.335,0.036),\n incidence.ph.hi = c(.535,2.193,2.307,2.265,0.165,0.749,0.688,0.834))\n\n# plot data\np.data <- df %>% ggplot(aes(x= serostatus, y = incidence.ph.mid, ymin = incidence.ph.lo, ymax = incidence.ph.hi,color=randomisation)) +\n geom_linerange(position=position_dodge(width = 0.5)) +\n geom_point(position=position_dodge(width = 0.5)) +\n facet_grid(.~outcome, scales = \"free\") +\n coord_flip() + ylab(\"incidence per 100\") +\n labs(y = \"Incidence per 100\", x = \"Serostatus\", color = \"Randomisation\")\nggsave(filename = \"Pics\\\\Fig1_Data.tiff\",p.data ,unit=\"cm\", width = 14, height = 5, compression = \"lzw\", dpi = 300)\n\n\n# sample from lognormal distribution in which the 50%, 2.5% and 97.5% quanitles fit the observed mean, CI.lo and CI.hi respectively\nLnfitSample <- function(input= c(mean=1, lo=.5, hi=2), N=10000){\n mean = input[1] %>% as.numeric()\n lo = input[2] %>% as.numeric()\n hi = input[3] %>% as.numeric()\n rlnorm(N, meanlog = log(mean), sdlog = (log(mean/lo) + log(hi/mean))/2/1.96) %>%\n return()\n}\n\n\n# Population impact of test and vaccinate ---------------------------------------------\n\n# calculate population impact of test and vaccinate strategy\n## need to include resampling of incidence \nCasesAverted <- function(seroPrevalence = .7, sensitivity = 1, specificity = 0, \n cohortSize=100000, df.tmp = df, outcm = \"hosp\"){\n df.tmp = df.tmp %>% filter(outcome == outcm)\n Inc.SeroPos.Vacc <- df.tmp %>% filter(randomisation==\"vacc\" & serostatus ==\"pos\") %>% \n select(incidence.ph.mid:incidence.ph.hi) %>% LnfitSample()\n Inc.SeroPos.Cont <- df.tmp %>% filter(randomisation==\"control\" & serostatus ==\"pos\") %>% \n select(incidence.ph.mid:incidence.ph.hi) %>% LnfitSample()\n Inc.SeroNeg.Vacc <- df.tmp %>% filter(randomisation==\"vacc\" & serostatus ==\"neg\") %>% \n select(incidence.ph.mid:incidence.ph.hi) %>% LnfitSample()\n Inc.SeroNeg.Cont <- df.tmp %>% filter(randomisation==\"control\" & serostatus ==\"neg\") %>% \n select(incidence.ph.mid:incidence.ph.hi) %>% LnfitSample()\n \n CasesAvertedSeroPos = cohortSize * seroPrevalence * sensitivity * (Inc.SeroPos.Cont - Inc.SeroPos.Vacc) / 100\n CasesAvertedSeroNeg = cohortSize * (1-seroPrevalence) * (1 - specificity) * (Inc.SeroNeg.Cont - Inc.SeroNeg.Vacc) /100\n \n df_res <- tibble(seroPrevalence = seroPrevalence, sensitivity = sensitivity,\n specificity = specificity, outcome = outcm, \n CasesAvertedSeroPos.mid = median(CasesAvertedSeroPos), \n CasesAvertedSeroPos.lo = quantile(CasesAvertedSeroPos,.025), \n CasesAvertedSeroPos.hi = quantile(CasesAvertedSeroPos,.975),\n CasesAvertedSeroNeg.mid = median(CasesAvertedSeroNeg), \n CasesAvertedSeroNeg.lo = quantile(CasesAvertedSeroNeg,.025), \n CasesAvertedSeroNeg.hi = quantile(CasesAvertedSeroNeg,.975), \n CasesAvertedTotal.mid = median(CasesAvertedSeroPos + CasesAvertedSeroNeg), \n CasesAvertedTotal.lo = quantile(CasesAvertedSeroPos + CasesAvertedSeroNeg, .025),\n CasesAvertedTotal.hi = quantile(CasesAvertedSeroPos + CasesAvertedSeroNeg, .975))\n return(df_res)\n}\n\n# plot impact of test and vaccinate strategy\ndf.plt = NULL\nfor(seroPrevalence in c(.6,.7,.8)){\n for(specificity in c(.9,.95,.98,.99,1)){\n for(sensitivity in seq(.8,1,by=.05)){\n df.plt <- df.plt %>% \n rbind(CasesAverted(seroPrevalence = seroPrevalence, sensitivity = sensitivity, specificity = specificity))\n }\n }\n}\n\ndf.plt <- df.plt %>%\n gather(key,value, -seroPrevalence, -sensitivity, -specificity, -outcome) %>%\n extract(key, c(\"outcome\",\"conf\"),\"(.*)\\\\.(.*)\") %>%\n spread(conf, value)\n \np.tandv = df.plt %>% ggplot(aes(x=sensitivity, y = mid, ymin=lo, ymax= hi, color = as.factor(seroPrevalence))) +\n geom_linerange(position = position_dodge(width = 0.04)) +\n geom_point(position = position_dodge(width = 0.04)) +\n facet_grid(outcome ~ specificity, scales = \"free\") +\n scale_color_discrete(name=\"seroprevalence\") + ylab(\"hospitalised dengue cases averted\\nin a 100,000 cohort\") +\n geom_hline(yintercept = 0, color=\"black\", lty=\"dashed\")\nggsave(filename = \"Pics\\\\Fig2_Impact_TandV.tiff\",p.tandv ,unit=\"cm\", width = 25, height = 14, compression = \"lzw\", dpi = 300)\n\n\n# Impact of sensitivity --------------------------------------------------------------------\n \n# calculate sensitivity needed to avoid chosing to vaccinate test negative\nTestNegRatio <- function(seroPrevalence = .7, sensitivity = .8, specificity = .95,\n df.tmp = df, outcm = \"hosp\", midonly=F){\n df.tmp = df.tmp %>% filter(outcome == outcm)\n if(midonly){\n Inc.SeroPos.Vacc <- df.tmp %>% filter(randomisation==\"vacc\" & serostatus ==\"pos\") %>% \n select(incidence.ph.mid) %>% as.numeric()\n Inc.SeroPos.Cont <- df.tmp %>% filter(randomisation==\"control\" & serostatus ==\"pos\") %>% \n select(incidence.ph.mid) %>% as.numeric()\n Inc.SeroNeg.Vacc <- df.tmp %>% filter(randomisation==\"vacc\" & serostatus ==\"neg\") %>% \n select(incidence.ph.mid) %>% as.numeric()\n Inc.SeroNeg.Cont <- df.tmp %>% filter(randomisation==\"control\" & serostatus ==\"neg\") %>% \n select(incidence.ph.mid) %>% as.numeric()\n }else{\n Inc.SeroPos.Vacc <- df.tmp %>% filter(randomisation==\"vacc\" & serostatus ==\"pos\") %>% \n select(incidence.ph.mid:incidence.ph.hi) %>% LnfitSample()\n Inc.SeroPos.Cont <- df.tmp %>% filter(randomisation==\"control\" & serostatus ==\"pos\") %>% \n select(incidence.ph.mid:incidence.ph.hi) %>% LnfitSample()\n Inc.SeroNeg.Vacc <- df.tmp %>% filter(randomisation==\"vacc\" & serostatus ==\"neg\") %>% \n select(incidence.ph.mid:incidence.ph.hi) %>% LnfitSample()\n Inc.SeroNeg.Cont <- df.tmp %>% filter(randomisation==\"control\" & serostatus ==\"neg\") %>% \n select(incidence.ph.mid:incidence.ph.hi) %>% LnfitSample()\n }\n \n risk.if.testNeg.vacc <- ((1-seroPrevalence) * specificity * Inc.SeroNeg.Vacc + \n seroPrevalence * (1-sensitivity) * Inc.SeroPos.Vacc ) / \n ((1-seroPrevalence) * specificity + seroPrevalence * (1-sensitivity) ) \n risk.if.testNeg.nova <- ((1-seroPrevalence) * specificity * Inc.SeroNeg.Cont + \n seroPrevalence * (1-sensitivity) * Inc.SeroPos.Cont ) / \n ((1-seroPrevalence) * specificity + seroPrevalence * (1-sensitivity) ) \n \n df_res <- tibble(seroPrevalence = seroPrevalence, sensitivity = sensitivity,\n specificity = specificity, outcome = outcm, \n riskiftestNegvacc.mid = median(risk.if.testNeg.vacc), \n riskiftestNegnova.mid = median(risk.if.testNeg.nova),\n riskiftestNegvacc.lo = quantile(risk.if.testNeg.vacc,.025), \n riskiftestNegvacc.hi = quantile(risk.if.testNeg.vacc,.975),\n riskiftestNegnova.lo = quantile(risk.if.testNeg.nova,.025), \n riskiftestNegnova.hi = quantile(risk.if.testNeg.nova,.975),\n RR.mid = median(risk.if.testNeg.vacc / risk.if.testNeg.nova), \n RR.lo = quantile(risk.if.testNeg.vacc / risk.if.testNeg.nova, .025),\n RR.hi = quantile(risk.if.testNeg.vacc / risk.if.testNeg.nova, .975))\n return(df_res)\n}\n\n# analyse where test nagative vacc vs novacc risks are for a number of scenarios\ndf.plt = NULL\nfor(seroPrevalence in c(.5,.7,.9)){\n for(specificity in c(.95,1)){\n for(sensitivity in seq(.6,1,by=.1)){\n df.plt <- df.plt %>% \n rbind(TestNegRatio(seroPrevalence = seroPrevalence, sensitivity = sensitivity, specificity = specificity)) %>%\n rbind(TestNegRatio(seroPrevalence = seroPrevalence, sensitivity = sensitivity, specificity = specificity, outcm = \"severe\"))\n \n }\n }\n}\n\np.sens <- df.plt %>% \n ggplot(aes(x=sensitivity, y = RR.mid, ymin=RR.lo, ymax= RR.hi, color=outcome)) +\n geom_linerange(position = position_dodge(width = 0.04)) +\n geom_point(position = position_dodge(width = 0.04)) +\n facet_grid(seroPrevalence ~ specificity, scales = \"free\") +\n scale_y_log10() + geom_hline(yintercept = 1, color=\"black\", lty=\"dashed\") +\n scale_color_discrete(name=\"outcome\") +\n ylab(\"RR for hospitalised dengue\\nin test-negative for\\nvaccination vs no vaccination\")\nggsave(filename = \"Pics\\\\FigX_SensitivityImpact.tiff\",p.sens ,unit=\"cm\", width = 20, height = 12, compression = \"lzw\", dpi = 300)\n\n# analyse where test nagative vacc vs novacc risks - map\ndf.plt2 = NULL\nfor(seroPrevalence in c(.5,.6,.7,.8,.9)){\n for(specificity in seq(.9,1,by=.01)){\n for(sensitivity in seq(.6,1,by=.01)){\n df.plt2 <- df.plt2 %>% \n rbind(TestNegRatio(seroPrevalence = seroPrevalence, sensitivity = sensitivity, specificity = specificity, midonly=T)) %>%\n rbind(TestNegRatio(seroPrevalence = seroPrevalence, sensitivity = sensitivity, specificity = specificity, outcm = \"severe\", midonly=T))\n \n }\n }\n}\n\np.sens.b <- df.plt2 %>% \n ggplot(aes(x=sensitivity, y=specificity, fill = RR.mid)) +\n facet_grid(seroPrevalence ~ outcome) + \n geom_tile() +\n scale_fill_gradient2(name=\"RR in vaccinees\\nvs controls\", low = \"green\", mid = \"yellow\",\n high = \"red\", midpoint = 0, breaks=round(c(.5,1/1.2,1/1.1,1,1.1,1.2,2),2),trans = \"log\", limits=c(1/1.21,1.2)) +\n theme_bw() +\n labs(x = \"Sensitivity\", y = \"Specificity\")\nggsave(\"Pics\\\\Fig3a_SensitivityImpactMap.tiff\", p.sens.b, width = 20, height = 13, units = \"cm\", compression=\"lzw\", dpi =300)\n\n\n# importance of NPV ---------------------------------------------\nTestNegRatio.NPV <- function(NPV = .7, df.tmp = df, outcm = \"hosp\"){\n df.tmp = df.tmp %>% filter(outcome == outcm)\n\n Inc.SeroPos.Vacc <- df.tmp %>% filter(randomisation==\"vacc\" & serostatus ==\"pos\") %>% \n select(incidence.ph.mid:incidence.ph.hi) %>% LnfitSample()\n Inc.SeroPos.Cont <- df.tmp %>% filter(randomisation==\"control\" & serostatus ==\"pos\") %>% \n select(incidence.ph.mid:incidence.ph.hi) %>% LnfitSample()\n Inc.SeroNeg.Vacc <- df.tmp %>% filter(randomisation==\"vacc\" & serostatus ==\"neg\") %>% \n select(incidence.ph.mid:incidence.ph.hi) %>% LnfitSample()\n Inc.SeroNeg.Cont <- df.tmp %>% filter(randomisation==\"control\" & serostatus ==\"neg\") %>% \n select(incidence.ph.mid:incidence.ph.hi) %>% LnfitSample()\n\n risk.if.testNeg.vacc <- ( NPV * Inc.SeroNeg.Vacc + \n (1-NPV) * Inc.SeroPos.Vacc ) \n risk.if.testNeg.nova <- ( NPV * Inc.SeroNeg.Cont + \n (1-NPV) * Inc.SeroPos.Cont ) \n \n df_res <- tibble(NPV = NPV, outcome = outcm, \n riskiftestNegvacc.mid = median(risk.if.testNeg.vacc), \n riskiftestNegnova.mid = median(risk.if.testNeg.nova),\n riskiftestNegvacc.lo = quantile(risk.if.testNeg.vacc,.025), \n riskiftestNegvacc.hi = quantile(risk.if.testNeg.vacc,.975),\n riskiftestNegnova.lo = quantile(risk.if.testNeg.nova,.025), \n riskiftestNegnova.hi = quantile(risk.if.testNeg.nova,.975),\n RR.mid = median(risk.if.testNeg.vacc / risk.if.testNeg.nova), \n RR.lo = quantile(risk.if.testNeg.vacc / risk.if.testNeg.nova, .025),\n RR.hi = quantile(risk.if.testNeg.vacc / risk.if.testNeg.nova, .975))\n return(df_res)\n}\n\ndf.plt.NPV = NULL\nfor( NPV in seq(.5,1,by=0.01)){\n df.plt.NPV = df.plt.NPV %>% \n rbind(TestNegRatio.NPV(NPV)) %>%\n rbind(TestNegRatio.NPV(NPV, outcm = \"severe\"))\n}\ndf.plt.NPV$outcome = df.plt.NPV$outcome %>% str_replace(\"hosp\",\"Hospitalised\")\ndf.plt.NPV$outcome = df.plt.NPV$outcome %>% str_replace(\"severe\",\"Severe\")\ndf.plt.NPV %>%\n ggplot(aes(x=NPV, y=RR.mid, ymin=RR.lo, ymax=RR.hi, group=outcome, color=outcome, fill=outcome)) +\n geom_ribbon(alpha=0.2, color=NA) +\n geom_line() +\n geom_hline(yintercept = 1, color = \"black\", lty = \"dashed\") + \n #facet_grid(outcome~., scales=\"free\") +\n scale_y_log10() +\n labs(x = \"Negative predictive value\", y = \"RR for\\nsevere or hospitalised disease \\nin test-negative for\\nvaccination vs no vaccination\",\n fill = \"Outcome\", color = \"Outcome\") +\n theme_bw()+\n guides(group=F) \nggsave(\"Pics\\\\Fig3b_NPVimpact.tiff\", width = 13, height = 7, units = \"cm\", compression=\"lzw\", dpi =1000)\nggsave(\"Pics\\\\Fig3b_NPVimpact.pdf\", width = 13, height = 7, units = \"cm\")\n\n# calculate min sens needed ---------------------------------------------\n\nget_PV <- function(specificity=.9, sensitivity=.7, seroprevalence=0.7 ){\n tp= sensitivity * seroprevalence\n fn= (1-sensitivity) * seroprevalence\n tn= specificity * (1-seroprevalence)\n fp= (1-specificity) * (1-seroprevalence)\n \n PPV = tp / (tp+fp) #prop of true positive among all pos\n NPV = tn / (tn+fn) #prop of negative positive among all negative\n \n df = data.frame(specificity=as.factor(specificity), sensitivity=sensitivity, seroprevalence=seroprevalence, NPV=NPV, PPV=PPV) %>%\n as.tibble()\n \n return(df)\n \n}\n\nres = NULL\nfor(specificity in c(.9,.95,.99)){\n for(seroprevalence in seq(0.15,1,by=0.01)){\n for(sensitivity in seq(0,1,by=0.01)){\n res = res %>%\n rbind(get_PV(specificity, sensitivity, seroprevalence))\n }\n }\n}\nmin.PPV = .90\nmin.NPV = .75 # Ratio for RR forvaccinees to get hospitalised in Seropos vs Seroneg is 1.57/1.09 / 0.375/1.88\np.dat = res %>% group_by(specificity,seroprevalence) %>% mutate(PPV.based = ( PPV == min(PPV + 5*(PPV%\n filter(PPV.based | NPV.based) %>% \n gather(criteria, value, -specificity, -sensitivity, -seroprevalence, -NPV, -PPV) %>%\n filter (value) \np.dat$criteria = p.dat$criteria %>% str_replace(\"V.b\",\"V b\")\np = p.dat %>% \n ggplot(aes(x=seroprevalence, y=sensitivity, color=criteria, lty = specificity)) +\n geom_line() +\n theme_bw() + \n labs(x = \"Seroprevalence\", y = \"Minimum sensitivity\", color = \"Criteria\", lty = \"Specificity\") +\n scale_x_continuous(breaks = seq(0.1,1,by=0.2)) +\n scale_y_continuous(breaks = seq(0,1,by=0.2))\nggsave(\"Pics/RequiredSensitivity.tiff\", p, units = \"cm\",height = 7, width = 13, compression=\"lzw\", dpi=1000)\nggsave(\"Pics/RequiredSensitivity.pdf\", p, units = \"cm\",height = 7, width = 13)\n\n", "meta": {"hexsha": "90525c82586b6cdf64a9ea79a6d30d9dd1c09018", "size": 15155, "ext": "r", "lang": "R", "max_stars_repo_path": "main.r", "max_stars_repo_name": "StefanFlasche/Dengue_RDT_specs", "max_stars_repo_head_hexsha": "3ac896534a2f1179f944385015530ba4071f5701", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "main.r", "max_issues_repo_name": "StefanFlasche/Dengue_RDT_specs", "max_issues_repo_head_hexsha": "3ac896534a2f1179f944385015530ba4071f5701", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "main.r", "max_forks_repo_name": "StefanFlasche/Dengue_RDT_specs", "max_forks_repo_head_hexsha": "3ac896534a2f1179f944385015530ba4071f5701", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 51.9006849315, "max_line_length": 144, "alphanum_fraction": 0.6323985483, "num_tokens": 4693, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7981867873410141, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.3835117324169164}} {"text": "\n# Read in World Ocean Atlas data\nnms <- c('lat', 'lon', 'm0', 'm5', 'm10', 'm15', 'm20', 'm25', 'm30', 'm35', 'm40', 'm45', 'm50', 'm55', 'm60', 'm65', 'm70', 'm75', 'm80', 'm85', 'm90', 'm95', 'm100', 'm125', 'm150', 'm175', 'm200', 'm225', 'm250', 'm275', 'm300', 'm325', 'm350', 'm375', 'm400', 'm425', 'm450', 'm475', 'm500', 'm550', 'm600', 'm650', 'm700', 'm750', 'm800', 'm850', 'm900', 'm950', 'm1000', 'm1050', 'm1100', 'm1150', 'm1200', 'm1250', 'm1300', 'm1350', 'm1400', 'm1450', 'm1500', 'm1550', 'm1600', 'm1650', 'm1700', 'm1750', 'm1800', 'm1850', 'm1900', 'm1950', 'm2000', 'm2100', 'm2200', 'm2300', 'm2400', 'm2500', 'm2600', 'm2700', 'm2800', 'm2900', 'm3000', 'm3100', 'm3200', 'm3300', 'm3400', 'm3500', 'm3600', 'm3700', 'm3800', 'm3900', 'm4000', 'm4100', 'm4200', 'm4300', 'm4400', 'm4500', 'm4600', 'm4700', 'm4800', 'm4900', 'm5000', 'm5100', 'm5200', 'm5300', 'm5400', 'm5500')\ndps <- c(0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100, 125, 150, 175, 200, 225, 250, 275, 300, 325, 350, 375, 400, 425, 450, 475, 500, 550, 600, 650, 700, 750, 800, 850, 900, 950, 1000, 1050, 1100, 1150, 1200, 1250, 1300, 1350, 1400, 1450, 1500, 1550, 1600, 1650, 1700, 1750, 1800, 1850, 1900, 1950, 2000, 2100, 2200, 2300, 2400, 2500, 2600, 2700, 2800, 2900, 3000, 3100, 3200, 3300, 3400, 3500, 3600, 3700, 3800, 3900, 4000, 4100, 4200, 4300, 4400, 4500, 4600, 4700, 4800, 4900, 5000, 5100, 5200, 5300, 5400, 5500) # the depths associated with each column (after lat/lon)\n\nwoa <- read.csv('data_dl/woa/woa13_decav_t00an01v2.csv', skip=2, row.names=NULL, header=FALSE, col.names=nms) # use col.names to force all columns to be read (file doesn't have trailing ,s for blank columns)\n\n\n# Initial plot (slow)\n\ncol = rgb(0,0,0,0.01)\nplot(dps, woa[1,3:ncol(woa)], type='l', ylab='temperature', xlab='depth (m)', ylim=c(-2,30), col=col, xlim=c(0,1000))\nfor(i in 2:nrow(woa)){\n\tlines(dps, woa[i,3:ncol(woa)], col=col)\n}\n\n\n###########################################\n# average temperature within lat bands\n###########################################\nwoalat <- aggregate(list(m0=woa$m0, m5=woa$m5, m10=woa$m10, m15=woa$m15, m20=woa$m20, m25=woa$m25, m30=woa$m30, m35=woa$m35, m40=woa$m40, m45=woa$m45, m50=woa$m50, m55=woa$m55, m60=woa$m60, m65=woa$m65, m70=woa$m70, m75=woa$m75, m80=woa$m80, m85=woa$m85, m90=woa$m90, m95=woa$m95, m100=woa$m100, m125=woa$m125, m150=woa$m150, m175=woa$m175, m200=woa$m200, m225=woa$m225, m250=woa$m250, m275=woa$m275, m300=woa$m300, m325=woa$m325, m350=woa$m350, m375=woa$m375, m400=woa$m400, m425=woa$m425, m450=woa$m450, m475=woa$m475, m500=woa$m500, m550=woa$m550, m600=woa$m600, m650=woa$m650, m700=woa$m700, m750=woa$m750, m800=woa$m800, m850=woa$m850, m900=woa$m900, m950=woa$m950, m1000=woa$m1000, m1050=woa$m1050, m1100=woa$m1100, m1150=woa$m1150, m1200=woa$m1200, m1250=woa$m1250, m1300=woa$m1300, m1350=woa$m1350, m1400=woa$m1400, m1450=woa$m1450, m1500=woa$m1500, m1550=woa$m1550, m1600=woa$m1600, m1650=woa$m1650, m1700=woa$m1700, m1750=woa$m1750, m1800=woa$m1800, m1850=woa$m1850, m1900=woa$m1900, m1950=woa$m1950, m2000=woa$m2000, m2100=woa$m2100, m2200=woa$m2200, m2300=woa$m2300, m2400=woa$m2400, m2500=woa$m2500, m2600=woa$m2600, m2700=woa$m2700, m2800=woa$m2800, m2900=woa$m2900, m3000=woa$m3000, m3100=woa$m3100, m3200=woa$m3200, m3300=woa$m3300, m3400=woa$m3400, m3500=woa$m3500, m3600=woa$m3600, m3700=woa$m3700, m3800=woa$m3800, m3900=woa$m3900, m4000=woa$m4000, m4100=woa$m4100, m4200=woa$m4200, m4300=woa$m4300, m4400=woa$m4400, m4500=woa$m4500, m4600=woa$m4600, m4700=woa$m4700, m4800=woa$m4800, m4900=woa$m4900, m5000=woa$m5000, m5100=woa$m5100, m5200=woa$m5200, m5300=woa$m5300, m5400=woa$m5400, m5500=woa$m5500), by=list(lat=woa$lat), FUN=mean, na.rm=TRUE)\n\n\n\n# plot lat averages, color by lat\n#col = rgb(0,0,0,0.1)\ncols <- rainbow(nrow(woalat))\nplot(dps, woalat[1,2:ncol(woalat)], type='l', ylab='temperature', xlab='depth (m)', ylim=c(-2,30), col=cols[1], xlim=c(0,1000))\nfor(i in 2:nrow(woalat)){\n\tlines(dps, woalat[i,2:ncol(woalat)], col=cols[i])\n}\n\nabline(v=100, lty=2)\n\n# plot SST vs. lat\nplot(woalat$lat, woalat$m0, type='l')\nabline(v=5)\n\n\n# plot all profiles at 0.5°\ninds <- which(woa$lat==0.5)\ncols <- rainbow(length(inds))\nplot(dps, woa[inds[1],3:ncol(woa)], type='l', ylab='temperature', xlab='depth (m)', ylim=c(-2,30), col=cols[1], xlim=c(0,1000))\nfor(i in 2:length(inds)){\n\tlines(dps, woa[inds[i],3:ncol(woa)], col=cols[i])\n}\n\n\n# plot all profiles where depth < 1000\ninds <- which(is.na(woa$m1050))\ncol = rgb(0,0,0,0.1)\nplot(dps, woa[inds[1],3:ncol(woa)], type='l', ylab='temperature', xlab='depth (m)', ylim=c(-2,30), col=col, xlim=c(0,1000))\nfor(i in 2:length(inds)){\n\tlines(dps, woa[inds[i],3:ncol(woa)], col=col)\n}\n\n##################\n# Average all\n##################\n\nwoaave <- apply(woa[,3:ncol(woa)], MARGIN=2, FUN=mean, na.rm=TRUE)\n\nplot(dps, woaave, type='l')\n\nplot(dps, woaave, type='l', xlim=c(0,300))\n\nwoaave['m50'] - woaave['m0']\nwoaave['m300'] - woaave['m0']\n\n\n#######################\n# Average change in temperature\n#######################\n\nmean(woa$m50 - woa$m0, na.rm=TRUE)\nmean(woa$m300 - woa$m0, na.rm=TRUE)\nmean(woa$m1000 - woa$m0, na.rm=TRUE)", "meta": {"hexsha": "7a6e073b85a8ea89679f2b0e0b6ea623a89d8289", "size": 5174, "ext": "r", "lang": "R", "max_stars_repo_path": "data/pinsky/pinskylab-hotWater-250832d/scripts/woa.r", "max_stars_repo_name": "HuckleyLab/phyto-mhw", "max_stars_repo_head_hexsha": "8e067c73310fb4a4520d5a72f68717030ce90e14", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-10-13T02:37:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-27T04:41:09.000Z", "max_issues_repo_path": "data/pinsky/pinskylab-hotWater-250832d/scripts/woa.r", "max_issues_repo_name": "HuckleyLab/phyto-mhw", "max_issues_repo_head_hexsha": "8e067c73310fb4a4520d5a72f68717030ce90e14", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2020-07-19T10:54:37.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-17T19:53:09.000Z", "max_forks_repo_path": "data/pinsky/pinskylab-hotWater-250832d/scripts/woa.r", "max_forks_repo_name": "HuckleyLab/phyto-mhw", "max_forks_repo_head_hexsha": "8e067c73310fb4a4520d5a72f68717030ce90e14", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 67.1948051948, "max_line_length": 1667, "alphanum_fraction": 0.6347120216, "num_tokens": 2569, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.672331699179286, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.38313000140710163}} {"text": "## Usage: Rscript this.r [pos_range]\n\noptions(stringsAsFactors=FALSE)\n\n\n\nlibrary(HDInterval)\n\n\n\n`%.%` <- function(x,y) paste0(x,y)\n\njoin = function(sep, vec, ...) paste(collapse=sep, c(vec, ...))\ncat0 = function(...) cat(sep=\"\", ...)\n\necho_str <- function(x, sep=\" =\\t\", collapse=\", \") deparse(substitute(x)) %.% sep %.% join(collapse, x)\necho <- function(x, sep=\" =\\t\", collapse=\", \") cat0(deparse(substitute(x)), sep, join(collapse, x), \"\\n\");\n\n\n\nstr_trim_left = function(str, trimLen){\n\tstrlen = nchar(str)\n\tstart = pmin(strlen, trimLen) + 1\n\tend = strlen\n\tsubstr(str, start, end)\n}\nstr_trim_right = function(str, trimLen){\n\tstrlen = nchar(str)\n\tstart = 1\n\tend = pmax(0, strlen - trimLen)\n\tsubstr(str, start, end)\n}\nstr_left = function(str, len){\n\tstrlen = nchar(str)\n\tstart = 1\n\tend = pmin(len, strlen)\n\tsubstr(str, start, end)\n}\nstr_right = function(str, len){\n\tstrlen = nchar(str)\n\tstart = pmax(1, strlen - len + 1)\n\tend = strlen\n\tsubstr(str, start, end)\n}\n\n\n\n### ref: http://varianceexplained.org/r/bayesian_fdr_baseball/\ncummean = function(vec){\n\tcumsum(vec) / (1:length(vec))\n}\nPEP_to_qvalues = function(PEP_vec){\n\torder_vec = order(PEP_vec)\n\tans = rep(NA, length(PEP_vec))\n\tPEP_ordered = PEP_vec[order_vec]\n\tqvalue_ordered = cummean(PEP_ordered)\n\tans[order_vec] = qvalue_ordered\n\tans\n}\n\n\n\nif(interactive()==FALSE){\n\targs = commandArgs(TRUE)\n}\nif(length(args) < 3){\n\tstop(\"Usage: Rscript this.r [pos_range]\")\n}\n\noutput_prefix = args[1]\ninput_foreground_prefix = args[2]\ninput_background_prefix = args[3]\n\npos_range = NULL\nif(length(args) >= 4){\n\tpos_range = args[4]\n\ttmp = as.integer(strsplit(pos_range, \"[:-]\")[[1]])\n\tif(length(tmp)==1){\n\t\t# good, do nothing\n\t\t# 2019-08-21, Yyx debug, pos_range will be character without converting\n\t\tpos_range = as.integer(tmp[1])\n\t}else if(length(tmp)==2){\n\t\tpos_range = tmp[1]:tmp[2]\n\t}else{\n\t\tstop(\"Cannot recognize pos_range = \" %.% pos_range)\n\t}\n}\n\n\n\ninput_foreground_stat_DF = read.delim(input_foreground_prefix %.% \".all.stat.txt\")\necho(dim(input_foreground_stat_DF))\ninput_background_stat_DF = read.delim(input_background_prefix %.% \".all.stat.txt\")\necho(dim(input_background_stat_DF))\nstopifnot(nrow(input_foreground_stat_DF)==nrow(input_background_stat_DF))\n\nnames(input_foreground_stat_DF) = \"in1.\" %.% names(input_foreground_stat_DF)\nnames(input_background_stat_DF) = \"in2.\" %.% names(input_background_stat_DF) # there is a bug in previous version, and debugged on 2019-08-29\ninput_DF = cbind(input_foreground_stat_DF, input_background_stat_DF)\necho(dim(input_DF))\n\ninput_DF$in1.simu_num = NA\ninput_DF$in1.mu_mean = NA\ninput_DF$in1.mu_LB = NA\ninput_DF$in1.mu_UB = NA\ninput_DF$in2.simu_num = NA\ninput_DF$in2.mu_mean = NA\ninput_DF$in2.mu_LB = NA\ninput_DF$in2.mu_UB = NA\ninput_DF$muDiff.simu_num = NA\ninput_DF$muDiff_mean = NA\ninput_DF$muDiff_LB = NA\ninput_DF$muDiff_UB = NA\ninput_DF$muDiff_gt0_posterior = NA\ninput_DF$muDiff_gt0_01_posterior = NA\ninput_DF$muDiff_gt0_05_posterior = NA\ninput_DF$muDiff_gt0_1_posterior = NA\n\nreal_pos_range = 1:nrow(input_DF)\nif(!is.null(pos_range)){\n\treal_pos_range = pos_range[pos_range %in% 1:nrow(input_DF)]\n}\n\nfor(i in real_pos_range){\n\techo(i)\n\ttry({\n\tmcmc_1 = read.delim(input_foreground_prefix %.% \".site_\" %.% i %.% \".mcmc_rlt.tsv\")\n\tinput_DF$in1.simu_num[i] = nrow(mcmc_1)\n\tinput_DF$in1.mu_mean[i] = mean(mcmc_1$mu)\n\ttmp = hdi(mcmc_1$mu)\n\tinput_DF$in1.mu_LB[i] = tmp[1]\n\tinput_DF$in1.mu_UB[i] = tmp[2]\n\t})\n\t\n\ttry({\n\tmcmc_2 = read.delim(input_background_prefix %.% \".site_\" %.% i %.% \".mcmc_rlt.tsv\")\n\tinput_DF$in2.simu_num[i] = nrow(mcmc_2)\n\tinput_DF$in2.mu_mean[i] = mean(mcmc_2$mu)\n\ttmp = hdi(mcmc_2$mu)\n\tinput_DF$in2.mu_LB[i] = tmp[1]\n\tinput_DF$in2.mu_UB[i] = tmp[2]\n\t})\n\t\n\ttry({\n\tNS = min(c(nrow(mcmc_1), nrow(mcmc_2)))\n\tmuDiff_vec = mcmc_1$mu[1:NS] - mcmc_2$mu[1:NS]\n\tinput_DF$muDiff.simu_num[i] = NS\n\tinput_DF$muDiff_mean[i] = mean(muDiff_vec)\n\ttmp = hdi(muDiff_vec)\n\tinput_DF$muDiff_LB[i] = tmp[1]\n\tinput_DF$muDiff_UB[i] = tmp[2]\n\tinput_DF$muDiff_gt0_posterior[i] = mean(muDiff_vec > 0)\n\tinput_DF$muDiff_gt0_01_posterior[i] = mean(muDiff_vec > 0.01)\n\tinput_DF$muDiff_gt0_05_posterior[i] = mean(muDiff_vec > 0.05)\n\tinput_DF$muDiff_gt0_1_posterior[i] = mean(muDiff_vec > 0.1)\n\t})\n}\nwrite.table(input_DF[real_pos_range,], file=output_prefix %.% \".final_\" %.% min(pos_range) %.% \"_\" %.% max(pos_range) %.% \".stat.txt\", row.names=FALSE, sep=\"\\t\", quote=FALSE)\n\nfor(gt_str in c(\"0\", \"0_01\", \"0_05\", \"0_1\")){\n\tinput_DF[[\"muDiff_gt\" %.% gt_str %.% \"_PEP\"]] = 1 - input_DF[[\"muDiff_gt\" %.% gt_str %.% \"_posterior\"]]\n\tinput_DF[[\"muDiff_gt\" %.% gt_str %.% \"_FDR\"]] = PEP_to_qvalues(input_DF[[\"muDiff_gt\" %.% gt_str %.% \"_PEP\"]])\n}\nwrite.table(input_DF[real_pos_range,], file=output_prefix %.% \".final_\" %.% min(pos_range) %.% \"_\" %.% max(pos_range) %.% \".stat.txt\", row.names=FALSE, sep=\"\\t\", quote=FALSE)\n\n", "meta": {"hexsha": "32840761e5eb3d3d25fd2c4da418599f0edd1846", "size": 4929, "ext": "r", "lang": "R", "max_stars_repo_path": "stratify_and_Bayesian/hierarchical_Bayesian_model_jags_SHM_test.20190819/Yyx_two_group_compare.20190903.r", "max_stars_repo_name": "Yyx2626/HTGTSrep", "max_stars_repo_head_hexsha": "d8716304b555a7b9161e5f2ce988ebfd17abc9f0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-05-08T05:12:37.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-28T02:53:03.000Z", "max_issues_repo_path": "stratify_and_Bayesian/hierarchical_Bayesian_model_jags_SHM_test.20190819/Yyx_two_group_compare.20190903.r", "max_issues_repo_name": "Yyx2626/HTGTSrep", "max_issues_repo_head_hexsha": "d8716304b555a7b9161e5f2ce988ebfd17abc9f0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-03-05T04:08:39.000Z", "max_issues_repo_issues_event_max_datetime": "2021-08-11T15:02:37.000Z", "max_forks_repo_path": "stratify_and_Bayesian/hierarchical_Bayesian_model_jags_SHM_test.20190819/Yyx_two_group_compare.20190903.r", "max_forks_repo_name": "Yyx2626/HTGTSrep", "max_forks_repo_head_hexsha": "d8716304b555a7b9161e5f2ce988ebfd17abc9f0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2020-05-30T12:45:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-31T12:24:53.000Z", "avg_line_length": 29.6927710843, "max_line_length": 174, "alphanum_fraction": 0.701562183, "num_tokens": 1635, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5774953651858117, "lm_q2_score": 0.6619228758499942, "lm_q1q2_score": 0.3822573929138351}} {"text": "#!/usr/bin/Rscript\n\n## icdiff.r -- Calculate information content difference for\n## fastphase-formatted genotype file\n\n## Author: David Eccles (gringer), 2008 \n\nusage <- function(){\n cat(\"usage: ./icdiff.r\",\" \\n\");\n cat(\"\\nOther Options:\\n\");\n cat(\"-help : Only display this help message\\n\");\n cat(\"-hapmap3 : Hapmap phase 3 formatted Files\\n\");\n cat(\"\\n\");\n}\n\ninfile.name <- FALSE;\noutfile.name <- FALSE;\nhapmap3 <- FALSE;\n\nargLoc <- 1;\nwhile(!is.na(commandArgs(TRUE)[argLoc])){\n if(file.exists(commandArgs(TRUE)[argLoc])){ # file existence check\n if(infile.name == FALSE){\n infile.name <- commandArgs(TRUE)[argLoc];\n } else {\n cat(\"Error: More than one existing [input] file specified\\n\");\n usage();\n quit(save = \"no\", status=1);\n }\n } else {\n if(commandArgs(TRUE)[argLoc] == \"-help\"){\n usage();\n quit(save = \"no\", status=0);\n } else if(commandArgs(TRUE)[argLoc] == \"-hapmap3\"){\n hapmap3 <- TRUE;\n } else {\n outfile.name <- commandArgs(TRUE)[argLoc];\n }\n }\n argLoc <- argLoc + 1;\n}\n\nif((infile.name == FALSE) || (outfile.name == FALSE)){\n cat(\"Error: No valid input/output file name given\\n\\n\");\n usage();\n quit(save = \"no\", status=1);\n}\n\n## max(table(apply(head(gt.df,33), 2, paste, collapse = \"\"))) == 1;\n\n## # show heatmap of first 33 genotypes (at start of chromosome 21)\n## heatmap(t(head(gt.df,33)), scale = \"none\", Colv = NA);\n\n## dist.ind <- as.matrix(dist(t(gt.df), method = \"manhattan\"))\n## diag(dist.ind) <- NA;\n\n## ## because of recombination, bits of one parent will be scattered\n## ## through each chromosome, so the differences will even out over\n## ## large stretches of the chromosome, so differences between each\n## ## homologous chromosome and chromosomes from other people will\n## ## balance out.\n## heatmap(as.matrix(dist.ind), col = topo.colors(100), symm = TRUE)\n\n\n## information content of some split with counts A1,A2,An:\n## let P(An) = An / Sum(A1..An)\n## Ic = Sum(-P(An) * log(An,2))\n## [Russell, pages 659-660]\n\n## What I want is the difference between the maximum split and the\n## actual split. Sum that, and it should give an indication of the\n## prevalence of particular haplotypes over others (i.e. extended\n## haplotype homozygosity).\n\n## Need to make sure it continues for at least log(n) iterations,\n## because until then, we don't know if a haplotype is more prevalent\n## than expected in the random case.\n\n## this spreads out in both directions, averaging one choosing to go\n## left first and one choosing to go right first\n\nicDiffSum <- function(genotype.matrix, location, constrain = TRUE){\n if(is.null(dim(genotype.matrix))){\n dim(genotype.matrix) <- c(length(genotype.matrix),1);\n }\n ic.target <- log(dim(genotype.matrix)[1],2);\n num.haplotypes <- dim(genotype.matrix)[1];\n ic.diffs.left <- NULL;\n lengths.left <- NULL;\n ic.diffs.right <- NULL;\n lengths.right <- NULL;\n for(leftBias in c(TRUE, FALSE)){\n goLeft <- leftBias;\n diffpos <- 1;\n ic.value <- 0;\n loc.left <- location;\n loc.right <- location;\n while(ic.value < ic.target){\n if(constrain){\n ## constrain information content to maximum possible with\n ## given number of haplotypes\n ic.max <- min(((loc.right - loc.left) + 1), ic.target);\n } else {\n ic.max <- (loc.right - loc.left) + 1;\n }\n ## warning: null genotypes appear as genotype \"NA\"\n if(loc.right != loc.left){\n prob.hap <- table(apply(genotype.matrix[,loc.left:loc.right],\n 1, paste, collapse = \"\")) / num.haplotypes;\n } else {\n prob.hap <- table(genotype.matrix[,loc.left]) / num.haplotypes;\n }\n ic.value <- sum(-prob.hap * log(prob.hap,2));\n ##print(paste(leftBias, \" -> \", ic.value));\n if(leftBias == TRUE){\n ic.diffs.left[diffpos] <- (ic.max - ic.value) / ic.max;\n lengths.left[diffpos] <- (loc.right-loc.left) + 1;\n } else {\n ic.diffs.right[diffpos] <- (ic.max - ic.value) / ic.max;\n lengths.right[diffpos] <- (loc.right-loc.left) + 1;\n }\n diffpos <- diffpos + 1;\n ## Extra logic to make sure it doesn't duplicate results by\n ## hanging in the same place for two iterations. These two\n ## 'goLeft' cases could be combined, but it makes the code less\n ## clear.\n if(goLeft){\n goLeft <- !goLeft; # i.e. goLeft <- FALSE\n if(loc.left > 1){\n loc.left <- max(1,loc.left - 1);\n } else {\n loc.right <- min(dim(genotype.matrix)[2],loc.right + 1);\n }\n } else {\n goLeft <- !goLeft; # i.e. goLeft <- TRUE\n if(loc.right < dim(genotype.matrix)[2]){\n loc.right <- min(dim(genotype.matrix)[2],loc.right + 1);\n } else {\n loc.left <- max(1,loc.left - 1);\n }\n }\n if((loc.left == 1) && (loc.right == dim(genotype.matrix)[2])){\n ## if the entire chromosome is covered, do no more\n ic.value <- ic.target;\n }\n }\n }\n ## print(rbind(round(lengths.left,5),round(ic.diffs.left,5)));\n ## print(rbind(round(lengths.right,5),round(ic.diffs.right,5)));\n return((sum(ic.diffs.left) + sum(ic.diffs.right))/2);\n}\n\noldicDiffSum <- function(genotype.matrix){\n ic.diffs <- NULL;\n ic.diff <- 1;\n ic.value <- 0;\n x <- 1;\n if(is.null(dim(genotype.matrix))){\n dim(genotype.matrix) <- c(1,length(genotype.matrix));\n }\n ic.target <- log(dim(genotype.matrix)[2],2);\n while((ic.value < ic.target) && (x <= dim(genotype.matrix)[1])){\n ic.max <- min(x,ic.target);\n counts.hap <- table(apply(head(genotype.matrix,x), 2, paste, collapse = \"\"));\n prob.hap <- counts.hap / sum(counts.hap);\n ic.value <- sum(-prob.hap * log(prob.hap,2));\n ic.diff <- ((ic.max - ic.value) / ic.max);\n ic.diffs <- c(ic.diffs,ic.diff);\n x <- x+1;\n }\n return(sum(ic.diffs));\n}\n\ngtval <- function(x){\n if((is.matrix(x)) || (is.data.frame(x))){\n apply(x,2,function(data){\n as.numeric(sub(\"A|T\",1,sub(\"G|C\",2,data)));\n });\n } else if(is.vector(x)) {\n as.numeric(sub(\"A|T\",1,sub(\"G|C\",2,x)));\n } else {\n if((x = \"A\") || (x = \"T\")){\n 1;\n } else if((x = \"C\") || (x = \"G\")){\n 2;\n } else {\n 0;\n }\n }\n}\n\n## ## The following test suggests that this algorithm is tractable and\n## ## shouldn't need further optimisations:\n\n## ## 1) It is linear in complexity for number of markers [O(n)]\n\n## system.time(for(x in 1:10){oldicDiffSum(gt.df[-(1:x),])})\n## ## user system elapsed\n## ## 2.120 0.028 2.267\n## system.time(for(x in 1:100){oldicDiffSum(gt.df[-(1:x),])})\n## ## user system elapsed\n## ## 17.393 0.240 17.688\n\n## ## 2) Estimated runtime for chromosome 21 is less than half an\n## ## hour (actually, 16 minutes, 5435 markers)\n\n## ## > (5435/100 * 17.393) / 60\n## ## [1] 15.75516\n\n## ## [Estimated runtime for chromosome 1 is about 1.5 hours, 23062\n## ## markers]\n\n\ncat(\"Retrieving data for chromosome ...\");\ninFile <- gzfile(infile.name);\nopen(inFile);\nlineRead <- \"\";\nif(!hapmap3){\n while(lineRead != \"BEGINGENOTYPES\"){ # read until genotype start\n lineRead <- paste(scan(inFile, nlines = 1,\n what = character(0),\n quiet = TRUE)[1:2], collapse = \"\");\n }\n lineRead <- \"\";\n person.id <- \"\";\n gt.df <- NULL;\n while(lineRead != \"END GENOTYPES\"){ # read until genotype end\n lineRead <- readLines(inFile, n = 1, warn = FALSE);\n if(substr(lineRead,3,4) == \"id\"){\n person.id <- substr(lineRead,6,nchar(lineRead));\n hap.1 <- scan(inFile, nlines = 1, quiet = TRUE);\n hap.2 <- scan(inFile, nlines = 1, quiet = TRUE);\n new.df <- cbind(hap.1, hap.2);\n colnames(new.df) <- paste(person.id,c(1,2), sep = \".\");\n gt.df <- cbind(gt.df,new.df);\n }\n }\n colnames(gt.df) <- sub(\"0+([0-9][0-9]\\\\.)\",\"\\\\1\",\n colnames(gt.df), perl=TRUE);\n gt.df <- t(gt.df);\n} else { # if hapmap3-formatted input (but no header)\n gt.df <- read.table(inFile, row.names = 1, header = FALSE);\n gt.df <- gt.df[,-1];\n marker.names <- rownames(gt.df);\n gt.df <- data.frame(t(gt.df));\n}\nclose(inFile);\ncat(\"done\\n\");\ncat(\"Calculating distance matrix to eliminate identical chromosomes...\");\nif(hapmap3){\n dist.ind <- as.matrix(dist(gtval(gt.df), method = \"manhattan\"));\n} else {\n dist.ind <- as.matrix(dist(gt.df), method = \"manhattan\");\n}\nremove.columns <- NULL;\nfor(haplotype in 1:(dim(gt.df)[1])){\n ## if fewer than 20 differences, treat as the same chromosome\n ## this allows for some genotyping error\n if(length(which(which(dist.ind[haplotype,] < 20) > haplotype) > 0)){\n remove.columns <- c(remove.columns, (which(dist.ind[haplotype,] < 20))\n [which(dist.ind[haplotype,] < 20) > haplotype]);\n }\n}\nif(length(remove.columns) > 0){\n gt.df <- gt.df[,-remove.columns];\n}\ncat(\"done (\",length(unique(remove.columns)),\" columns removed)\\n\",sep=\"\");\noutFile <- file(outfile.name);\nopen(outFile, open = \"w\");\nfor(marker in 1:(dim(gt.df)[2])){\n cat(colnames(gt.df)[marker],\" \",icDiffSum(gt.df, marker),\n \"\\n\", file = outFile, sep = \"\");\n}\nclose(outFile);\n\n\n", "meta": {"hexsha": "c5e0a7d9d61f50c5be2566823ca961344272f543", "size": 9154, "ext": "r", "lang": "R", "max_stars_repo_path": "icdiff.r", "max_stars_repo_name": "gringer/bootstrap-subsampling", "max_stars_repo_head_hexsha": "9b794dbcd05e983dfd37bf46e39c5e873ed2ae37", "max_stars_repo_licenses": ["ISC"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "icdiff.r", "max_issues_repo_name": "gringer/bootstrap-subsampling", "max_issues_repo_head_hexsha": "9b794dbcd05e983dfd37bf46e39c5e873ed2ae37", "max_issues_repo_licenses": ["ISC"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "icdiff.r", "max_forks_repo_name": "gringer/bootstrap-subsampling", "max_forks_repo_head_hexsha": "9b794dbcd05e983dfd37bf46e39c5e873ed2ae37", "max_forks_repo_licenses": ["ISC"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-11-02T11:22:10.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-02T11:22:10.000Z", "avg_line_length": 33.0469314079, "max_line_length": 81, "alphanum_fraction": 0.5907799869, "num_tokens": 2626, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7090191214879992, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.38214940962875416}} {"text": "#!/usr/bin/env Rscript\n\n#===========================================================\n# R script for analyzing the statistical significance of interactions\n# this is an implementation of the paper Ay et. al. 2014 (FitHiC)\n# incorporates spline fit for raw contact count\n# also implements the bias calculation and the bias based filtering and spline fit procedure\n\n#Author: Sourya Bhattacharyya\n#Vijay-Ay lab, LJI\n#===========================================================\n\nlibrary(splines)\nlibrary(fdrtool)\nlibrary(parallel)\t# library for parallel processing\n\nlibrary(optparse)\n\n# #===========================\n# # parallel computation of binomial distribution on input vector\n# parallel.BinomDistr <- function(inpvec) {\n# \tidx <- inpvec[1]\n# \tcc <- inpvec[2]\n# \ttc <- inpvec[3]\n# \tcurrprob <- inpvec[4]\n\n# \tcurr_dbinom <- dbinom(cc, size=tc, prob=currprob)\n# \tcurr_pbinom <- pbinom(cc, size=tc, prob=currprob, lower.tail=FALSE)\n# \treturn c(idx, curr_dbinom, (curr_dbinom + curr_pbinom))\n# }\n\n# #===========================\n\noption_list = list(\n \tmake_option(c(\"--InpFile\"), type=\"character\", default=NULL, help=\"File with interactions + normalization features among individual genomic bins, preferably sorted with respect to interaction distance\"),\n \tmake_option(c(\"--headerInp\"), type=\"logical\", action=\"store_true\", default=FALSE, help=\"If TRUE, input interaction file has the header. Default FALSE.\"),\n\tmake_option(c(\"--OutFile\"), type=\"character\", default=NULL, help=\"Output file name storing interactions + probability, P value and Q value\"),\n\tmake_option(c(\"--P2P\"), type=\"integer\", action=\"store\", default=0, help=\"Can be 0 or 1. If 1, spline fit is modeled using only peak to peak interactions. Default 0.\"),\n \tmake_option(c(\"--EqLenBin\"), type=\"logical\", action=\"store_true\", default=FALSE, help=\"If TRUE, Equal length bins are used. Default FALSE, means that equal occupancy bins are used. Users need not alter this parameter\"),\n \tmake_option(c(\"--BiasCorr\"), type=\"integer\", action=\"store\", default=0, help=\"If 0, raw contact count is used. Else, bias corrected contact count is used before applying FitHiC. Default 0.\"),\n\tmake_option(c(\"--BiasLowThr\"), type=\"numeric\", default=0.2, help=\"Lower threshold of bias. Default 0.2\"),\n\tmake_option(c(\"--BiasHighThr\"), type=\"numeric\", default=5, help=\"Higher threshold of bias. Default 5\"), \t\n \tmake_option(c(\"--nbins\"), type=\"integer\", action=\"store\", default=200, help=\"Number of bins employed for FitHiC.\", metavar=\"nbins\"),\n \tmake_option(c(\"--Draw\"), type=\"logical\", action=\"store_true\", default=FALSE, help=\"If TRUE, spline fit of FitHiC is plotted. Default FALSE.\"),\n \tmake_option(c(\"--cccol\"), type=\"integer\", action=\"store\", default=7, help=\"Column number of the file storing the contact count\"),\n \tmake_option(c(\"--TimeFile\"), type=\"character\", default=NULL, help=\"If specified, denotes the file which will contain time profiling information\"),\n \tmake_option(c(\"--BiasFilt\"), type=\"integer\", action=\"store\", default=0, help=\"If 1, interactions are filtered according to BiasLowThr and BiasHighThr, before processing. Default 0\"),\n\tmake_option(c(\"--ProbBias\"), type=\"integer\", action=\"store\", default=0, help=\"If 1, probability values are multiplied with the bias values. Default 0.\")\n); \n \nopt_parser = OptionParser(option_list=option_list);\nopt = parse_args(opt_parser);\n\nnbins <- as.integer(opt$nbins) # number of bins used in FitHiC\nif (is.null(opt$TimeFile)) {\n\ttimeprof <- 0\n} else {\n\ttimeprof <- 1\n}\n\n# peak to peak background usage option\nPeak2PeakBackg <- as.integer(opt$P2P)\ncat(sprintf(\"\\n Peak to peak background usage for spline fit: %s \", Peak2PeakBackg))\n\n# number of processors within the system\nncore <- detectCores()\ncat(sprintf(\"\\n Number of cores in the system: %s \", ncore))\n\n# directory containing the input interaction file\ninpdir <- dirname(opt$InpFile)\n\n# directory to contain the spline fitted output interaction file\nOutIntDir <- dirname(opt$OutFile)\n\n# this directory will store the spline graph according to the model\noutdir <- paste0(OutIntDir,'/Results')\nsystem(paste('mkdir -p', outdir))\n\n# this file stores the spline fitted model\nif (opt$EqLenBin) {\n\tplotfile <- paste0(outdir,'/','EqLenBin_SplinePass1.pdf')\n} else {\n\tplotfile <- paste0(outdir,'/','EqOccBin_SplinePass1.pdf')\t\n}\n\nif (timeprof == 1) {\n\tstarttime <- Sys.time()\n}\n\n# load the interaction data matrix\n# Note: the data has a header information\ninteraction.data <- read.table(opt$InpFile, header=opt$headerInp)\nif (opt$headerInp == FALSE) {\n\tcolnames(interaction.data) <- c(\"chr1\", \"s1\", \"e1\", \"chr2\", \"s2\", \"e2\", \"cc\", \"d1\", \"isPeak1\", \"Bias1\", \"mapp1\", \"gc1\", \"cut1\", \"d2\", \"isPeak2\", \"Bias2\", \"mapp2\", \"gc2\", \"cut2\")\t\n}\n\nif (timeprof == 1) {\n\tendtime <- Sys.time()\n\tfp <- file(opt$TimeFile, open=\"a\")\n\toutstr <- paste('\\n Time to load the interaction data file in the R structure: ', (endtime - starttime))\n\twrite(outstr, file=fp, append=T)\n\tclose(fp)\n}\n\ncat(sprintf(\"\\n Number of unfiltered interactions: %s \", nrow(interaction.data)))\n\n# return if the number of interaction is 0\nif (nrow(interaction.data) == 0) {\n\tcat(sprintf(\"\\n No of interactions : 0 - exit !!!\"))\n\treturn()\n}\n\nif (ncol(interaction.data) < opt$cccol) {\n\tcat(sprintf(\"\\n There is no contact count column or the formatting of the input file has problems - exit !!!\"))\n\treturn()\n}\n\n# vector of initial (prior) probabilities for contact counts\nProb_Val <- c()\n\n# probability of the observed contact count for a single locus pair, from the spline fit\nSpline_Binom_Prob_CC <- c()\n\n# P-value of the observed contact count for a single locus pair\n# binomial distribution + spline based estimation\nSpline_Binom_P_Val_CC <- c()\n\n# for each bin, count the no of distinct locus pairs\nno_distinct_loci <- c()\n\n# for each bin, no of observed contacts\nNumContact <- c()\n\n# for each bin, stores the average contact count per locus pair\navg_contact <- c()\n\n# prior contact probability for a specific locus pair falling within a bin\nprior_contact_prob <- c()\n\n# average interaction distance for all locus pairs falling within a bin\navg_int_dist <- c()\n\n#======================================================\n# if normalization using bias values is enabled \n# then discard the interactions where either loci has bias values outside specified thresholds\nif ((opt$BiasCorr == 1) & (opt$BiasFilt == 1)) {\n\t\n\t# specifying the columns in the interaction data \n\t# where the bias information is provided\n\tbias1.col <- 10\n\tbias2.col <- 16\n\n\tif (ncol(interaction.data) >= bias2.col) {\n\t\tinteraction.data <- interaction.data[which((interaction.data[,bias1.col] >= opt$BiasLowThr) & (interaction.data[,bias1.col] <= opt$BiasHighThr) & (interaction.data[,bias2.col] >= opt$BiasLowThr) & (interaction.data[,bias2.col] <= opt$BiasHighThr)), ]\n\t\tcat(sprintf(\"\\n Bias specific filtering is enabled - Number of interactions where both loci satisfy bias criterion: %s \", nrow(interaction.data)))\n\t}\n}\n\n#======================================================\n# absolute genomic distance for an interaction instance\ngene.dist <- abs(interaction.data[,2] - interaction.data[,5])\n\n# no of interactions pairs\nnumPairs <- length(gene.dist)\ncat(sprintf(\"\\n *** Total number of interactions: %s \", numPairs))\n\n# total number of contacts for all the interactions\nTotContact <- sum(interaction.data[,opt$cccol])\n\nif (timeprof == 1) {\n\tstarttime <- Sys.time()\n}\n\n#======================================================\n# add - sourya\n# we form the training data out of the total number of interactions\n# if --P2P is enabled, training data consists of only peak to peak interactions\n# else training data consists of the complete interaction set\nif ((Peak2PeakBackg == 1) & (ncol(interaction.data) >= 15)) {\n\tTrainingData <- interaction.data[which((interaction.data[,9] == 1) & (interaction.data[,15] == 1)), ]\n\t# append the interaction distance as the last column of the training data\n\tTrainingData <- cbind(TrainingData, abs(TrainingData[,2] - TrainingData[,5]))\n\t# now sort the data with respect to increasing interaction distance\n\tTrainingData <- TrainingData[order( TrainingData[,ncol(TrainingData)] ), ]\n\t# remove the last column\n\tTrainingData <- TrainingData[,1:(ncol(TrainingData)-1)]\n} else {\n\tTrainingData <- interaction.data\n}\n\nnumTrainingPairs <- nrow(TrainingData)\nif (numTrainingPairs == 0) {\n\tcat(sprintf(\"\\n No training data for FitHiC spline fit - error - return !!! \"))\n\treturn()\n}\n\ncat(sprintf(\"\\n *** Total number of training interactions: %s \", numTrainingPairs))\n\n# interaction distance vector for the training data only\nTrainingdata_GeneDist <- abs(TrainingData[,2] - TrainingData[,5])\n\n# contact count sum for the training data\nTotTrainingDataContact <- sum(TrainingData[,opt$cccol])\n\n#=====================================================\n# divide the genomic distance into b quantiles (number of bins)\n\n# Note: for equal length bins (opt$EqLenBin is TRUE), each bin would have equal no of entries (pairs of loci)\n# from the training data\n# on the other hand, for equal occupancy bins (opt$EqLenBin is FALSE), each bin would have equal no of contact count\n# from the training data\n# In both cases, however, corresponding bin intervals will be variable\n\n# error condition - sourya\n# if the number of interactions is less than the argument 'nbins'\n# then re-adjust the values of nbins and then assign the \n# no of entries in each of the bins\n\nif (opt$EqLenBin) {\n\t# no of entries (occupancies) for each bin \n\t# each bin have same no of locus pairs\n\tif (numTrainingPairs < nbins) {\n\t\tnbins <- numTrainingPairs\n\t\tnentry <- 1\n\t} else {\n\t\tnentry <- floor(numTrainingPairs / nbins)\n\t}\n} else {\n\t# no of contacts for each bin\n\t# each bin have same no of contacts\n\tif (TotTrainingDataContact < nbins) {\n\t\tnbins <- numTrainingPairs\n\t}\n\tncontactbin <- floor(TotTrainingDataContact / nbins)\n}\n\n#==============================================\n\nif (opt$EqLenBin) {\n\t# equal length bin case (equal locus entries)\n\tfor (bin_idx in (1:nbins)) {\n\t\tsi <- (bin_idx - 1) * nentry + 1\n\t\tif (bin_idx < nbins) {\n\t\t\tei <- si + nentry - 1\t\t\n\t\t} else {\n\t\t\tei <- numTrainingPairs\t# last read\n\t\t}\n\t\tno_distinct_loci[bin_idx] <- (ei-si+1)\n\t\tNumContact[bin_idx] <- sum(TrainingData[si:ei,opt$cccol])\n\t\tavg_contact[bin_idx] <- NumContact[bin_idx] / no_distinct_loci[bin_idx]\n\t\tprior_contact_prob[bin_idx] <- (avg_contact[bin_idx] / TotTrainingDataContact)\n\t\tavg_int_dist[bin_idx] <- mean(Trainingdata_GeneDist[si:ei])\n\t}\n} else {\n\t# equal occupancy (contact count) bin - preferred\n\n\t# keeps track of total no of contact counts for a particular bin\n\tcumContactCount <- 0\n\tnelem <- 0\n\tei <- 0\n\tbin_idx <- 0\n\n\t# keeps track of the no of different genomic distance values encountered within this bin\n\t# and also the no of elements (locus pairs) having that particular genomic distance\n\tValGeneDist <- c()\n\tnelemSameGeneDist <- c()\n\n\twhile (ei < numTrainingPairs) {\n\t\tsi <- ei + 1\n\t\tcurr_gene_dist <- abs(TrainingData[si,2] - TrainingData[si,5])\n\t\tidx_list <- which(Trainingdata_GeneDist == curr_gene_dist)\n\t\tnelem <- nelem + length(idx_list)\n\t\tei <- ei + length(idx_list)\n\t\tcumContactCount <- cumContactCount + sum(TrainingData[si:ei, opt$cccol])\n\t\t\n\t\tValGeneDist <- c(ValGeneDist, curr_gene_dist)\n\t\tnelemSameGeneDist <- c(nelemSameGeneDist, length(idx_list))\n\n\t\tif (cumContactCount >= ncontactbin) {\n\t\t\t# current cumulative contact exceeds the expected average contact per bin\n\t\t\t# and also, all the contacts with this specified genomic distance is covered\n\t\t\t# so, we fix this bin \n\t\t\tbin_idx <- bin_idx + 1\n\t\t\tno_distinct_loci[bin_idx] <- nelem\n\t\t\tNumContact[bin_idx] <- cumContactCount\n\t\t\tavg_contact[bin_idx] <- cumContactCount / nelem\n\t\t\tprior_contact_prob[bin_idx] <- (avg_contact[bin_idx] / TotTrainingDataContact)\n\n\t\t\tavg_int_dist[bin_idx] <- 0\n\t\t\tfor (j in (1:length(ValGeneDist))) {\n\t\t\t\tavg_int_dist[bin_idx] <- avg_int_dist[bin_idx] + ((nelemSameGeneDist[j] * 1.0) / nelem) * ValGeneDist[j]\n\t\t\t}\n\n\t\t\t# reset the couners\n\t\t\tcumContactCount <- 0\n\t\t \tValGeneDist <- c()\n\t\t \tnelemSameGeneDist <- c()\n\t\t \tnelem <- 0\n\t\t}\n\t}\n\t# now dump the data in a text file\n\tOutBinfile <- paste0(OutIntDir, '/', 'Bin_Info.log')\n\twrite.table(cbind(avg_int_dist, no_distinct_loci, NumContact, avg_contact, prior_contact_prob), OutBinfile, row.names = FALSE, col.names = c(\"AvgDist\",\"NumLoci\",\"NumContact\",\"AvgContact\",\"PriorProb\"), sep = \"\\t\", quote=FALSE, append=FALSE)\t\n}\n\ncat(sprintf(\"\\n after printing the bin log file\"))\n\n#=====================================\n# now prepare a spline fit where x axis is the 'avg_int_dist'\n# and y axis is the 'prior_contact_prob'\n#=====================================\n\n# # the first spline works according to the specified degree of freedom (16 - for testing)\n# fit <- smooth.spline(avg_int_dist, prior_contact_prob, df=16)\n\n# if (timeprof == 1) {\n# \tendtime <- Sys.time()\n# \tfp <- file(opt$TimeFile, open=\"a\")\n# \toutstr <- paste('\\n Time for spline (df=16): ', (endtime - starttime))\n# \twrite(outstr, file=fp, append=T)\n# \tclose(fp)\n# \tstarttime <- Sys.time()\n# }\n\n# the spline works according to the cross validation principle\nfit2 <- smooth.spline(avg_int_dist, prior_contact_prob, cv=TRUE)\n\nif (timeprof == 1) {\n\tendtime <- Sys.time()\n\tfp <- file(opt$TimeFile, open=\"a\")\n\toutstr <- paste('\\n Time for spline (CV): ', (endtime - starttime))\n\twrite(outstr, file=fp, append=T)\n\tclose(fp)\n\tstarttime <- Sys.time()\n}\n\n# # perform anti-tonic regression on the first spline\n# fit.mr <- monoreg(fit$x, fit$y, type=\"antitonic\")\n\n# if (timeprof == 1) {\n# \tendtime <- Sys.time()\n# \tfp <- file(opt$TimeFile, open=\"a\")\n# \toutstr <- paste('\\n Time for antitonic regression on spline (df = 16): ', (endtime - starttime))\n# \twrite(outstr, file=fp, append=T)\n# \tclose(fp)\n# \tstarttime <- Sys.time()\n# }\n\n# perform anti-tonic regression on the second spline\n# antitonic = monotonic decreasing (as the probability decreases with increasing distance)\nfit2.mr <- monoreg(fit2$x, fit2$y, type=\"antitonic\")\n\nif (timeprof == 1) {\n\tendtime <- Sys.time()\n\tfp <- file(opt$TimeFile, open=\"a\")\n\toutstr <- paste('\\n Time for antitonic regression on spline (CV): ', (endtime - starttime))\n\twrite(outstr, file=fp, append=T)\n\tclose(fp)\n}\n\n# # plot the data, if plotting is enabled via the parameter opt$Draw\n# if (opt$Draw) {\n# \tpdf(plotfile, width=14, height=10)\n# \tplot(avg_int_dist, prior_contact_prob, cex=0.5, col=\"darkgrey\", xlab=\"Average interaction distance\", ylab=\"Prior contact probability\")\n# \ttitle(\"Smooth spline - antitonic regression - pass 1\")\n# \tlines(fit.mr, col=\"red\", lwd=2)\n# \tlines(fit2.mr, col=\"blue\", lwd=2)\n# \tlegend(\"topright\",legend=c(\"16 DF\", paste(as.integer(fit2$df), \"df (cv)\")), col=c(\"red\", \"blue\"), lty=1, lwd=2, cex=0.8)\n# \tdev.off()\t\t\n# }\n\n#=========================\n# now use this fitted spline\n# to get predicted probability values for all distance values of the interactions\n# in the unit of bin size employed in the current file)\nbinsize <- abs(interaction.data[1,2] - interaction.data[1,5])\nTestDistVal <- seq(min(gene.dist), max(gene.dist), binsize)\n\n# probability obtained from the spline\npp.fit2 <- predict(fit2, TestDistVal)\n\n# use this computed probability and the input distance to fit a spline again\nfit2_new <- smooth.spline(pp.fit2$x, pp.fit2$y, cv=TRUE)\n\n# perform antitonic regression on this spline\nfit2_new.mr <- monoreg(fit2_new$x, fit2_new$y, type=\"antitonic\")\n\n# plot the fitted spline and the smoothing regression\nif (opt$Draw) {\n\tplotfile1 <- paste0(outdir,'/','EqOccBin_SplinePass1.pdf')\t\n\tpdf(plotfile1, width=10, height=8)\n\tplot(avg_int_dist, prior_contact_prob, cex=0.5, col=\"black\", xlab=\"Average interaction distance\", ylab=\"Prior contact probability\", xlim=c(0, max(gene.dist)))\n\tlines(fit2$x, fit2$y, col=\"yellow\", lwd=0.5)\n\tlines(fit2.mr$x, fit2.mr$yf, col=\"blue\", lwd=0.5)\n\tlines(fit2_new$x, fit2_new$y, col=\"green\", lwd=0.5)\n\tlines(fit2_new.mr$x, fit2_new.mr$yf, col=\"red\", lwd=0.5)\n\tlegend(\"topright\",legend=c(paste(\"spline (fit2) - \", as.integer(fit2$df), \"df (cv)\"), \"MR on spline (fit2.mr)\", paste(\"5 Kb uniform spline (fit2_new) - \", as.integer(fit2_new$df), \"df (cv)\"), \"MR on 5 Kb uniform spline (fit2_new.mr)\"), col=c(\"yellow\", \"blue\", \"green\", \"red\"), lty=1, lwd=1, cex=0.8)\n\ttitle(\"Smooth spline - antitonic regression - pass 1\")\n\tdev.off()\n}\n\n# plot the fitted spline and the smoothing regression\n# in log scale\nif (opt$Draw) {\n\tplotfile1 <- paste0(outdir,'/','EqOccBin_SplinePass1_LOGScale.pdf')\t\n\tpdf(plotfile1, width=10, height=8)\n\tplot(avg_int_dist, log10(prior_contact_prob), cex=0.5, col=\"black\", xlab=\"Average interaction distance\", ylab=\"Prior contact probability (log)\", xlim=c(0, max(gene.dist)))\n\tlines(fit2$x, log10(fit2$y), col=\"yellow\", lwd=0.5)\n\tlines(fit2.mr$x, log10(fit2.mr$yf), col=\"blue\", lwd=0.5)\n\tlines(fit2_new$x, log10(fit2_new$y), col=\"green\", lwd=0.5)\n\tlines(fit2_new.mr$x, log10(fit2_new.mr$yf), col=\"red\", lwd=0.5)\n\tlegend(\"topright\",legend=c(paste(\"spline (fit2) - \", as.integer(fit2$df), \"df (cv)\"), \"MR on spline (fit2.mr)\", paste(\"5 Kb uniform spline (fit2_new) - \", as.integer(fit2_new$df), \"df (cv)\"), \"MR on 5 Kb uniform spline (fit2_new.mr)\"), col=c(\"yellow\", \"blue\", \"green\", \"red\"), lty=1, lwd=1, cex=0.8)\n\ttitle(\"Smooth spline - antitonic regression - pass 1 - log scale\")\n\tdev.off()\n}\n\n# create a data frame to write the old spline and old MR regression results\nold_sample.df <- cbind.data.frame(fit2$x, fit2$y, fit2.mr$x, fit2.mr$yf)\ncolnames(old_sample.df) <- c('fit2$x', 'fit2$y', 'fit2.mr$x', 'fit2.mr$yf')\nwrite.table(old_sample.df, paste0(outdir,'/EqOccBin_OldSpline_Regression.txt'), row.names = FALSE, col.names = TRUE, sep = \"\\t\", quote=FALSE, append=FALSE)\n\n# create a data frame to write the old spline and old MR regression results\nnew_sample.df <- cbind.data.frame(fit2_new$x, fit2_new$y, fit2_new.mr$x, fit2_new.mr$yf)\ncolnames(new_sample.df) <- c('fit2_new$x', 'fit2_new$y', 'fit2_new.mr$x', 'fit2_new.mr$yf')\nwrite.table(new_sample.df, paste0(outdir,'/EqOccBin_NewSpline_Regression.txt'), row.names = FALSE, col.names = TRUE, sep = \"\\t\", quote=FALSE, append=FALSE)\n\n#--------------------------------------------\n# Paper: Ferhat Ay, 2014\n# the probability is computed with respect to the spline plot\n# which is then substituted to the binomial distribution, for P-value estimation\n\nif (is.unsorted(gene.dist) == TRUE) {\n\n\tcat(sprintf(\"\\n **** The interaction file is unsorted --- check ****\"))\n\n\t# here the genomic distance is unsorted\n\t# so we employ the predict function and probability distribution computation\n\t# for the complete array\n\n\t# get the spline interpolation prediction from the already modeled smoothing spline object (CV spline)\n\t# with respect to the input genomic distance vector\n\t# the returned value is a component of 2 fields: (x,y)\n\t# where x is the input data and y is the predicted data\n\t\n\t# input will be the genomic distance\n\t# output is the corresponding contact probability \n\n\t# note: the probability was computed with respect to 'numPairs' placed as the denominator\n\t# accordingly we modify the binomial distribution equation\n\n\t# predict from the new spline fit - sourya\n\t# pp <- predict(fit2, gene.dist)\n\tpp <- predict(fit2_new, gene.dist)\n\n\tfor (k in (1:numPairs)) {\n\t\t# probability for this particular interaction is in the y field\n\t\tp <- pp$y[k]\n\t\tif (opt$BiasCorr == 0) {\n\t\t\t# model binomial distribution with this probability\n\t\t\tSpline_Binom_Prob_CC[k] <- dbinom(interaction.data[k, opt$cccol], size=TotContact, prob=p)\n\t\t\t# compute the p value with respect to the modified distribution\n\t\t\tSpline_Binom_P_Val_CC[k] <- pbinom(interaction.data[k, opt$cccol], size=TotContact, prob=p, lower.tail=FALSE) + Spline_Binom_Prob_CC[k]\n\t\t\t# store the prior probability\n\t\t\tProb_Val[k] <- p\n\t\t} else {\n\t\t\t# model binomial distribution with the product of probability, and the bias values of two segments\n\t\t\tif (opt$ProbBias == 1) {\n\t\t\t\tcurr_prob <- p * interaction.data[k, bias1.col] * interaction.data[k, bias2.col]\t\n\t\t\t} else {\n\t\t\t\tcurr_prob <- p\n\t\t\t}\n\t\t\tSpline_Binom_Prob_CC[k] <- dbinom(interaction.data[k, opt$cccol], size=TotContact, prob=curr_prob)\n\t\t\t# compute the p value with respect to the modified distribution\n\t\t\tSpline_Binom_P_Val_CC[k] <- pbinom(interaction.data[k, opt$cccol], size=TotContact, prob=curr_prob, lower.tail=FALSE) + Spline_Binom_Prob_CC[k]\n\t\t\t# store the prior probability\n\t\t\tProb_Val[k] <- p\n\t\t}\n\t}\n} else {\n\n\tif (timeprof == 1) {\n\t\tstarttime <- Sys.time()\n\t}\n\n\t# here the genomic distance is sorted\n\t# so we selectively apply the predict function to only the distinct elements of the list\n\tuniq.idx <- order(gene.dist)[!duplicated(gene.dist)]\n\n\tif (timeprof == 1) {\n\t\tendtime <- Sys.time()\n\t\tfp <- file(opt$TimeFile, open=\"a\")\n\t\toutstr <- paste('\\n Time to find unique indices in genomic distance: ', (endtime - starttime))\n\t\twrite(outstr, file=fp, append=T)\n\t\tclose(fp)\n\t}\n\n\tif (timeprof == 1) {\n\t\tstarttime <- Sys.time()\n\t}\n\n\tfor (k in (1:length(uniq.idx))) {\n\t\t# all the locations from si to ei will have the same probability \n\t\t# since the gene distance value is the same\n\t\tsi <- uniq.idx[k]\n\t\tif (k < length(uniq.idx)) {\n\t\t\tei <- uniq.idx[k+1] - 1\n\t\t} else {\n\t\t\tei <- numPairs\t# last read\t\n\t\t}\n\t\t# compute the probability according to the genomic distance (of the start location - single element)\n\t\t# this probability value will be used for all the values within the interval (si to ei)\n\t\t\n\t\t# predict from the new spline fit - sourya\n\t\t# pp <- predict(fit2, gene.dist[si])\n\t\tpp <- predict(fit2_new, gene.dist[si])\n\t\tp <- pp$y\n\n\t\t#==========================\n\t\t# compute the probability distribution for the current interval\n\t\t#==========================\n\t\tif (opt$BiasCorr == 0) {\n\t\t\tcurr_dbinom <- dbinom(interaction.data[si:ei, opt$cccol], size=TotContact, prob=p)\n\t\t\tcurr_pbinom <- pbinom(interaction.data[si:ei, opt$cccol], size=TotContact, prob=p, lower.tail=FALSE)\n\t\t\t# append the distribution to the final vector\n\t\t \tSpline_Binom_Prob_CC <- c(Spline_Binom_Prob_CC, curr_dbinom)\n\t\t \tSpline_Binom_P_Val_CC <- c(Spline_Binom_P_Val_CC, (curr_dbinom + curr_pbinom))\t\n\t\t \t# store the prior probability as well\n\t\t \tProb_Val[si:ei] <- p\n\t\t} else {\n\t\t\t# bias based probability correction\n\n\t\t\t# comment - sourya\n\t\t\t# for (idx in (si:ei)) {\n\t\t\t# \t# model binomial distribution with the product of probability, and the bias values of two segments\n\t\t\t# \tcurr_prob <- p * interaction.data[idx, (opt$cccol + 1)] * interaction.data[idx, (opt$cccol + 3)]\n\t\t\t# \tcurr_dbinom <- dbinom(interaction.data[idx, opt$cccol], size=TotContact, prob=curr_prob)\n\t\t\t# \tcurr_pbinom <- pbinom(interaction.data[idx, opt$cccol], size=TotContact, prob=curr_prob, lower.tail=FALSE)\n\t\t\t# \t# append the distribution to the final vector\n\t\t\t# \tSpline_Binom_Prob_CC[idx] <- curr_dbinom\n\t\t\t# \tSpline_Binom_P_Val_CC[idx] <- (curr_dbinom + curr_pbinom)\t\n\t\t\t# \t# store the prior probability as well\n\t\t \t\t# Prob_Val[idx] <- curr_prob\n\t\t\t# }\n\n\t\t\t# add - sourya\n\n\t\t\t# cat(sprintf(\"\\n *** Before executing Parallel from si: %s to ei: %s \", si, ei))\n\n\t\t\t# now apply this matrix on the parallel version of binomial distribution computation\n\t\t\t# the second argument 1 means that individual rows of matrix is processed \n\t\t\t# in the parallel computation\n\t\t\tresult_binomdistr <- as.data.frame(parallel:::mclapply( si:ei , mc.cores = ncore , function(idx){\n\t\t\t\tcc <- interaction.data[idx, opt$cccol]\n\t\t\t\tif (opt$ProbBias == 1) {\n\t\t\t\t\tpr <- p * interaction.data[idx, bias1.col] * interaction.data[idx, bias2.col]\n\t\t\t\t} else {\n\t\t\t\t\tpr <- p\n\t\t\t\t}\n\t\t\t\tdb <- dbinom(cc, size=TotContact, prob=pr)\n\t\t\t\tpb <- pbinom(cc, size=TotContact, prob=pr, lower.tail=FALSE)\n\t\t\t\treturn(c(idx,pr,db,(db+pb)))\n\t\t\t\t} ))\n\n\t\t\t# cat(sprintf(\"\\n *** rows: %s columns: %s \", nrow(result_binomdistr), ncol(result_binomdistr)))\n\n\t\t\t# copy the results\n\t\t\t# columns : si to ei\n\t\t\t# rows: 4 \n\t\t\t# for (i in (1:ncol(result_binomdistr))) {\n\t\t\t# \tidx <- result_binomdistr[1,i]\n\t\t\t# \tProb_Val[idx] <- result_binomdistr[2,i]\n\t\t\t# \tSpline_Binom_Prob_CC[idx] <- result_binomdistr[3,i]\n\t\t\t# \tSpline_Binom_P_Val_CC[idx] <- result_binomdistr[4,i]\n\t\t\t# }\n\t\t\tProb_Val[si:ei] <- as.double(result_binomdistr[2,1:ncol(result_binomdistr)])\n\t\t\tSpline_Binom_Prob_CC[si:ei] <- as.double(result_binomdistr[3,1:ncol(result_binomdistr)])\n\t\t\tSpline_Binom_P_Val_CC[si:ei] <- as.double(result_binomdistr[4,1:ncol(result_binomdistr)])\n\n\t\t\t# end add - Sourya\n\t\t}\n\t}\n\n\tif (timeprof == 1) {\n\t\tendtime <- Sys.time()\n\t\tfp <- file(opt$TimeFile, open=\"a\")\n\t\toutstr <- paste('\\n Time for Spline based distribution compute (p value) (sorted interaction file): ', (endtime - starttime))\n\t\twrite(outstr, file=fp, append=T)\n\t\tclose(fp)\n\t}\n}\n\nif (timeprof == 1) {\n\tstarttime <- Sys.time()\n}\n\n# from the generated P values, obtain the Q value using BH correction\nSpline_Binom_QVal <- p.adjust(Spline_Binom_P_Val_CC, method = \"BH\")\t\n\nif (timeprof == 1) {\n\tendtime <- Sys.time()\n\tfp <- file(opt$TimeFile, open=\"a\")\n\toutstr <- paste('\\n Time to compute Q value (from P value) in spline: ', (endtime - starttime))\n\twrite(outstr, file=fp, append=T)\n\tclose(fp)\n}\n\nif (timeprof == 1) {\n\tstarttime <- Sys.time()\n}\n\n# accumulate all results - also add header information\nFinalData <- cbind(interaction.data, Prob_Val, Spline_Binom_Prob_CC, Spline_Binom_P_Val_CC, Spline_Binom_QVal)\ncolnames(FinalData) <- c(colnames(interaction.data), \"p\", \"dbinom\", \"P-Value\", \"Q-Value\")\n\n#===================================\n# add - sourya - debug\n# scan through individual genomic distance\n# and plot the number of contacts / interactions for each distance\nqval_thr <- 0.01\nuniq_gene_dist <- sort(unique(gene.dist))\n\n# distance specific contact count and no of interactions\nunfilt_cc_dist <- c()\nfilt_cc_dist <- c()\nunfilt_p2p_cc_dist <- c()\nfilt_p2p_cc_dist <- c()\nunfilt_int_dist <- c()\nfilt_int_dist <- c()\nunfilt_p2p_int_dist <- c()\nfilt_p2p_int_dist <- c()\n\nfor (i in 1:length(uniq_gene_dist)) {\n\tcurr_dist <- uniq_gene_dist[i]\n\tcurr_dist_unfilt_int_idx <- which(abs(FinalData[,2] - FinalData[,5]) == curr_dist)\n\tcurr_dist_filt_int_idx <- which((abs(FinalData[,2] - FinalData[,5]) == curr_dist) & (FinalData[,ncol(FinalData)] < qval_thr))\n\t\n\tif (ncol(interaction.data) >= 15) {\n\t\tcurr_dist_unfilt_p2p_idx <- which((abs(FinalData[,2] - FinalData[,5]) == curr_dist) & (FinalData[,9] == 1) & (FinalData[,15] == 1))\n\t\tcurr_dist_filt_p2p_idx <- which((abs(FinalData[,2] - FinalData[,5]) == curr_dist) & (FinalData[,9] == 1) & (FinalData[,15] == 1) & (FinalData[,ncol(FinalData)] < qval_thr))\t\t\n\t}\n\n\tunfilt_int_dist <- c(unfilt_int_dist, length(curr_dist_unfilt_int_idx))\n\tunfilt_cc_dist <- c(unfilt_cc_dist, sum(FinalData[curr_dist_unfilt_int_idx, 7]))\n\tfilt_int_dist <- c(filt_int_dist, length(curr_dist_filt_int_idx))\n\tfilt_cc_dist <- c(filt_cc_dist, sum(FinalData[curr_dist_filt_int_idx, 7]))\n\n\tif (ncol(interaction.data) >= 15) {\n\t\tunfilt_p2p_int_dist <- c(unfilt_p2p_int_dist, length(curr_dist_unfilt_p2p_idx))\n\t\tunfilt_p2p_cc_dist <- c(unfilt_p2p_cc_dist, sum(FinalData[curr_dist_unfilt_p2p_idx, 7]))\n\t\tfilt_p2p_int_dist <- c(filt_p2p_int_dist, length(curr_dist_filt_p2p_idx))\n\t\tfilt_p2p_cc_dist <- c(filt_p2p_cc_dist, sum(FinalData[curr_dist_filt_p2p_idx, 7]))\t\n\t}\n}\n\nx <- sum(unfilt_cc_dist)\nunfilt_cc_dist_frac <- unfilt_cc_dist / (x * 1.0)\n\nx <- sum(filt_cc_dist)\nfilt_cc_dist_frac <- filt_cc_dist / (x * 1.0)\n\nx <- sum(unfilt_int_dist)\nunfilt_int_dist_frac <- unfilt_int_dist / (x * 1.0)\n\nx <- sum(filt_int_dist)\nfilt_int_dist_frac <- filt_int_dist / (x * 1.0)\n\nif (ncol(interaction.data) >= 15) {\n\t\n\tx <- sum(unfilt_p2p_cc_dist)\n\tunfilt_p2p_cc_dist_frac <- unfilt_p2p_cc_dist / (x * 1.0)\n\n\tx <- sum(filt_p2p_cc_dist)\n\tfilt_p2p_cc_dist_frac <- filt_p2p_cc_dist / (x * 1.0)\n\n\tx <- sum(unfilt_p2p_int_dist)\n\tunfilt_p2p_int_dist_frac <- unfilt_p2p_int_dist / (x * 1.0)\n\n\tx <- sum(filt_p2p_int_dist)\n\tfilt_p2p_int_dist_frac <- filt_p2p_int_dist / (x * 1.0)\n\n\tout.df <- cbind.data.frame(uniq_gene_dist, unfilt_int_dist, unfilt_int_dist_frac, unfilt_cc_dist, unfilt_cc_dist_frac, unfilt_p2p_int_dist, unfilt_p2p_int_dist_frac, unfilt_p2p_cc_dist, unfilt_p2p_cc_dist_frac, filt_int_dist, filt_int_dist_frac, filt_cc_dist, filt_cc_dist_frac, filt_p2p_int_dist, filt_p2p_int_dist_frac, filt_p2p_cc_dist, filt_p2p_cc_dist_frac)\t\n\n\tcolnamevec <- c(\"dist\", \"U-Num\", \"%U-Num\", \"U-CC\", \"%U-CC\", \"U-P2P-Num\", \"%U-P2P-Num\", \"U-P2P-CC\", \"%U-P2P-CC\", \"F-Num\", \"%F-Num\", \"F-CC\", \"%F-CC\", \"F-P2P-Num\", \"%F-P2P-Num\", \"F-P2P-CC\", \"%F-P2P-CC\")\t\n} else {\n\tout.df <- cbind.data.frame(uniq_gene_dist, unfilt_int_dist, unfilt_int_dist_frac, unfilt_cc_dist, unfilt_cc_dist_frac, filt_int_dist, filt_int_dist_frac, filt_cc_dist, filt_cc_dist_frac)\n\tcolnamevec <- c(\"dist\", \"U-Num\", \"%U-Num\", \"U-CC\", \"%U-CC\", \"F-Num\", \"%F-Num\", \"F-CC\", \"%F-CC\")\t\n}\n\ncolnames(out.df) <- colnamevec\nwrite.table(out.df, paste0(outdir, '/Count_Summary.txt'), row.names = FALSE, col.names = TRUE, sep = \"\\t\", quote=FALSE, append=FALSE)\n\ncolorvec <- c(\"black\", \"yellow\", \"blue\", \"green\", \"red\", \"brown\", \"magenta\", \"cyan\")\n\nplotfile1 <- paste0(outdir,'/Count_Summary.pdf')\t\npdf(plotfile1, width=10, height=8)\nplot(out.df[,1], out.df[,3], cex=0.5, col=colorvec[1], type=\"l\", xlab=\"Distance\", ylab=\"Percentage\")\nlines(out.df[,1], out.df[,5], col=colorvec[2], lwd=0.5)\nlines(out.df[,1], out.df[,7], col=colorvec[3], lwd=0.5)\nlines(out.df[,1], out.df[,9], col=colorvec[4], lwd=0.5)\n\nif (ncol(interaction.data) >= 15) {\n\tlines(out.df[,1], out.df[,11], col=colorvec[5], lwd=0.5)\n\tlines(out.df[,1], out.df[,13], col=colorvec[6], lwd=0.5)\n\tlines(out.df[,1], out.df[,15], col=colorvec[7], lwd=0.5)\n\tlines(out.df[,1], out.df[,17], col=colorvec[8], lwd=0.5)\n}\n\nif (ncol(interaction.data) >= 15) {\n\tlegendvec <- c(colnamevec[3], colnamevec[5], colnamevec[7], colnamevec[9], colnamevec[11], colnamevec[13], colnamevec[15], colnamevec[17])\n} else {\n\tlegendvec <- c(colnamevec[3], colnamevec[5], colnamevec[7], colnamevec[9])\n}\n\nlegend(\"topright\",legend=legendvec, col=colorvec, lty=1, lwd=1, cex=0.8)\ntitle(\"% of different quantities\")\ndev.off()\n# end add - sourya - debug\n#===================================\n\n\n# append the Spline distribution probability and corresponding P value as separate columns\n# and write in a separate text file\ntemp_outfile <- paste0(OutIntDir, '/', 'temp_out.bed')\nwrite.table(FinalData, temp_outfile, row.names = FALSE, col.names = TRUE, sep = \"\\t\", quote=FALSE, append=FALSE) \n\n# now sort the file contents and write that in the final specified output file\nsystem(paste('sort -k1,1 -k2,2n -k5,5n', paste0('-k',opt$cccol,',',opt$cccol,'nr'), temp_outfile, '>', opt$OutFile))\n# delete the temporary output file\nsystem(paste('rm', temp_outfile))\n\n# # sort the data according to the chromosome name, start positions of both the interacting segments\n# # and finally with the decreasing contact count\n# FinalData <- FinalData[order( FinalData[,1], FinalData[,2], FinalData[,5], -FinalData[,opt$cccol] ), ]\n\n# # write the data with the header information\n# write.table(FinalData, opt$OutFile, row.names = FALSE, col.names = TRUE, sep = \"\\t\", quote=FALSE, append=FALSE)\n\nif (timeprof == 1) {\n\tendtime <- Sys.time()\n\tfp <- file(opt$TimeFile, open=\"a\")\n\toutstr <- paste('\\n Time to write the interaction data (with Q value) for spline based distribution: ', (endtime - starttime))\n\twrite(outstr, file=fp, append=T)\n\tclose(fp)\n}\n", "meta": {"hexsha": "f9e31d3fb36546553ec8b47f5f062fafab0be62f", "size": 31136, "ext": "r", "lang": "R", "max_stars_repo_path": "src/Interaction.r", "max_stars_repo_name": "gahanleeo/FitHiChIP", "max_stars_repo_head_hexsha": "f34fe9eff5d65ad3dfaaecc43a6c245221b840ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 21, "max_stars_repo_stars_event_min_datetime": "2017-11-07T09:39:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-24T05:35:24.000Z", "max_issues_repo_path": "src/Interaction.r", "max_issues_repo_name": "gahanleeo/FitHiChIP", "max_issues_repo_head_hexsha": "f34fe9eff5d65ad3dfaaecc43a6c245221b840ff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 66, "max_issues_repo_issues_event_min_datetime": "2018-03-28T02:36:20.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-24T10:44:28.000Z", "max_forks_repo_path": "src/Interaction.r", "max_forks_repo_name": "gahanleeo/FitHiChIP", "max_forks_repo_head_hexsha": "f34fe9eff5d65ad3dfaaecc43a6c245221b840ff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 19, "max_forks_repo_forks_event_min_datetime": "2017-12-08T22:02:48.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-10T06:49:25.000Z", "avg_line_length": 41.7932885906, "max_line_length": 364, "alphanum_fraction": 0.6898766701, "num_tokens": 9278, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7577943822145997, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.3818572651902093}} {"text": "psa <- function(A, B) {\n\n string_to_vector <- function(x) {\n len <- nchar(x)\n return(substring(x, 1:len, 1:len))\n }\n\n move_cost <- function() {\n x <- pointer[1]\n y <- pointer[2]\n vertical_gap_penalty <- if (semi_global_mode && pointer[1] == (length(a))) 1 else -1\n vertical_move <- psa_array[x,y - 1] + if (y > 0) vertical_gap_penalty else -Inf\n horizontal_gap_penalty <- if (semi_global_mode && y == (length(b))) 1 else -1\n horizontalMove <- psa_array[x - 1,y] + if (x > 0) horizontal_gap_penalty else -Inf\n if (x > 1 && y > 1 && a[x - 1] == b[y - 1]) {\n diagonalScore <- 1\n diagonalMove <- psa_array[x - 1,y - 1] + diagonalScore\n } else {\n diagonalScore <- -Inf\n diagonalMove <- diagonalScore\n }\n moves_cost <- c(vertical_move, horizontalMove, diagonalMove)\n move_types <- rbind(c(0, -1), # vertical\n c(-1, 0), # horizontal\n c(-1, -1)) # diagonal\n return(c(max(moves_cost), move_types[which.max(moves_cost),]))\n }\n\n a <- string_to_vector(A)\n b <- string_to_vector(B)\n a_len <- length(a)\n b_len <- length(b)\n semi_global_mode <- min(a_len, b_len)/max(a_len, b_len) < 0.6\n\n psa_array <- array(0, dim=c(a_len+1, b_len+1))\n psa_array[1,] <- if (!semi_global_mode) 0:-b_len\n psa_array[,1] <- if (!semi_global_mode) 0:-a_len\n\n for (i in 1:a_len+1) {\n for (j in 1:b_len+1) {\n pointer <- c(i, j)\n psa_array[pointer[1], pointer[2]] <- move_cost()[1]\n }\n }\n\n pointer <- c(a_len+1,b_len+1)\n optimal_move_cost <- psa_array[pointer[1], pointer[2]]\n alignment_path <- c()\n while ((pointer[1] > 2) || (pointer[2] > 2)) {\n best_move <- move_cost()\n move <- best_move[2:3]\n alignment_path <- rbind(alignment_path, move)\n pointer <- pointer + move\n }\n return(tail(c(psa_array),1))\n}\n\npsa(\"ACACT\", \"ACT\")\npsa(\"ATGCTAAGCATA\", \"TACGATTCGTAT\")\npsa(\"ATGCTAAGCATA\", \"TTAGCTAAGCATA\")\n", "meta": {"hexsha": "0c8169df33e7300ddac8cfd39231a33d99682e62", "size": 2034, "ext": "r", "lang": "R", "max_stars_repo_path": "psa.r", "max_stars_repo_name": "janisz/bioinformatics", "max_stars_repo_head_hexsha": "93149ff0395b8b38c7b73875fe071864868377ff", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "psa.r", "max_issues_repo_name": "janisz/bioinformatics", "max_issues_repo_head_hexsha": "93149ff0395b8b38c7b73875fe071864868377ff", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "psa.r", "max_forks_repo_name": "janisz/bioinformatics", "max_forks_repo_head_hexsha": "93149ff0395b8b38c7b73875fe071864868377ff", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.3442622951, "max_line_length": 90, "alphanum_fraction": 0.5604719764, "num_tokens": 651, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7185943805178139, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.3817240705847705}} {"text": "\r\n#### Theoretical simulation for learning parking (such as parallel or perpendicular parking)\r\n#### Usage: Just load and run parking_simulation.20220109.r in R \r\n#### by dragging the R script file into R console, \r\n#### or by executing source(\"parking_simulation.20220109.r\") in R console.\r\n\r\n### Author: Adam Yongxin Ye\r\n### Version: 0.1.0 (2022-01-09)\r\n\r\n\r\nlibrary(grid)\r\n\r\n\r\n`%.%` = function(x,y) paste0(x,y)\r\n\r\n\r\ncarGrob = function(x=0, y=0, wheel_angle=0, width=1, length=2, wheel_to_front=0.3, wheel_to_back=wheel_to_front, wheel_length=0.3, frame_lwd=1, wheel_lwd=3, col=\"black\", default.units=\"cm\"){\r\n\tif (!is.unit(x)) x <- unit(x, default.units)\r\n\tif (!is.unit(y)) y <- unit(y, default.units)\r\n\tif (!is.unit(width)) width <- unit(width, default.units)\r\n\tif (!is.unit(length)) length <- unit(length, default.units)\r\n\tif (!is.unit(wheel_to_front)) wheel_to_front <- unit(wheel_to_front, default.units)\r\n\tif (!is.unit(wheel_to_back)) wheel_to_back <- unit(wheel_to_back, default.units)\r\n\tif (!is.unit(wheel_length)) wheel_length <- unit(wheel_length, default.units)\r\n\r\n\tx1 = x - width*0.5\r\n\tx2 = x + width*0.5\r\n\ty1 = y - wheel_to_back\r\n\ty2 = y1 + length\r\n\ty3 = y2 - wheel_to_front\r\n\tframeGrob = rectGrob(x=x1 + width*0.5, y=y1 + length*0.5, width=width, height=length, gp=gpar(col=col, lwd=frame_lwd))\r\n\twheel_axis_F = segmentsGrob(x1, y3, x2, y3, gp=gpar(col=col, lwd=frame_lwd))\r\n\twheel_axis_R = segmentsGrob(x1, y, x2, y, gp=gpar(col=col, lwd=frame_lwd))\r\n\twheel_dx = wheel_length*0.5*sinpi(wheel_angle/180)\r\n\twheel_dy = wheel_length*0.5*cospi(wheel_angle/180)\r\n\twheel_FL = segmentsGrob(x1-wheel_dx, y3+wheel_dy, x1+wheel_dx, y3-wheel_dy, gp=gpar(col=col, lwd=wheel_lwd))\r\n\twheel_FR = segmentsGrob(x2-wheel_dx, y3+wheel_dy, x2+wheel_dx, y3-wheel_dy, gp=gpar(col=col, lwd=wheel_lwd))\r\n\twheel_RL = segmentsGrob(x1, y+wheel_length*0.5, x1, y-wheel_length*0.5, gp=gpar(col=col, lwd=wheel_lwd))\r\n\twheel_RR = segmentsGrob(x2, y+wheel_length*0.5, x2, y-wheel_length*0.5, gp=gpar(col=col, lwd=wheel_lwd))\r\n\tgTree(children = gList(frameGrob, wheel_axis_F, wheel_axis_R, wheel_FL, wheel_FR, wheel_RL, wheel_RR))\r\n}\r\n\r\ndrawCarVP = function(x=0, y=0, angle=0, wheel_angle=0, width=1, length=2, wheel_to_front=0.3, wheel_to_back=wheel_to_front, wheel_length=0.3, frame_lwd=1, wheel_lwd=3, col=\"black\", default.units=\"cm\"){\r\n\tif (!is.unit(x)) x <- unit(x, default.units)\r\n\tif (!is.unit(y)) y <- unit(y, default.units)\r\n\tif (!is.unit(width)) width <- unit(width, default.units)\r\n\tif (!is.unit(length)) length <- unit(length, default.units)\r\n\tif (!is.unit(wheel_to_front)) wheel_to_front <- unit(wheel_to_front, default.units)\r\n\tif (!is.unit(wheel_to_back)) wheel_to_back <- unit(wheel_to_back, default.units)\r\n\tif (!is.unit(wheel_length)) wheel_length <- unit(wheel_length, default.units)\r\n\t\r\n\tdy_to_center = length*0.5 - wheel_to_back\r\n\tvp_x = x - dy_to_center * sinpi(angle/180)\r\n\tvp_y = y + dy_to_center * cospi(angle/180)\r\n\tcarVP = viewport(x=vp_x, y=vp_y, width=width, height=length, angle=angle)\r\n\tcarGr = carGrob(x=width*0.5, y=wheel_to_back, wheel_angle=wheel_angle, width=width, length=length, wheel_to_front=wheel_to_front, wheel_to_back=wheel_to_back, wheel_length=wheel_length, frame_lwd=frame_lwd, wheel_lwd=wheel_lwd, col=col, default.units=default.units)\r\n\tpushViewport(carVP)\r\n\tgrid.draw(carGr)\r\n\tpopViewport()\r\n\tinvisible(carVP)\r\n}\r\n\r\ncreateCar = function(x=0, y=0, angle=0, wheel_angle=0, wheel_angle_limit=30, width=1, length=2, wheel_to_front=0.3, wheel_to_back=wheel_to_front, wheel_length=0.3, frame_lwd=1, wheel_lwd=3, col=\"black\", default.units=\"cm\"){\r\n\tans = list(x=x, y=y, angle=angle, wheel_angle=wheel_angle, wheel_angle_limit=wheel_angle_limit, width=width, length=length, wheel_to_front=wheel_to_front, wheel_to_back=wheel_to_back, wheel_length=wheel_length, frame_lwd=frame_lwd, wheel_lwd=wheel_lwd, col=col, default.units=default.units)\r\n\tclass(ans) = \"car\"\r\n\tinvisible(ans)\r\n}\r\ndrawCar = function(car){\r\n\twith(car, drawCarVP(x=x, y=y, angle=angle, wheel_angle=wheel_angle, width=width, length=length, wheel_to_front=wheel_to_front, wheel_to_back=wheel_to_back, wheel_length=wheel_length, frame_lwd=frame_lwd, wheel_lwd=wheel_lwd, col=col, default.units=default.units))\r\n}\r\n\r\ncarStearWheel = function(car, new_wheel_angle){\r\n\tcar$wheel_angle = new_wheel_angle\r\n\tif(car$wheel_angle > car$wheel_angle_limit){\r\n\t\tcar$wheel_angle = car$wheel_angle_limit\r\n\t}\r\n\tif(car$wheel_angle < -car$wheel_angle_limit){\r\n\t\tcar$wheel_angle = -car$wheel_angle_limit\r\n\t}\r\n\tinvisible(car)\r\n}\r\ncarStearWheelDelta = function(car, delta_wheel_angle){\r\n\tcarStearWheel(car, car$wheel_angle + delta_wheel_angle)\r\n}\r\ncarMove = function(car, distance){\r\n\tif(car$wheel_angle==0){\r\n\t\tcar$x = car$x - distance*sinpi(car$angle/180)\r\n\t\tcar$y = car$y + distance*cospi(car$angle/180)\r\n\t}else{\r\n\t\tradius = (car$length-car$wheel_to_front-car$wheel_to_back) / tanpi(car$wheel_angle/180)\r\n\t\tcenter_x = car$x - radius*cospi(car$angle/180)\r\n\t\tcenter_y = car$y - radius*sinpi(car$angle/180)\r\n\t\tangle_distance = distance / radius / pi * 180\r\n\t\tcar$angle = car$angle + angle_distance\r\n\t\tcar$x = center_x + radius*cospi(car$angle/180)\r\n\t\tcar$y = center_y + radius*sinpi(car$angle/180)\r\n\t}\r\n\tinvisible(car)\r\n}\r\n\r\n#carDemo = createCar(5, 5)\r\n#carDemo %>% drawCar\r\n#carDemo %>% carMove(5) %>% drawCar\r\n#carDemo %>% carMove(5) %>% carStearWheel(30) %>% carMove(5) %>% drawCar\r\n\r\n\r\n\r\nToyotaCorolla_scale = c(4630, 1780, 2700) # length, width, wheel base\r\n\r\nToyotaCorolla_scale = ToyotaCorolla_scale / 1500\r\n\r\nrestart_simulation = function(userCar_x=5, userCar_y=5, parkedCar_x=6.5, parkedCar_y=c(3,11), parkedCar_angle=0, roadEdge_x=7.3, wheel_length=0.4){\r\n\tparkedCar_list = list()\r\n\tnum_parkedCar = max(c(length(parkedCar_x), length(parkedCar_y)))\r\n\tparkedCar_x = rep(parkedCar_x, length.out=num_parkedCar)\r\n\tparkedCar_y = rep(parkedCar_y, length.out=num_parkedCar)\r\n\tparkedCar_angle = rep(parkedCar_angle, length.out=num_parkedCar)\r\n\tfor(k in 1:num_parkedCar){\r\n\t\tparkedCar_list[[k]] = createCar(parkedCar_x[k], parkedCar_y[k], angle=parkedCar_angle[k], length=ToyotaCorolla_scale[1], width=ToyotaCorolla_scale[2], wheel_to_front=(ToyotaCorolla_scale[1]-ToyotaCorolla_scale[3])/2, wheel_length=wheel_length)\r\n\t}\r\n\r\n\tuserCar = createCar(userCar_x, userCar_y, col=\"brown\", length=ToyotaCorolla_scale[1], width=ToyotaCorolla_scale[2], wheel_to_front=(ToyotaCorolla_scale[1]-ToyotaCorolla_scale[3])/2, wheel_length=wheel_length)\r\n\tspeed = 0\r\n\r\n\tredraw = function(){\r\n\t\tgrid.newpage()\r\n\t\tfor(k in 1:num_parkedCar){\r\n\t\t\tdrawCar(parkedCar_list[[k]])\r\n\t\t}\r\n\t\tdrawCar(userCar)\r\n\t\tgrid.text(\"speed=\" %.% speed %.% \" , wheel_angle=\" %.% userCar$wheel_angle %.% \" , car_angle=\" %.% round(userCar$angle, 3), 0, 0, just=c(0,0))\r\n\t\tfor(now_roadEdge_x in roadEdge_x){\r\n\t\t\tgrid.segments(now_roadEdge_x, 0, now_roadEdge_x, 100, default.units=\"cm\", gp=gpar(lwd=2))\r\n\t\t}\r\n\t}\r\n\r\n\tdt = 0.5\r\n\tt = 0\r\n\twhile(TRUE){\r\n\t\tredraw()\r\n\t\t### ref: https://stackoverflow.com/questions/15272916/how-to-wait-for-a-keypress-in-r\r\n\t\tprompt_txt = \"Press arrow key to adjust, or any other key to maintain speed, or ESC to end\"\r\n\t\tshould_exit = FALSE\r\n\t\tgetGraphicsEvent(prompt=prompt_txt, consolePrompt=prompt_txt, onKeybd=function(key){\r\n\t\t\tif(key==\"Up\"){\r\n\t\t\t\tspeed <<- round(speed + 0.1, 2)\r\n\t\t\t}else if(key==\"Down\"){\r\n\t\t\t\tspeed <<- round(speed - 0.1, 2)\r\n\t\t\t}else if(key==\"Left\"){\r\n\t\t\t\tuserCar <<- carStearWheelDelta(userCar, + 30/1.5*0.5)\r\n\t\t\t}else if(key==\"Right\"){\r\n\t\t\t\tuserCar <<- carStearWheelDelta(userCar, - 30/1.5*0.5)\r\n\t\t\t}else if(key==\"ctrl-[\" || key==\"\\033\" || key==\"ctrl-C\"){ # ESC\r\n\t\t\t\tshould_exit <<- TRUE\r\n\t\t\t}else{\r\n#\t\t\t\tprint(key)\r\n\t\t\t}\r\n\t\t\t1\r\n\t\t})\r\n\t\tif(should_exit){\r\n\t\t\tbreak\r\n\t\t}\r\n\t\tuserCar = carMove(userCar, speed*dt)\r\n\t\tt = t + dt\r\n#\t\tSys.sleep(0.01)\r\n\t}\r\n}\r\n\r\n\r\n\r\n### Add X11() for compatibility in MacOS\r\nX11(type=\"cairo\")\r\n\r\n\r\nsimulation_option = 1\r\n\r\nif(simulation_option==1){\r\n\r\n\t## parallel parking\r\n\trestart_simulation(userCar_x=5, userCar_y=5, parkedCar_x=6.5, parkedCar_y=c(3,11), parkedCar_angle=0, roadEdge_x=7.3, wheel_length=0.4)\r\n\r\n}else if(simulation_option==2){\r\n\r\n\t## perpendicular parking\r\n\trestart_simulation(userCar_x=5, userCar_y=5, parkedCar_x=6.5, parkedCar_y=c(5,8.1), parkedCar_angle=-90, roadEdge_x=c(9.2,2), wheel_length=0.4)\r\n\r\n}\r\n### ref: https://www.acko.com/car-guide/how-to-park-a-car-perfectly-easy-guide-to-parallel-parking/\r\n\r\n", "meta": {"hexsha": "b1ea3fad19d93a6d2a20efbef1ff20fbc2fe3978", "size": 8350, "ext": "r", "lang": "R", "max_stars_repo_path": "parking_simulation.20220109.r", "max_stars_repo_name": "Yyx2626/yyxParkingSimulation", "max_stars_repo_head_hexsha": "2f7f18e2145637607f560c24737ad90b4cdadc61", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2022-01-10T23:57:36.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-11T00:04:44.000Z", "max_issues_repo_path": "parking_simulation.20220109.r", "max_issues_repo_name": "Yyx2626/yyxParkingSimulation", "max_issues_repo_head_hexsha": "2f7f18e2145637607f560c24737ad90b4cdadc61", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "parking_simulation.20220109.r", "max_forks_repo_name": "Yyx2626/yyxParkingSimulation", "max_forks_repo_head_hexsha": "2f7f18e2145637607f560c24737ad90b4cdadc61", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-01-11T00:04:06.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-11T00:04:06.000Z", "avg_line_length": 43.9473684211, "max_line_length": 292, "alphanum_fraction": 0.7079041916, "num_tokens": 2667, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7057850402140659, "lm_q2_score": 0.538983220687684, "lm_q1q2_score": 0.3804062940877638}} {"text": "Step2plus_Celltype_marker_inference_new<-function(tg_R1_lists,data_CORS_cancer,tg_R1_cut=8,tg_R1_list_stat,cell_type_enrich_cut=0.5,resolution_level=resolution_level0,hcutn0=40)\n{\n #have two sets of parameters for BCV t tests\n #1. For testing total rank and determining adding the base of a new cell type (strong condition)\n #2. For the linear model based cell type specific marker selected (weak condition)\n #3. Parameter set includes: number of BCV bins, number of rounds for t test and msep cut\n\t #4. Add a new step, select top K R1 bases by using hclust, and add R1 bases by a mixed score of (1) three combination linear dependency and (2) cell type uniqueness\n tg_R1_lists_st<-tg_R1_lists\n for(i in 1:length(tg_R1_lists_st))\n {\n tg_R1_lists_st[[i]]<-tg_R1_lists_st[[i]][1:min(length(tg_R1_lists_st[[i]]),tg_R1_cut)]\n }\n \n print(\"Compute_total_rank!\")\n tg_all_genes<-c()\n for(i in 1:length(tg_R1_lists_st))\n {\n tg_all_genes<-c(tg_all_genes,tg_R1_lists_st[[i]])\n }\n tg_all_genes<-unique(tg_all_genes)\n tg_data_ccc<-data_CORS_cancer[tg_all_genes,]\n BCV_stat_c<-BCV_ttest3(tg_data_ccc,rounds=100,slice0=4,maxrank0=30,msep_cut=0.0001)\n dim_tt<-sum(BCV_stat_c[[1]]<0.01)\n print(\"Total Cell Dim\")\n\tprint( dim_tt)\n #remove the leave one out step and add a hclust pre-filtering step\n\tdata_c<-data_CORS_cancer\n\tBase_all<-c()\n\tfor(i in 1:length(tg_R1_lists_st))\n\t{\n tg_data_c<-data_c[tg_R1_lists_st[[i]],]\n cc<-svd(tg_data_c)$v[,1]\n ccc<-cor(cc,t(tg_data_c))\n if(mean(ccc)<0)\n {\n cc<--cc\n }\n Base_all<-rbind(Base_all,cc)\n\t}\n\trownames(Base_all)<-names(tg_R1_lists_st)\n\tbbb_all0<-Base_all\n\trownames(bbb_all0)<-1:nrow(bbb_all0)\n\t\n\thcutn0<-min(hcutn0,nrow(bbb_all0))\n\tdata_genes_all<-data_CORS_cancer[tg_all_genes,]\n\thcutn1<-min(hcutn0+3,nrow(bbb_all0))\n\thclust_R1_screen<-hclust_screen_top_bases(bbb_all0,data_genes_all,hcutn=hcutn1)\n\tccc<-c()\n\tfor(i in 1:length(hclust_R1_screen[[1]]))\n\t{\n\t\taaa<-cor(t(hclust_R1_screen[[1]][[i]]))\n\t\tdiag(aaa)<-0\n\t\tccc<-c(ccc,max(aaa))\n\t}\n\tR_bases_hclust_top_correlations<-ccc\n\thh<-hclust_R1_screen[[3]][[hcutn0]]\n\tBase_hclust_screen_result<-Base_screen(bbb_all0,hh,tg_R1_list_stat)\n\tBase_hclust_screen_selected<-as.numeric(Base_hclust_screen_result[[1]])\n\t\n\ttg_R1_lists_selected<-list()\n\ttg_R1_list_stat_selected<-list()\n\tnn<-c()\n\tfor(i in 1:length(Base_hclust_screen_selected))\n\t{\n\t\ttg_R1_lists_selected[[i]]<- tg_R1_lists_st[[Base_hclust_screen_selected[[i]]]]\n\t\ttg_R1_list_stat_selected[[i]]<-tg_R1_list_stat[[Base_hclust_screen_selected[[i]]]][tg_R1_lists_selected[[i]],]\n\t\tcc<-apply(tg_R1_list_stat_selected[[i]],2,mean)\n\t\tnn<-c(nn,names(which(cc==max(cc))[1]))\n\t}\n\tnames(tg_R1_lists_selected)<-nn\n\ttgs<-tg_R1_lists_selected\n\n print(\"Linking graph based cell type selection\")\n ddd<-combn(length(tgs),3)\n comp_ids<-c()\n stat_all<-rep(0,length(tgs))\n stat_2total<-rep(0,length(tgs))\n names(stat_all)<-1:length(tgs)\n data_c<-data_CORS_cancer\n\t\n\tBase_all<-c()\n\tfor(i in 1:length(tgs))\n\t{\n tg_data_c<-data_c[tgs[[i]],]\n cc<-svd(tg_data_c)$v[,1]\n ccc<-cor(cc,t(tg_data_c))\n if(mean(ccc)<0)\n {\n cc<--cc\n }\n Base_all<-rbind(Base_all,cc)\n\t}\n\trownames(Base_all)<-names(tgs)\n\n\t\nfor(i in 1:ncol(ddd))\n{\n tg_genes<-unique(c(tgs[[ddd[1,i]]],tgs[[ddd[2,i]]],tgs[[ddd[3,i]]]))\n \t pp<-sum(BCV_ttest2(data_c[tg_genes,],rounds=20,maxrank0=5)<0.001)\n if(pp==2)\n {\n comp_ids<-c(comp_ids,i)\n #print(i)\n lm0<-lm(Base_all[ddd[1,i],]~Base_all[ddd[2,i],]+Base_all[ddd[3,i],]+0)\n if(sum(is.na(coefficients(lm0)))==0)\n {\n stat_2total[ddd[,i]]<-stat_2total[ddd[,i]]+1\n if((sign(coefficients(lm0))[1]==1)&(sign(coefficients(lm0))[2]==1))\n {\n stat_all[ddd[2,i]]<-stat_all[ddd[2,i]]+1\n stat_all[ddd[3,i]]<-stat_all[ddd[3,i]]+1\n }\n if((sign(coefficients(lm0))[1]==-1)&(sign(coefficients(lm0))[2]==1))\n {\n stat_all[ddd[2,i]]<-stat_all[ddd[2,i]]+1\n stat_all[ddd[1,i]]<-stat_all[ddd[1,i]]+1\n }\n if((sign(coefficients(lm0))[1]==1)&(sign(coefficients(lm0))[2]==-1))\n {\n stat_all[ddd[3,i]]<-stat_all[ddd[3,i]]+1\n stat_all[ddd[1,i]]<-stat_all[ddd[1,i]]+1\n }\n }\n }\n if(i%%100==1)\n {\n print(i)\n }\n}\n\n\nstat_all0<-stat_all/stat_2total\nscores10<-stat_all0\ns1<-scores10[order(-scores10)]\nss<-rownames(Base_all)[order(-scores10)]\nscore_plus<-rep(0,length(ss))\nnames(score_plus)<-names(s1)\nss0<-unique(ss)\nss0_counts<-rep(1,length(ss0))\nnames(ss0_counts)<-ss0\nfor(i in 1:length(ss))\n{\n\tscore_plus[i]<-ss0_counts[ss[i]]\n\tss0_counts[ss[i]]<-ss0_counts[ss[i]]+1\n}\nscore_plus0<-(1/score_plus)^2\ns2<-score_plus0+s1\ns2<-s2[order(-s2)]\n\n#names(tgs)[as.numeric(names(s2))]\n#names(tgs)[selected_id]\n\ntotal_dim<-dim_tt\nN<-0\ntt_selected_genes<-c()\nselected_p<-c()\nselected_c<-c()\ntg_d_stat<-c()\nselected_id<-c()\nfor(i in 1:length(s2))\n{\n if(N<=total_dim)\n {\n tg_id_c<-as.numeric(names(s2)[i])\n print(c(tg_id_c,tg_id_c))\n if(length(selected_p)==0)\n {\n selected_p<-tgs[[tg_id_c]]\n tg_d_stat<-1\n selected_id<-c(tg_id_c)\n N<-N+1\n print(N)\n print(selected_id)\n }\n else\n {\n selected_c<-c(selected_p,tgs[[tg_id_c]])\n selected_c<-unique(selected_c)\n tg_data_ccc0<-data_CORS_cancer[selected_c,] \n BCV_stat_c0<-BCV_ttest3(tg_data_ccc0,rounds=100,slice0=2,maxrank0=30,msep_cut=0.0001)\n tg_d_c<-sum(BCV_stat_c0[[1]]<0.001)#which(BCV_stat_c0[[1]]>0.001)[1]-1\n print(tg_d_c)\n if(tg_d_c>tg_d_stat[length(tg_d_stat)])\n {\n tg_d_stat<-c(tg_d_stat,tg_d_c)\n selected_id<-c(selected_id,tg_id_c)\n selected_p<-selected_c\n N<-N+1\n print(N)\n print(selected_id)\n }\n print(\"\")\n } \n }\n}\n\ntg_2badded_cells<-setdiff(unique(names(tgs)),unique(names(tgs)[selected_id]))\nadd_R1_base_cut<-list()\n#add_R1_base_full<-list()\nif(length(tg_2badded_cells)>0)\n{\n ccc<-rep(0,length(tg_2badded_cells))\n names(ccc)<-tg_2badded_cells\n ttt<-s2\n for(i in 1:length(ttt))\n {\n if(sum(names(tgs)[as.numeric(names(ttt[i]))]==tg_2badded_cells))\n {\n tg<-names(tgs)[as.numeric(names(ttt[i]))]\n if(ccc[tg]==0)\n {\n add_R1_base_cut[[which(tg_2badded_cells==tg)]]<-tgs[[as.numeric(names(ttt[i]))]]\n #add_R1_base_full[[which(tg_2badded_cells==tg)]]<-tg_R1_lists[[as.numeric(names(ttt[i]))]]\n ccc[tg]<-1\n }\n }\n }\n}\nnames(add_R1_base_cut)<-tg_2badded_cells\n\n#############################\nnn<-rep(\"\",length(tg_R1_list_stat_selected))\nfor(i in 1:length(tg_R1_list_stat_selected))\n{\n if(max(tg_R1_list_stat_selected[[i]][min(tg_R1_cut,nrow(tg_R1_list_stat_selected[[i]])),resolution_level])>cell_type_enrich_cut)\n {\n ccc<-tg_R1_list_stat_selected[[i]][min(tg_R1_cut,nrow(tg_R1_list_stat_selected[[i]])),resolution_level]\n nn[i]<-names(which(ccc==max(ccc))[1])\n }\n}\nselected_cell_types<-intersect(resolution_level,unique(nn))\n\ncellreso_R1_base_cut<-list()\n#cellreso_R1_base_full<-list()\n\nfor(i in 1:length(selected_cell_types))\n{\n cc1<-c()\n #cc2<-c()\n for(j in 1:length(nn))\n {\n if(nn[j]==selected_cell_types[i])\n {\n cc1<-c(cc1,tgs[[j]])\n #cc2<-c(cc2,tg_R1_lists[[j]])\n }\n }\n cellreso_R1_base_cut[[i]]<-unique(cc1)\n #cellreso_R1_base_full[[i]]<-unique(cc2)\n}\nnames(cellreso_R1_base_cut)<-selected_cell_types\n#names(cellreso_R1_base_full)<-selected_cell_types\n\n#############################\nsupp_results<-list(tg_R1_lists_selected,tg_R1_list_stat_selected,selected_id,tg_d_stat,dim_tt,stat_all,stat_2total,hclust_R1_screen,Base_hclust_screen_selected,R_bases_hclust_top_correlations)\nnames(supp_results)<-c(\"tg_R1_lists_selected\",\"tg_R1_list_stat_selected\",\"selected_id\",\"tg_d_stat\",\"total_cell_type_number\",\"stat_all\",\"stat_2total\",\"hclust_R1_screen\",\"Base_hclust_screen_selected\",\"R_bases_hclust_top_correlations\")\n\nselected_R1_base_cut<-list()\n#selected_R1_base_full<-list()\n\nfor(i in 1:length(selected_id))\n{\n selected_R1_base_cut[[i]]<-tgs[[selected_id[i]]]\n #selected_R1_base_full[[i]]<-tg_R1_lists[[selected_id[i]]]\n}\nnames(selected_R1_base_cut)<-names(tgs)[selected_id]\n#names(selected_R1_base_full)<-names(tgs)[selected_id]\n\nR2_selected_cell_type_markers<-list(selected_R1_base_cut,add_R1_base_cut,cellreso_R1_base_cut,supp_results)\nnames(R2_selected_cell_type_markers)<-c(\"selected_R1_base_cut\",\"add_R1_base_cut\",\"cellreso_R1_base_cut\",\"supp_results\")\nreturn(R2_selected_cell_type_markers)\n}\n\n\nhclust_screen_top_bases<-function(bbb_all0,data_genes_all,hcutn=80)\n{\naaa<-data_genes_all\nh<-hclust(dist(bbb_all0))\ntg_trunc_list<-list()\ntg_trunc_list_old<-list()\nst<-0\ntrunc_RS_bases_all<-list()\nRMSE_IM<-list()\nhclust_info<-list()\nhcutn0<-min(hcutn,nrow(bbb_all0))\nfor(i in 1:hcutn0)\n{\n\tfff<-cutree(h,i)\n\thclust_info[[i]]<-fff\n\tfff0<-unique(fff)\n\ttg_trunc_list_old<-tg_trunc_list\n\ttg_trunc_list<-list()\n\t#tg_trunc_list_info<-list()\n\ttg_trunc_RS_bases<-c()\n\tRMSE_table_c<-c()\n\tif(st==0)\n\t{\n\t\tfor(j in 1:length(fff0))\n\t\t{\n\t\t\ttg_ccc<-names(which(fff==fff0[j]))\n\t\t\ttg_trunc_list[[j]]<-tg_ccc\n\t\t\tif(length(tg_ccc)==1)\n \t\t{\n \t\ttg_trunc_RS_bases<-rbind(tg_trunc_RS_bases,bbb_all0[tg_ccc,])\n \t\t}\n \t\telse\n \t\t{\n \t\tbbb_all0_c<-bbb_all0[tg_ccc,]\n \t\tbbb_all0_cc<-t(svd(bbb_all0_c)$v)[1,]\n\t\t\t\taaa0<-cor(t(t(bbb_all0_cc)),t(bbb_all0_c))\n\t\t\t\taaa0<-aaa0[which(abs(aaa0)>0.6)]\n\t\t\t\tif(mean(aaa0)<0)\n\t\t\t\t{\n\t\t\t\t\tbbb_all0_cc<--bbb_all0_cc\n\t\t\t\t}\n \t\ttg_trunc_RS_bases<-rbind(tg_trunc_RS_bases,bbb_all0_cc)\n \t\t}\n\n\n\t\t}\n\t\trownames(tg_trunc_RS_bases)<-1:nrow(tg_trunc_RS_bases)\n\t\ttrunc_RS_bases_all[[i]]<-tg_trunc_RS_bases\n\t\tccc<-c()\n\t\tfor(j in 1:nrow(tg_trunc_RS_bases))\n\t\t{\n \t\tttt_c<-tg_trunc_RS_bases[j,]%*%t(tg_trunc_RS_bases[j,])/sum((tg_trunc_RS_bases[j,])^2)\n \t\tccc<-cbind(ccc,RMSE_row(aaa%*%ttt_c)/RMSE_row(aaa))\n \t}\n\t\tRMSE_IM[[i]]<-ccc\n\t\tst<-1\n\t}\n\telse\n\t{\n\t\tccc_old<-ccc\n\t\tfor(j in 1:length(fff0))\n\t\t{\n\t\t\ttg_ccc<-names(which(fff==fff0[j]))\n\t\t\ttg_trunc_list[[j]]<-tg_ccc\n\t\t\tif(length(tg_ccc)==1)\n \t\t{\n \t\ttg_trunc_RS_bases<-rbind(tg_trunc_RS_bases,bbb_all0[tg_ccc,])\n \t\t}\n \t\telse\n \t\t{\n \t\tbbb_all0_c<-bbb_all0[tg_ccc,]\n \t\tbbb_all0_cc<-t(svd(bbb_all0_c)$v)[1,]\n\t\t\t\taaa0<-cor(t(t(bbb_all0_cc)),t(bbb_all0_c))\n\t\t\t\taaa0<-aaa0[which(abs(aaa0)>0.6)]\n\t\t\t\tif(mean(aaa0)<0)\n\t\t\t\t{\n\t\t\t\t\tbbb_all0_cc<--bbb_all0_cc\n\t\t\t\t}\n \t\ttg_trunc_RS_bases<-rbind(tg_trunc_RS_bases,bbb_all0_cc)\n \t}\n\t\t}\n\t\trownames(tg_trunc_RS_bases)<-1:nrow(tg_trunc_RS_bases)\n\t\ttrunc_RS_bases_all[[i]]<-tg_trunc_RS_bases\n\t\tperturb_id<-hcut_update(tg_trunc_list,tg_trunc_list_old)\n\t\tccc<-c()\n\t\tfor(j in 1:nrow(tg_trunc_RS_bases))\n\t\t{\n\t\t\tif(sum(j==perturb_id[[2]])==0)\n\t\t\t{\n\t\t\t\tccc<-cbind(ccc,ccc_old[,perturb_id[[3]][j]])\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tttt_c<-tg_trunc_RS_bases[j,]%*%t(tg_trunc_RS_bases[j,])/sum((tg_trunc_RS_bases[j,])^2)\n\t\t\t\tccc<-cbind(ccc,RMSE_row(aaa%*%ttt_c)/RMSE_row(aaa))\n\t\t\t\t#print(c(i,j))\n\t\t\t}\n }\n\t\tRMSE_IM[[i]]<-ccc\n\t}\n}\nif(hcutn00.6)]\n\t\t\t\tif(mean(aaa0)<0)\n\t\t\t\t{\n\t\t\t\t\tbbb_all0_cc<--bbb_all0_cc\n\t\t\t\t}\n \t\ttg_trunc_RS_bases<-rbind(tg_trunc_RS_bases,bbb_all0_cc)\n \t\t}\n\t\t}\n\t\trownames(tg_trunc_RS_bases)<-1:nrow(tg_trunc_RS_bases)\n\t\ttrunc_RS_bases_all[[N]]<-tg_trunc_RS_bases\n\t\tccc<-c()\n\t\tfor(j in 1:nrow(tg_trunc_RS_bases))\n\t\t{\n \t\tttt_c<-tg_trunc_RS_bases[j,]%*%t(tg_trunc_RS_bases[j,])/sum((tg_trunc_RS_bases[j,])^2)\n \t\tccc<-cbind(ccc,RMSE_row(aaa%*%ttt_c)/RMSE_row(aaa))\n \t}\n\t\tRMSE_IM[[N]]<-ccc\n\t}\n}\n}\nccc<-list(trunc_RS_bases_all,RMSE_IM,hclust_info)\nnames(ccc)<-c(\"Bases_all\",\"RMSE_all\",\"clust_info_all\")\nreturn(ccc)\n}\n\nBase_screen<-function(bbb_all0,hh,tg_R1_list_stat)\n{\n\ttg_R1_list_stat0<-tg_R1_list_stat\n\tnames(tg_R1_list_stat0)<-1:length(tg_R1_list_stat)\n\tttt<-unique(hh)\n\tmerge_list_info<-list()\n\tR1_selected_c<-c()\n\tfor(i in 1:length(ttt))\n\t{\n\t\t#print(i)\n\t\tcc<-names(which(hh==ttt[i]))\n\t\tmerge_list_info[[i]]<-list(cc,1)\n\t\tif(length(cc)==1)\n\t\t{\n\t\t\tR1_selected_c<-c(R1_selected_c,cc)\n\t\t}\n\t\tif(length(cc)==2)\n\t\t{\n\t\t\tddd<-cor(t(bbb_all0[cc,]))\n\t\t\t#print(ddd)\n\t\t\tm1<-max(apply(tg_R1_list_stat0[[cc[1]]],2,mean))\n\t\t\tm2<-max(apply(tg_R1_list_stat0[[cc[2]]],2,mean))\n\t\t\tif(m1>=m2)\n\t\t\t{\n\t\t\t\tR1_selected_c<-c(R1_selected_c,cc[1])\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tR1_selected_c<-c(R1_selected_c,cc[2])\n\t\t\t}\n\t\t\tmerge_list_info[[i]][[2]]<-ddd\n\t\t}\n\t\tif(length(cc)>2)\n\t\t{\n\t\t\tddd<-cor(t(bbb_all0[cc,]))\n\t\t\tfff<-apply(ddd,1,mean)\n\t\t\tggg<-which(fff==max(fff))\n\t\t\tif(length(ggg)==1)\n\t\t\t{\n\t\t\t\tR1_selected_c<-c(R1_selected_c,cc[ggg])\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tdd<-cc[ggg]\n\t\t\t\tmm<-c()\n\t\t\t\tfor(j in 1:length(dd))\n\t\t\t\t{\n\t\t\t\t\tmm<-c(mm,max(apply(tg_R1_list_stat0[[dd[j]]],2,mean)))\n\t\t\t\t}\n\t\t\t\tee<-dd[which(mm==max(mm))[1]]\n\t\t\t\tR1_selected_c<-c(R1_selected_c,ee)\n\t\t\t}\n\t\t\tmerge_list_info[[i]][[2]]<-ddd\n\t\t}\n\t}\n return(list(R1_selected_c,merge_list_info)) \n}\n\nhcut_update<-function(tg_trunc_list,tg_trunc_list_old)\n{\n\tout_list<-rep(0,length(tg_trunc_list))\n\tfor(i in 1:length(tg_trunc_list))\n\t{\n\t\tfor(j in 1:length(tg_trunc_list_old))\n\t\t{\n\t\t\tif(length(intersect(tg_trunc_list[[i]],tg_trunc_list_old[[j]]))>0)\n\t\t\t{\n\t\t\t\tout_list[i]<-j\n\t\t\t}\n\t\t}\n\t}\n\ttg_old_id<-as.numeric(names(which(table(out_list)==2)))\n\ttg_new_id<-which(out_list==tg_old_id)\n\treturn(list(tg_old_id,tg_new_id,out_list))\n}\n", "meta": {"hexsha": "d562baaa981d896e9a65627fc06df6c2c6a294ec", "size": 15679, "ext": "r", "lang": "R", "max_stars_repo_path": "R/temp_func.r", "max_stars_repo_name": "changwn/ICTD", "max_stars_repo_head_hexsha": "acb0d5c2c859b4c756e1ff50e6624046a2f68d36", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-01-31T02:23:12.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-17T00:33:55.000Z", "max_issues_repo_path": "R/temp_func.r", "max_issues_repo_name": "changwn/ICTD", "max_issues_repo_head_hexsha": "acb0d5c2c859b4c756e1ff50e6624046a2f68d36", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/temp_func.r", "max_forks_repo_name": "changwn/ICTD", "max_forks_repo_head_hexsha": "acb0d5c2c859b4c756e1ff50e6624046a2f68d36", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.9250493097, "max_line_length": 232, "alphanum_fraction": 0.5909177881, "num_tokens": 5102, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.798186768138228, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.38039957144295994}} {"text": "#author: Thomas Coleman\n# Difference in Differences Regressions - Error Analysis and Graphs for data from Snow 1855\n\n# See \"Causality in the Time of Cholera\" working paper at https://papers.ssrn.com/abstract=3262234 \n# and my John Snow project website, http://www.hilerun.org/econ/papers/snow\n\n# This code is licensed under the BSD 2-Clause License, https://opensource.org/licenses/BSD-2-Clause\n\n# This collect together some simple functions that produce a standard format graph, and are 'source'd \n# into various notebooks\n\n# **preperrdata** Before graphing, to prepare the data\n\n# * Takes in *fittedmodel* - a regression that has been already run. From this it extracts the necessary \n# parameters. Also *single*, a string which for \"single\" says that there is a single treatment effect. \n# * Calculates the 1849 and 1854 predicted counts and rates\n# * Calculates *approximate* 95% error bars around the predicted rates, based on whether the fitted model \n# is Poisson or Negative Binomial\n# * Produces an adjusted 1854 predicted rate, adjusting for the 1854 time effect and treatment effect, so \n# that it is comparable to the 1849 predicted rate (for purposes of plotting with error bars)\n\n# This function changes global data (the x1849 & x1854 dataframes) using the \"<<-\" instead of \"<-\" \n# assignment. This is poor programming style but I could not find another easy way of doing what I wanted. \n\n# **plot2_worker** Plots actual vs predicted, with error bars around the predicted\n\n# * Actually does the plotting, given all the data as input arguments (sequence no. for sub-districts; \n# the actual mean or rate; predicted; the 2.5% and 97.5% points; title)\n# * btw, the hack for plotting error bars is from \n# https://stackoverflow.com/questions/13032777/scatter-plot-with-error-bars\n\n# **plot2** Is a cover function which unpacks the actual versus predicted mean from the appropriate dataframe\n\n# **plot3** Plots actual 1849, 1854 (adjusted for time & treatment effects), predicted, with error bars\n\n# **plotcomp** Plots actual 1849 versus 1854, with error bars around actual 1849\n\n# **ploterrbars** is NOT a function you should use - I use it to print out .pdf versions of the graphs I want to use\n\n\n\n# 22-jul-2020 modify to create \"adjusted rates\" for both 1849 and 1854 \n\npreperrdata <- function(fittedmodel,single = \"single\",link=\"log\",conf=.95,population=\"population\") { # This is not a good way to do this because I am \n\t # changing globals from within the function (using <<- \n\t # instead of <-)\n# Function to prepare the data (error bars) for graphing\n# The 2.5% and 97.5% confidence bands are calculated assuming either Poisson or Negative Binomial\n# The rates are calculated by generating the counts up and down from the \"expected\" (from the fitted model)\n\n\t# Set the confidence levels (inputting 0.95 means lower leve .025, upper .975, total .05 / .95)\n\txconfidl <- (1-conf)/2\n\txconfidu <- 1-xconfidl\n\texpected <- predict(fittedmodel)\n\txfamily <- family(fittedmodel)$family\n\tif (link == \"log\") {\n\t\texpected <- exp(expected) # expected values\n\t}\n\tif (substr(xfamily,1,8) == \"gaussian\") { # For OLS \"rate\" model need to convert from rates to counts\n\t\texpected[1:28] <- expected[1:28] * x1849[,population]\n\t\texpected[29:56] <- expected[29:56] * x1854[,population]\n\t}\n\ttheta <- fittedmodel$theta\n\tx1849$predcount <<- expected[1:28]\n\tx1854$predcount <<- expected[29:56]\n\tx1849$predrate <<- 10000 * expected[1:28] / x1849[,population]\n\tx1854$predrate <<- 10000 * expected[29:56] / x1854[,population]\n\tif (xfamily == \"poisson\") { # Get 95% confidence bands depending on model used (Poiss vs Neg Binom)\n\t\tx1849$limdn <<- 10000 * qpois(xconfidl,lambda=x1849$predcount) / x1849[,population]\n\t\tx1849$limup <<- 10000 * qpois(xconfidu,lambda=x1849$predcount) / x1849[,population]\n\t\tx1854$limdn <<- 10000 * qpois(xconfidl,lambda=x1854$predcount) / x1854[,population]\n\t\tx1854$limup <<- 10000 * qpois(xconfidu,lambda=x1854$predcount) / x1854[,population]\n\t\tx1849$limdnact <<- 10000 * qpois(xconfidl,lambda=x1849$deaths) / x1849[,population]\n\t\tx1849$limupact <<- 10000 * qpois(xconfidu,lambda=x1849$deaths) / x1849[,population]\n\t} else if (substr(xfamily,1,8) == \"Negative\"){\n\t\tx1849$limdn <<- 10000 * qnbinom(xconfidl,size=theta,mu=x1849$predcount) / x1849[,population]\n\t\tx1849$limup <<- 10000 * qnbinom(xconfidu,size=theta,mu=x1849$predcount) / x1849[,population]\n\t\tx1854$limdn <<- 10000 * qnbinom(xconfidl,size=theta,mu=x1854$predcount) / x1854[,population]\n\t\tx1854$limup <<- 10000 * qnbinom(xconfidu,size=theta,mu=x1854$predcount) / x1854[,population]\n\t\tx1849$limdnact <<- 10000 * qnbinom(xconfidl,size=theta,mu=x1849$deaths) / x1849[,population]\n\t\tx1849$limupact <<- 10000 * qnbinom(xconfidu,size=theta,mu=x1849$deaths) / x1849[,population]\n\t} else if (substr(xfamily,1,8) == \"gaussian\"){\n\t\tx3 <- predict(fittedmodel,interval=\"prediction\") # I think \"confidence\" is what I want and not \"prediction\"\n\t\tx1849$limdn <<- x3[1:28,2]\n\t\tx1849$limup <<- x3[1:28,3]\n\t\tx1854$limdn <<- x3[29:56,2]\n\t\tx1854$limup <<- x3[29:56,3]\n\t\tif (link == \"log\") { # There is no \"link\" item for lm, so the only way I can tell if this model is run\n\t\t # in level or log form is to look at the predicted, and if it is negative presume it's in logs\n\t\t\tx1849$limdn <<- exp(x1849$limdn)\n\t\t\tx1849$limup <<- exp(x1849$limup)\n\t\t\tx1854$limdn <<- exp(x1854$limdn)\n\t\t\tx1854$limup <<- exp(x1854$limup)\n\t\t}\n\t\tx1849$limdn <<- 10000 * x1849$limdn\n\t\tx1849$limup <<- 10000 * x1849$limup\n\t\tx1854$limdn <<- 10000 * x1854$limdn\n\t\tx1854$limup <<- 10000 * x1854$limup\n\t}\n\n\n\t# Now adjust the 1854 predicted counts (and rates) for the time and treatment fixed effects -\n\t# effectively netting out the 1854 effect and making it 1849-equivalent\n\t# Adjust for the year effect only - this should make 1849 & 1854 comparable net of time effect\n\tif (link == \"log\") {\n\t\txyr1854 <- (coef(fittedmodel)[\"year1854\"])\n\t\tx49 <- exp(xyr1854)\n\t\tx54 <- exp(-xyr1854)\n\t\tx1849$rateadjyr <<- 10000 * (x1849$deaths*x49) / x1849[,population]\n\t\tx1854$rateadjyr <<- 10000 * (x1854$deaths*x54) / x1854[,population]\n\t} else {\n\t\tx49 <- (coef(fittedmodel)[\"year1854\"])\n\t\tx54 <- -(coef(fittedmodel)[\"year1854\"])\n\t\tx1849$rateadjyr <<- x1849$rate + x49\n\t\tx1854$rateadjyr <<- x1854$rate + x54\n\t}\n\t# Adjust the 1854 actual for the estimated Treatment Effect and the estimated Year Effect\n\tif (single == \"single\") { # model with single treatment effect\n\t\txdegless <- (coef(fittedmodel)[\"supplierSouthwarkVauxhall_Lambeth:year1854\"])\n\t\txdegmore <- xdegless # Make both treatment effects the same\n\t\tif (link == \"log\") {\n\t\t\tx49 <- x49 * exp((x1849$lambethdegree == \"less_Lambeth\")*xdegless) \n\t\t\tx49 <- x49 * exp((x1849$lambethdegree == \"more_Lambeth\")*xdegmore) \n\t\t\tx54 <- x54 * exp(-(x1854$lambethdegree == \"less_Lambeth\")*xdegless) \n\t\t\tx54 <- x54 * exp(-(x1854$lambethdegree == \"more_Lambeth\")*xdegmore)\n\t\t\tx1849$rateadj <<- 10000 * (x1849$deaths*x49) / x1849[,population]\n\t\t\tx1854$rateadj <<- 10000 * (x1854$deaths*x54) / x1854[,population]\n\t\t} else {\n\t\t\tx49 <- x49 + (x1849$lambethdegree == \"less_Lambeth\")*xdegless\n\t\t\tx54 <- x49 + (x1849$lambethdegree == \"more_Lambeth\")*xdegmore \n\t\t\tx54 <- x54 -(x1854$lambethdegree == \"less_Lambeth\")*xdegless\n\t\t\tx54 <- x54 -(x1854$lambethdegree == \"more_Lambeth\")*xdegmore\n\t\t\tx1849$rateadj <<- x1849$rate + x49\n\t\t\tx1854$rateadj <<- x1854$rate + x54\n\t\t}\n\t} else if (single == \"two\") { # model with two treatment effects \t\t\n\t\txdegless <- coef(fittedmodel)[\"lambethdegreeless_Lambeth:year1854\"]\n\t\txdegmore <- coef(fittedmodel)[\"lambethdegreemore_Lambeth:year1854\"]\n\t\tif (link == \"log\") {\n\t\t\tx49 <- x49 * exp((x1849$lambethdegree == \"less_Lambeth\")*xdegless) \n\t\t\tx49 <- x49 * exp((x1849$lambethdegree == \"more_Lambeth\")*xdegmore) \n\t\t\tx54 <- x54 * exp(-(x1854$lambethdegree == \"less_Lambeth\")*xdegless) \n\t\t\tx54 <- x54 * exp(-(x1854$lambethdegree == \"more_Lambeth\")*xdegmore)\n\t\t\tx1849$rateadj <<- 10000 * (x1849$deaths*x49) / x1849[,population]\n\t\t\tx1854$rateadj <<- 10000 * (x1854$deaths*x54) / x1854[,population]\n\t\t} else {\n\t\t\tx49 <- x49 + (x1849$lambethdegree == \"less_Lambeth\")*xdegless\n\t\t\tx54 <- x49 + (x1849$lambethdegree == \"more_Lambeth\")*xdegmore \n\t\t\tx54 <- x54 -(x1854$lambethdegree == \"less_Lambeth\")*xdegless\n\t\t\tx54 <- x54 -(x1854$lambethdegree == \"more_Lambeth\")*xdegmore\n\t\t\tx1849$rateadj <<- x1849$rate + x49\n\t\t\tx1854$rateadj <<- x1854$rate + x54\n\t\t}\n\t} else { # model with continuous treatment (population proportions)\n\t\txperc_lambeth54 <- coef(fittedmodel)[\"perc_lambeth54\"]\n\t\tif (link == \"log\") {\n\t\t\tx49 <- exp((x1849$perc_lambeth * xperc_lambeth54)) / x49\n\t\t\tx54 <- x54 * exp(-(x1854$perc_lambeth * xperc_lambeth54))\n\t\t\tx1849$rateadj <<- 10000 * (x1849$deaths*x49) / x1849[,population]\n\t\t\tx1854$rateadj <<- 10000 * (x1854$deaths*x54) / x1854[,population]\n\t\t} else {\n\t\t\tx49 <- (x1849$perc_lambeth * xperc_lambeth54) - x49\n\t\t\tx54 <- x54 -(x1854$perc_lambeth * xperc_lambeth54)\n\t\t\tx1849$rateadj <<- x1849$rate + x49\n\t\t\tx1854$rateadj <<- x1854$rate + x54\n\t\t}\n\t}\n\n\treturn(xfamily)\n}\n\n\n# \"Worker\" function to plot mean, predicted, and error bars\nplot2_worker <- function(yseq, xmean,xlimdn,xpred,xlimup,title,legposition=\"bottomright\") { \n\txplot <- plot(xmean, yseq,\n\t xlim=range(c(xmean, xpred,xlimdn,xlimup)),\n\t ylim=rev(range(yseq)), col=\"red\",\n\t main=title,xlab=\"Mortality rate actual (red filled) vs predicted (empty circle)\",ylab=\"sub-district\",\n\t pch=19)\n\tlines(xpred, yseq, type=\"p\",\n\t xlim=range(c(xmean, xpred,xlimdn,xlimup)),\n\t ylim=rev(range(yseq)), \n\t pch=1)\n\t# horizontal error bars\n\txplot <- arrows(xlimdn, yseq, xlimup, yseq, length=0.05, angle=90, code=3,lty=3)\n# Ooops - this legend is not for \"plot2\" but for \"plotcomp\"\n#\txplot <- legend(legposition, c(\"1849 red circle\", \"1854 blue triangle\"), col = c(2, 4),\n# text.col = c(\"red\",\"blue\"), lty = c(0, 0), pch = c(19, 17),\n# merge = TRUE,bty=\"o\",bg=\"white\") # The bty=\"o\" should overwrite the background\n\n\n\txplot\n}\n# \"Cover\" function that takes in the dataframe and unpacks\nplot2 <- function(confidata,xsupplier,title,legposition=\"bottomright\") { \n\txmean <- subset(confidata,supplier==xsupplier)[,\"rate\"]\n\txlimdn <- subset(confidata,supplier==xsupplier)[,\"limdn\"]\n\txlimup <- subset(confidata,supplier==xsupplier)[,\"limup\"]\n\txpred <- subset(confidata,supplier==xsupplier)[,\"predrate\"]\n\tyseq <- subset(confidata,supplier==xsupplier)[,\"seq\"]\n#\txtitle <- paste(xsupplier,title)\n\txplot <- plot2_worker(yseq,xmean,xlimdn,xpred,xlimup,title,legposition)\n}\n\n\n# 29-jul-20 Split out \"plot3_worker\"\nplot3_worker <- function(yseq,xmean, xpred,xlimdn,xlimup,x1854adj,title,legposition=\"bottomright\") {\n\txplot <- plot(xmean, yseq,\n\t xlim=range(c(xmean, xpred,xlimdn,xlimup,x1854adj)),\n\t ylim=rev(range(yseq)), col=\"red\", \n\t main=title,xlab=\"Mortality per 10,000 population\",ylab=\"sub-district\",\n\t pch=19)\n\tlines(xpred, yseq, type=\"p\",\n\t xlim=range(c(xmean, xpred,xlimdn,xlimup)),\n\t ylim=rev(range(yseq)), \n\t pch=1)\n\tlines(x1854adj, yseq, type=\"p\",\n\t xlim=range(c(xmean, xpred,xlimdn,xlimup)),\n\t ylim=rev(range(yseq)), col=\"blue\", \n\t pch=17)\n\n\t# horizontal error bars\n\txplot <- arrows(xlimdn, yseq, xlimup, yseq, length=0.05, angle=90, code=3,lty=3)\n\txplot <- legend(legposition, c(\"1849 red circle\", \"1854 blue triangle\", \"predicted\"), col = c(2, 4, 1),\n text.col = c(\"red\",\"blue\",\"black\"), lty = c(0, 0, 3), pch = c(19, 17, 1),\n merge = TRUE,bty=\"o\",bg=\"white\") # The bty=\"o\" should overwrite the background\n}\n\n\n# 26-feb-20 add (optional) argument \"rateadj\" which can be set to either\n# - \"rateadj\" = 1854 rate adjusted for both year effect and treatment effect\n# - \"rateadjyr\" = 1854 adjusted only for year effect (not treaement effect)\n# 22-jul-20 add (optional) argument \"yearadj\" which can be set to either 1849 or 1854\n# - \"1849\" - display base 1849, adjust 1854 back to 1849 by year effect and treatment\n# - \"1854\" - display base 1854, adjust 1849 forward to 1854by year (no adjustment) and treatment)\nplot3 <- function(confidata1849,confidata1854,xsupplier,title,legposition=\"bottomright\",rateadj=\"rateadj\",yearadj=\"1849\") { \n\tif (yearadj == \"1849\") {\n\t\txmean <- subset(confidata1849,supplier==xsupplier)[,\"rate\"]\n\t\txlimdn <- subset(confidata1849,supplier==xsupplier)[,\"limdn\"]\n\t\txlimup <- subset(confidata1849,supplier==xsupplier)[,\"limup\"]\n\t\txpred <- subset(confidata1849,supplier==xsupplier)[,\"predrate\"]\n\t\tyseq <- subset(confidata1849,supplier==xsupplier)[,\"seq\"]\n\t\tx1854adj <- subset(confidata1854,supplier==xsupplier)[,rateadj]\n\t}\n\telse {\n\t\txmean <- subset(confidata1849,supplier==xsupplier)[,rateadj]\n\t\txlimdn <- subset(confidata1854,supplier==xsupplier)[,\"limdn\"]\n\t\txlimup <- subset(confidata1854,supplier==xsupplier)[,\"limup\"]\n\t\txpred <- subset(confidata1854,supplier==xsupplier)[,\"predrate\"]\n\t\tyseq <- subset(confidata1854,supplier==xsupplier)[,\"seq\"]\n\t\tx1854adj <- subset(confidata1854,supplier==xsupplier)[,\"rate\"]\n\t}\n\txplot <- plot3_worker(yseq,xmean, xpred,xlimdn,xlimup,x1854adj,title,legposition)\n\t# xplot <- plot(xmean, y,\n\t# xlim=range(c(xmean, xpred,xlimdn,xlimup,x1854adj)),\n\t# ylim=rev(range(y)), col=\"red\", \n\t# main=title,xlab=\"Mortality per 10,000 population\",ylab=\"sub-district\",\n\t# pch=19)\n\t# lines(xpred, y, type=\"p\",\n\t# xlim=range(c(xmean, xpred,xlimdn,xlimup)),\n\t# ylim=rev(range(y)), \n\t# pch=1)\n\t# lines(x1854adj, y, type=\"p\",\n\t# xlim=range(c(xmean, xpred,xlimdn,xlimup)),\n\t# ylim=rev(range(y)), col=\"blue\", \n\t# pch=17)\n\n\t# # horizontal error bars\n\t# xplot <- arrows(xlimdn, y, xlimup, y, length=0.05, angle=90, code=3,lty=3)\n\t# xplot <- legend(legposition, c(\"1849 red circle\", \"1854 blue triangle\", \"predicted\"), col = c(2, 4, 1),\n # text.col = c(\"red\",\"blue\",\"black\"), lty = c(0, 0, 3), pch = c(19, 17, 1),\n # merge = TRUE,bty=\"o\",bg=\"white\") # The bty=\"o\" should overwrite the background\n\n}\n\n# Plotting joint region for 1849 & 1854 with error bars for each\nplotcomp <- function(confidata1849,confidata1854,xsupplier,title,legposition=\"bottomright\") { \n\txmean <- subset(confidata1849,supplier==xsupplier)[,\"rate\"]\n\txlimdn <- subset(confidata1849,supplier==xsupplier)[,\"limdnact\"]\n\txlimup <- subset(confidata1849,supplier==xsupplier)[,\"limupact\"]\n\txpred <- subset(confidata1849,supplier==xsupplier)[,\"predrate\"]\n\ty <- subset(confidata1849,supplier==xsupplier)[,\"seq\"]\n\txmean1854 <- subset(confidata1854,supplier==xsupplier)[,\"rateadjyr\"]\n#\txlimdn1854 <- subset(confidata1854,supplier==xsupplier)[,\"limdn\"]\n#\txlimup1854 <- subset(confidata1854,supplier==xsupplier)[,\"limup\"]\n\txplot <- plot(xmean, y,\n\t xlim=range(c(xmean, xmean1854,xlimdn,xlimup)),\n\t ylim=rev(range(y)), col=\"red\",\n\t main=title,xlab=\"Mortality: 1849 red circle, 1854 blue diamond\",ylab=\"sub-district\",\n\t pch=19)\n\tlines(xmean1854, y, type=\"p\",\n\t xlim=range(c(xmean, xmean1854,xlimdn,xlimup)),\n\t ylim=rev(range(y)), col=\"blue\",\n\t pch=17)\n\n\t# horizontal error bars\n\txplot <- arrows(xlimdn, y, xlimup, y, length=0.05, angle=90, code=3,,lty=3)\n\txplot <- legend(legposition, c(\"1849 red circle\", \"1854 blue triangle\"), col = c(2, 4),\n text.col = c(\"red\",\"blue\"), lty = c(0, 0), pch = c(19, 17),\n bty=\"o\",bg=\"white\") # The bty=\"o\" should overwrite the background\n\n#\txplot <- arrows(xlimdn1854, y, xlimup1854, y, length=0.05, angle=90, code=3)\n}\n\n\nploterrbars <- function(fittedmodel,plotname,single = \"single\") { # This is not a good way to do this because I am \n\t # changing globals from within the function (using <<- \n\t # instead of <-)\n\txfamily <- preperrdata(fittedmodel,single) # this function modifies global data\n\n\tpdf(paste(\"../paper/figures/errbar_\",plotname,\"a.pdf\",sep=\"\"))\n\t\tplot2(x1849,\"SouthwarkVauxhall\",paste(\"First-12 Southwark-only \",xfamily,\" 1849 \"))\n\tdev.off()\n\tpdf(paste(\"../paper/figures/errbar_\",plotname,\"b.pdf\",sep=\"\"))\n\t\tplot2(x1849,\"SouthwarkVauxhall_Lambeth\",paste(\"Next-16 Jointly-Supplied \",xfamily,\" 1849 \"))\n\tdev.off()\n\tpdf(paste(\"../paper/figures/errbar_\",plotname,\"c.pdf\",sep=\"\"))\n\t\tplot3(x1849,x1854,\"SouthwarkVauxhall\",paste(\"First-12 Southwark-only \",xfamily,\" 1849vs1854 \"))\n\tdev.off()\n\tpdf(paste(\"../paper/figures/errbar_\",plotname,\"d.pdf\",sep=\"\"))\n\t\tplot3(x1849,x1854,\"SouthwarkVauxhall_Lambeth\",paste(\"Next-16 Jointly-Supplied \",xfamily,\" 1849vs1854 \"))\n\tdev.off()\n\tif (xfamily != \"poisson\") { # Plot comparison for joint region only for Negative Binomial\n\t\tpdf(paste(\"../paper/figures/errbar_\",plotname,\"e.pdf\",sep=\"\"))\n\t\t\tplotcomp(x1849,x1854,\"SouthwarkVauxhall\",paste(\"First-12 Southwark-only \",xfamily,\" 1849vs1854 \"))\n\t\tdev.off()\n\t\tpdf(paste(\"../paper/figures/errbar_\",plotname,\"f.pdf\",sep=\"\"))\n\t\t\tplotcomp(x1849,x1854,\"SouthwarkVauxhall_Lambeth\",paste(\"Next-16 Jointly-Supplied \",xfamily,\" 1849vs1854 \"))\n\t\tdev.off()\n\t}\n\n}\n\n\n\n", "meta": {"hexsha": "b34e87039418301dcec7177755a5d10ebd383d81", "size": 17017, "ext": "r", "lang": "R", "max_stars_repo_path": "Snow_PlotFns.r", "max_stars_repo_name": "tscoleman/SnowCholera", "max_stars_repo_head_hexsha": "7fc024ab42e29f94f67a7fc312cdce92998ba5f6", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": 7, "max_stars_repo_stars_event_min_datetime": "2019-04-08T22:58:30.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-18T14:57:00.000Z", "max_issues_repo_path": "Snow_PlotFns.r", "max_issues_repo_name": "tscoleman/SnowCholera", "max_issues_repo_head_hexsha": "7fc024ab42e29f94f67a7fc312cdce92998ba5f6", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Snow_PlotFns.r", "max_forks_repo_name": "tscoleman/SnowCholera", "max_forks_repo_head_hexsha": "7fc024ab42e29f94f67a7fc312cdce92998ba5f6", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-02-07T10:59:14.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-07T10:59:14.000Z", "avg_line_length": 50.6458333333, "max_line_length": 156, "alphanum_fraction": 0.680907328, "num_tokens": 5631, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7371581741774411, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.38009343564390424}} {"text": "# *****************************************************************\r\n# *************** Population Dynamics Modeling ********************\r\n# ******************* UTR Lake Sturgeon ***************************\r\n# ****************** Author: Dan Walker ***************************\r\n# ****************** Began on 27/06/2017 **************************\r\n# *****************************************************************\r\n\r\n# FINAL CODE - see popdy_scratch for development and testing\r\n\r\nsetwd(\"C:/Users/danwa/OneDrive/Research/Lake Sturgeon/Chapter3/LST Data/LST ABundance\")\r\nset.seed(865)\r\n\r\n\r\n# Data from RMark POPAN Jolly-Seber MLE solution:\r\n# Total UTR population in 2011: 5643\r\n# Weight class - above/below 2500 g\r\n# Length class - <650 mm TL, 650 - 950 mm TL, >950 mm TL\r\n# Phi(survival) for heavy.avg.length = ~100%\r\n# Phi for skinny, average length = 0.42 (0.15 - 0.75 95% CI)\r\n\r\n\r\n# Annual releases\r\nrelease = read.csv(\"UTR.yearly.release.csv\")\r\nplot(release)\r\nsummary(release) # releases ~ N(8862, 3616.236^2)\r\n# 124,069 fish released 2000-2013\r\n\r\n# 20 year classes >15 y.o. (SLSWG) = stock until 2035\r\naddtl.releases = 22\r\n\r\nsim.releases = as.integer(rnorm(addtl.releases, 8862, 3616.236))\r\nyear = 2014:2035\r\nsim.releases.df = data.frame(year, sim.releases)\r\ncolnames(sim.releases.df) = c(\"Year\", \"count.released\")\r\nfull.sim.release = rbind(release, sim.releases.df)\r\n\r\nfull.sim.release[15,2]= 14615\r\nfull.sim.release[16,2]= 16308\r\n\r\n# ************************************************************\r\n# end of data entry necessary for Simulation procedures\r\n# ************************************************************\r\n\r\nwrite.csv(full.sim.release, \"full.sim.release.csv\")\r\n\r\nplot(full.sim.release,\r\n pch = ifelse(full.sim.release$Year >= 2016, 1, 16))\r\ntitle(main = \"Number of Reintroduced Lake Sturgeon\")\r\n\r\nmean(full.sim.release$count.released) # 9,163 fish released per year on average\r\nsum(full.sim.release$count.released) # 329,872 fish released total\r\n\r\n# Catch data\r\nlibrary(readxl)\r\ncatch = read_excel(\"CaptureData2.xlsx\", sheet = 3)\r\nView(catch)\r\nl_a = na.omit(data.frame(catch$TL.mm, catch$Age.caught))\r\ncolnames(l_a)<-c(\"TL\", \"Age\")\r\nView(l_a)\r\n\r\nboxplot(TL~Age, data = l_a)\r\nplot(TL~Age, data = l_a)\r\ntitle(main = \"Lake Sturgeon Length at Age\")\r\n\r\n# fit a cubic polynomial to the data NEEDS WORK\r\nl_a_cube = lm(TL~poly(Age, 3), data = l_a)\r\nsummary(l_a_cube)\r\n\r\nlm.test = data.frame(l_a$Age)\r\npred.cubic = predict(l_a_cube, x = lm.test, interval = 'confidence', level = 0.99)\r\n\r\nplot(TL~Age, data = l_a)\r\ntitle(main = \"Lake Sturgeon Length at Age\")\r\nabline(l_a_cube)\r\n\r\nlines(pred.cubic[, 1], col = \"black\", lwd = 3)\r\n\r\n\r\ncubic = function(x){\r\n 781.7 + 1047.7*(x) + 123.6*(x^2) - 445.9*(x^3)\r\n}\r\nx = l_a$Age\r\n\r\ny = cubic(x)\r\n\r\nplot(x, y)\r\n\r\n# VB growth curve\r\n\r\n# *************************************************\r\n# ****************** PopDy ************************\r\n# *************************************************\r\n\r\n# initialize storage matrix, constants\r\nsim.mat = matrix(nrow = 1000, ncol = 36)\r\nS.full = as.vector(seq(from = 0.15, to = 0.75, by = 0.01))\r\nZ.full = -log(S.full) #remove step if Z's are changed\r\ni = seq(from = 1 , to = 1000, by = 1000)\r\nm = matrix(0, nrow = 36, ncol = 36)\r\n# m\r\nstock.numbers = full.sim.release[ ,2]\r\ndiag(m)<- stock.numbers\r\nm[upper.tri(m)]<- NA #upper triangular matrix = NA, lower = 0, diag = stocking #s\r\n\r\n# *************************************************\r\n# *************** Simulation *********************\r\n# *************************************************\r\nsetwd(\"C:/Users/danwa/OneDrive/Research/Lake Sturgeon/Chapter3/LST Data/LST ABundance\")\r\nset.seed(865)\r\nrelease = read.csv(\"UTR.yearly.release.csv\")\r\n\r\n\r\n# Necessary functions:\r\n# 1\r\nfish.at.age = function(x){\r\n \r\n non.na.index = as.integer(min(which(!is.na(x$N)))) #find first year of stocking\r\n \r\n if(non.na.index < 36){\r\n x$t = x$t - non.na.index #adjust t to reflect first year\r\n x = x[complete.cases(x), ] #remove NAs\r\n for(d in 1:(nrow(x)-1)){\r\n x$N[d+1] = round(x$N[d]*exp((-x$Z[d]*x$t[d+1])))\r\n } \r\n } else {\r\n x$N = as.integer(rnorm(1, 8862, 3616.236))\r\n }\r\n return(x)\r\n} \r\n\r\n\r\n# 2\r\nna.pad = function(x, lent){\r\n x[1:lent]\r\n} \r\n\r\n# 3\r\nrotate = function(x){\r\n t(apply(x, 2, rev))\r\n}\r\n\r\n# Simulation - fixed N0, variable Z\r\n# initialize storage matrix, constants\r\nsim.mat = matrix(nrow = 1000, ncol = 36)\r\nS.full = as.vector(seq(from = 0.15, to = 0.75, by = 0.01))\r\nZ.full = -log(S.full) #remove step if Z's are changed\r\ni = seq(from = 1, to = 1000, by = 1)\r\nm = matrix(0, nrow = 36, ncol = 36)\r\n# m\r\nstock.numbers = full.sim.release[ ,2]\r\ndiag(m)<- stock.numbers\r\nm[upper.tri(m)]<- NA #upper triangular matrix = NA, lower = 0, diag = stocking #s\r\n\r\nfor(i in 1:1000){ #iterate 1000x simulations\r\n \r\n single.sim.result = matrix(NA, nrow = 36, ncol = 36) # initialize storage dataframe for output\r\n lent = 36\r\n \r\n for(n in 1:ncol(m)){ #iterate over all columns\r\n \r\n test.col = m[ , n]\r\n N = as.integer(test.col)\r\n df = as.data.frame(N)\r\n df$Z = sample(Z.full, 36) #tweak value here to lower mortality rate\r\n df$t = seq(from = 1, to = 36, by = 1)\r\n x = df\r\n \r\n if(n <= 35){\r\n x1 = fish.at.age(x)\r\n x1.exp = as.vector(na.pad(x1$N, lent))\r\n single.sim.result[ , n] = x1.exp\r\n } else {\r\n x$N[36] = as.integer(rnorm(1, 8862, 3616.236))\r\n x$N[1] <- x$N[36]\r\n x$N[36] <- NA\r\n single.sim.result[ , n] = x$N\r\n }\r\n }\r\n \r\n rott = rotate(single.sim.result)\r\n sim.resul = diag(rott)\r\n sim.resul.t = t(sim.resul)\r\n \r\n sim.mat[i, ] = sim.resul.t \r\n \r\n \r\n}\r\n\r\nView(sim.mat)\r\n\r\nwrite.csv(sim.mat, \"Fixed_N0_Varying_Z.csv\")\r\n\r\n# **********************************************************\r\n# ************ first complete run 20/07/2017 ***************\r\n# **********************************************************\r\n# **********************************************************\r\n\r\n# RESET ENVIRONMENT BEFORE RUNNING SECOND SIM!!!\r\n\r\n# **********************************************************\r\n# Simulation with fixed N0, fixed Z\r\n# **********************************************************\r\nsetwd(\"C:/Users/danwa/OneDrive/Research/Lake Sturgeon/Chapter3/LST Data/LST ABundance\")\r\nset.seed(865)\r\nrelease = read.csv(\"UTR.yearly.release.csv\")\r\n\r\n# New central function:\r\n\r\nfish.age.fixedZ = function(x){\r\n \r\n if(non.na.index < 36){\r\n x = x[complete.cases(x), ] #remove NAs\r\n for(d in 1:(nrow(x)-1)){\r\n x$N[d+1] = round(x$N[d]*exp((-x$Z[d]*x$t[d+1])))\r\n }\r\n # N.export = as.vector(x$N)\r\n return(x)\r\n } \r\n else {\r\n x$N = as.integer(rnorm(1, 8862, 3616.236))\r\n }\r\n} \r\n# 2\r\nna.pad = function(x, lent){\r\n x[1:lent]\r\n} \r\n\r\n# 3\r\nrotate = function(x){\r\n t(apply(x, 2, rev))\r\n}\r\n\r\n\r\n\r\n# initialize storage matrix, constants\r\nsim.mat = matrix(nrow = 1000, ncol = 36)\r\nS.full = as.vector(seq(from = 0.15, to = 0.75, by = 0.01))\r\nZ.full = -log(S.full) #remove step if Z's are changed\r\ni = seq(from = 1, to = 1000, by = 1)\r\nm = matrix(0, nrow = 36, ncol = 36)\r\n# m\r\nstock.numbers = full.sim.release[ ,2]\r\ndiag(m)<- stock.numbers\r\nm[upper.tri(m)]<- NA #upper triangular matrix = NA, lower = 0, diag = stocking #s\r\n\r\nfor(i in 1:1000){ #iterate 1000x simulations\r\n \r\n single.sim.result = matrix(NA, nrow = 36, ncol = 36) # initialize storage dataframe for output\r\n lent = 36\r\n \r\n for(n in 1:ncol(m)){ #iterate over all columns\r\n \r\n test.col = m[ , n]\r\n N = as.integer(test.col)\r\n df = as.data.frame(N)\r\n df$t = seq(from = 1, to = 36, by = 1)\r\n x = df\r\n non.na.index = as.integer(min(which(!is.na(x$N)))) #find first year of stocking\r\n x$t = x$t - non.na.index #adjust t to reflect first year\r\n if(n < 36){\r\n x = x[complete.cases(x), ]\r\n }\r\n x$Z = ifelse(x$t <= 3, -log(0.75), -log(0.99))\r\n \r\n if(n <= 35){\r\n x1 = fish.age.fixedZ(x)\r\n x1.exp = as.vector(na.pad(x1$N, lent))\r\n single.sim.result[ , n] = x1.exp\r\n } else {\r\n x$N[36] = as.integer(rnorm(1, 8862, 3616.236))\r\n x$N[1] <- x$N[36]\r\n x$N[36] <- NA\r\n single.sim.result[ , n] = x$N\r\n }\r\n \r\n }\r\n \r\n rott = rotate(single.sim.result)\r\n sim.resul = diag(rott)\r\n sim.resul.t = t(sim.resul)\r\n \r\n sim.mat[i, ] = sim.resul.t \r\n \r\n \r\n}\r\n\r\nView(sim.mat)\r\nwrite.csv(sim.mat, file = \"Fixed_Z_Fixed_N0.csv\")\r\n\r\n# *************************************************************\r\n# simulation with varying N0, fixed Z\r\n# *************************************************************\r\nsetwd(\"C:/Users/danwa/OneDrive/Research/Lake Sturgeon/Chapter3/LST Data/LST ABundance\")\r\nset.seed(865)\r\nrelease = read.csv(\"UTR.yearly.release.csv\")\r\n\r\nfish.age.fixedZ = function(x){\r\n \r\n if(non.na.index < 36){\r\n x = x[complete.cases(x), ] #remove NAs\r\n for(d in 1:(nrow(x)-1)){\r\n x$N[d+1] = round(x$N[d]*exp((-x$Z[d]*x$t[d+1])))\r\n }\r\n # N.export = as.vector(x$N)\r\n return(x)\r\n } \r\n else {\r\n x$N = as.integer(rnorm(1, 8862, 3616.236))\r\n }\r\n} \r\n# 2\r\nna.pad = function(x, lent){\r\n x[1:lent]\r\n} \r\n\r\n# 3\r\nrotate = function(x){\r\n t(apply(x, 2, rev))\r\n}\r\n\r\n\r\nsim.mat = matrix(nrow = 1000, ncol = 36)\r\naddtl.releases = 22\r\nfor(j in 1:1000){ \r\n # create new simulated release numbers\r\n sim.releases = as.integer(rnorm(addtl.releases, 8862, 3616.236))\r\n year = 2014:2035\r\n sim.releases.df = data.frame(year, sim.releases)\r\n colnames(sim.releases.df) = c(\"Year\", \"count.released\")\r\n sim.releases.df = rbind(release, sim.releases.df)\r\n \r\n sim.releases.df[15,2]= 14615\r\n sim.releases.df[16,2]= 16308\r\n \r\n m = matrix(0, nrow = 36, ncol = 36)\r\n stock.numbers = sim.releases.df[ ,2]\r\n diag(m)<- stock.numbers\r\n m[upper.tri(m)]<- NA #upper triangular matrix = NA, lower = 0, diag = stocking #s\r\n \r\n single.sim.result = matrix(NA, nrow = 36, ncol = 36) # initialize storage dataframe for output\r\n lent = 36\r\n \r\n for(n in 1:ncol(m)){ #iterate over all columns\r\n \r\n test.col = m[ , n]\r\n N = as.integer(test.col)\r\n df = as.data.frame(N)\r\n df$t = seq(from = 1, to = 36, by = 1)\r\n x = df\r\n non.na.index = as.integer(min(which(!is.na(x$N)))) #find first year of stocking\r\n x$t = x$t - non.na.index #adjust t to reflect first year\r\n if(n < 36){\r\n x = x[complete.cases(x), ]\r\n }\r\n x$Z = ifelse(x$t <= 3, -log(0.75), -log(0.99))\r\n \r\n if(n <= 35){\r\n x1 = fish.age.fixedZ(x)\r\n x1.exp = as.vector(na.pad(x1$N, lent))\r\n single.sim.result[ , n] = x1.exp\r\n } else {\r\n x$N[36] = as.integer(rnorm(1, 8862, 3616.236))\r\n x$N[1] <- x$N[36]\r\n x$N[36] <- NA\r\n single.sim.result[ , n] = x$N\r\n }\r\n \r\n }\r\n \r\n rott = rotate(single.sim.result)\r\n sim.resul = diag(rott)\r\n sim.resul.t = t(sim.resul)\r\n \r\n sim.mat[j, ] = sim.resul.t \r\n \r\n \r\n}\r\nView(sim.mat)\r\nsim.mat[sim.mat<0] <- 0\r\nwrite.csv(sim.mat, file = \"Fixed_Z_Varying_N0.csv\")\r\n\r\n\r\n# *************************************************************\r\n# simulation with varying N0, fixed Z, doubled reintroductions\r\n# *************************************************************\r\nsetwd(\"C:/Users/danwa/OneDrive/Research/Lake Sturgeon/Chapter3/LST Data/LST ABundance\")\r\nset.seed(865)\r\nrelease = read.csv(\"UTR.yearly.release.csv\")\r\n\r\nfish.age.fixedZ = function(x){\r\n \r\n if(non.na.index < 36){\r\n x = x[complete.cases(x), ] #remove NAs\r\n for(d in 1:(nrow(x)-1)){\r\n x$N[d+1] = round(x$N[d]*exp((-x$Z[d]*x$t[d+1])))\r\n }\r\n # N.export = as.vector(x$N)\r\n return(x)\r\n } \r\n else {\r\n x$N = as.integer(rnorm(1, (2*8862), 3616.236))\r\n }\r\n} \r\n# 2\r\nna.pad = function(x, lent){\r\n x[1:lent]\r\n} \r\n\r\n# 3\r\nrotate = function(x){\r\n t(apply(x, 2, rev))\r\n}\r\n\r\n\r\nsim.mat = matrix(nrow = 1000, ncol = 36)\r\naddtl.releases = 22\r\nfor(j in 1:1000){ \r\n # create new simulated release numbers\r\n sim.releases = as.integer(rnorm(addtl.releases, (8862*2), 3616.236))\r\n year = 2014:2035\r\n sim.releases.df = data.frame(year, sim.releases)\r\n colnames(sim.releases.df) = c(\"Year\", \"count.released\")\r\n sim.releases.df = rbind(release, sim.releases.df)\r\n \r\n sim.releases.df[15,2]= 14615\r\n sim.releases.df[16,2]= 16308\r\n \r\n m = matrix(0, nrow = 36, ncol = 36)\r\n stock.numbers = sim.releases.df[ ,2]\r\n diag(m)<- stock.numbers\r\n m[upper.tri(m)]<- NA #upper triangular matrix = NA, lower = 0, diag = stocking #s\r\n \r\n single.sim.result = matrix(NA, nrow = 36, ncol = 36) # initialize storage dataframe for output\r\n lent = 36\r\n \r\n for(n in 1:ncol(m)){ #iterate over all columns\r\n \r\n test.col = m[ , n]\r\n N = as.integer(test.col)\r\n df = as.data.frame(N)\r\n df$t = seq(from = 1, to = 36, by = 1)\r\n x = df\r\n non.na.index = as.integer(min(which(!is.na(x$N)))) #find first year of stocking\r\n x$t = x$t - non.na.index #adjust t to reflect first year\r\n if(n < 36){\r\n x = x[complete.cases(x), ]\r\n }\r\n x$Z = ifelse(x$t <= 3, -log(0.75), -log(0.99))\r\n \r\n if(n <= 35){\r\n x1 = fish.age.fixedZ(x)\r\n x1.exp = as.vector(na.pad(x1$N, lent))\r\n single.sim.result[ , n] = x1.exp\r\n } else {\r\n x$N[36] = as.integer(rnorm(1, 8862, 3616.236))\r\n x$N[1] <- x$N[36]\r\n x$N[36] <- NA\r\n single.sim.result[ , n] = x$N\r\n }\r\n \r\n }\r\n \r\n rott = rotate(single.sim.result)\r\n sim.resul = diag(rott)\r\n sim.resul.t = t(sim.resul)\r\n \r\n sim.mat[j, ] = sim.resul.t \r\n \r\n \r\n}\r\nView(sim.mat)\r\nsim.mat[sim.mat<0] <- 0\r\nwrite.csv(sim.mat, file = \"Fixed_Z_Varying_N0_2xReintro.csv\")\r\n\r\n\r\n", "meta": {"hexsha": "352e76ea88f7365b59fbb9827c5ae26bfa6b1df6", "size": 13370, "ext": "r", "lang": "R", "max_stars_repo_path": "PopDy.r", "max_stars_repo_name": "dwalke44/LSTsimulations", "max_stars_repo_head_hexsha": "1efd77091adcde9d37febc6cb9fc0e1ca0b30775", "max_stars_repo_licenses": ["BSD-2-Clause"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "PopDy.r", "max_issues_repo_name": "dwalke44/LSTsimulations", "max_issues_repo_head_hexsha": "1efd77091adcde9d37febc6cb9fc0e1ca0b30775", "max_issues_repo_licenses": ["BSD-2-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "PopDy.r", "max_forks_repo_name": "dwalke44/LSTsimulations", "max_forks_repo_head_hexsha": "1efd77091adcde9d37febc6cb9fc0e1ca0b30775", "max_forks_repo_licenses": ["BSD-2-Clause"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 28.0882352941, "max_line_length": 97, "alphanum_fraction": 0.5305160808, "num_tokens": 4229, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585903489891, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.37980052528254044}} {"text": "score <- function(input) {\n var0 <- exp((-0.06389634699048878) * ((((((5.1) - (input[1])) ^ (2.0)) + (((3.3) - (input[2])) ^ (2.0))) + (((1.7) - (input[3])) ^ (2.0))) + (((0.5) - (input[4])) ^ (2.0))))\n var1 <- exp((-0.06389634699048878) * ((((((5.7) - (input[1])) ^ (2.0)) + (((2.6) - (input[2])) ^ (2.0))) + (((3.5) - (input[3])) ^ (2.0))) + (((1.0) - (input[4])) ^ (2.0))))\n return(c((subroutine0(input)) + ((var0) * (0.8898986041811555)), (subroutine1(input)) + ((var0) * (0.37953658977037247)), (subroutine2(input)) + ((var1) * (0.0))))\n}\nsubroutine0 <- function(input) {\n var0 <- exp((-0.06389634699048878) * ((((((5.1) - (input[1])) ^ (2.0)) + (((3.8) - (input[2])) ^ (2.0))) + (((1.9) - (input[3])) ^ (2.0))) + (((0.4) - (input[4])) ^ (2.0))))\n return((subroutine3(input)) + ((var0) * (0.8898986041811555)))\n}\nsubroutine1 <- function(input) {\n var0 <- exp((-0.06389634699048878) * ((((((5.1) - (input[1])) ^ (2.0)) + (((3.8) - (input[2])) ^ (2.0))) + (((1.9) - (input[3])) ^ (2.0))) + (((0.4) - (input[4])) ^ (2.0))))\n return((subroutine4(input)) + ((var0) * (0.37953658977037247)))\n}\nsubroutine2 <- function(input) {\n var0 <- exp((-0.06389634699048878) * ((((((5.9) - (input[1])) ^ (2.0)) + (((3.2) - (input[2])) ^ (2.0))) + (((4.8) - (input[3])) ^ (2.0))) + (((1.8) - (input[4])) ^ (2.0))))\n return((subroutine5(input)) + ((var0) * (110.34516826676301)))\n}\nsubroutine3 <- function(input) {\n var0 <- exp((-0.06389634699048878) * ((((((5.7) - (input[1])) ^ (2.0)) + (((4.4) - (input[2])) ^ (2.0))) + (((1.5) - (input[3])) ^ (2.0))) + (((0.4) - (input[4])) ^ (2.0))))\n return((subroutine6(input)) + ((var0) * (0.0)))\n}\nsubroutine4 <- function(input) {\n var0 <- exp((-0.06389634699048878) * ((((((5.7) - (input[1])) ^ (2.0)) + (((4.4) - (input[2])) ^ (2.0))) + (((1.5) - (input[3])) ^ (2.0))) + (((0.4) - (input[4])) ^ (2.0))))\n return((subroutine7(input)) + ((var0) * (0.05610417372785803)))\n}\nsubroutine5 <- function(input) {\n var0 <- exp((-0.06389634699048878) * ((((((6.0) - (input[1])) ^ (2.0)) + (((2.7) - (input[2])) ^ (2.0))) + (((5.1) - (input[3])) ^ (2.0))) + (((1.6) - (input[4])) ^ (2.0))))\n return((subroutine8(input)) + ((var0) * (110.34516826676301)))\n}\nsubroutine6 <- function(input) {\n var0 <- exp((-0.06389634699048878) * ((((((4.5) - (input[1])) ^ (2.0)) + (((2.3) - (input[2])) ^ (2.0))) + (((1.3) - (input[3])) ^ (2.0))) + (((0.3) - (input[4])) ^ (2.0))))\n return((subroutine9(input)) + ((var0) * (0.8898986041811555)))\n}\nsubroutine7 <- function(input) {\n var0 <- exp((-0.06389634699048878) * ((((((4.5) - (input[1])) ^ (2.0)) + (((2.3) - (input[2])) ^ (2.0))) + (((1.3) - (input[3])) ^ (2.0))) + (((0.3) - (input[4])) ^ (2.0))))\n return((subroutine10(input)) + ((var0) * (0.3044555865539922)))\n}\nsubroutine8 <- function(input) {\n var0 <- exp((-0.06389634699048878) * ((((((5.0) - (input[1])) ^ (2.0)) + (((2.3) - (input[2])) ^ (2.0))) + (((3.3) - (input[3])) ^ (2.0))) + (((1.0) - (input[4])) ^ (2.0))))\n return((subroutine11(input)) + ((var0) * (0.0)))\n}\nsubroutine9 <- function(input) {\n var0 <- exp((-0.06389634699048878) * ((((((4.8) - (input[1])) ^ (2.0)) + (((3.4) - (input[2])) ^ (2.0))) + (((1.9) - (input[3])) ^ (2.0))) + (((0.2) - (input[4])) ^ (2.0))))\n return((subroutine12(input)) + ((var0) * (0.8898986041811555)))\n}\nsubroutine10 <- function(input) {\n var0 <- exp((-0.06389634699048878) * ((((((4.8) - (input[1])) ^ (2.0)) + (((3.4) - (input[2])) ^ (2.0))) + (((1.9) - (input[3])) ^ (2.0))) + (((0.2) - (input[4])) ^ (2.0))))\n return((subroutine13(input)) + ((var0) * (0.37953658977037247)))\n}\nsubroutine11 <- function(input) {\n var0 <- exp((-0.06389634699048878) * ((((((6.7) - (input[1])) ^ (2.0)) + (((3.0) - (input[2])) ^ (2.0))) + (((5.0) - (input[3])) ^ (2.0))) + (((1.7) - (input[4])) ^ (2.0))))\n return((subroutine14(input)) + ((var0) * (110.34516826676301)))\n}\nsubroutine12 <- function(input) {\n var0 <- exp((-0.06389634699048878) * ((((((5.7) - (input[1])) ^ (2.0)) + (((3.8) - (input[2])) ^ (2.0))) + (((1.7) - (input[3])) ^ (2.0))) + (((0.3) - (input[4])) ^ (2.0))))\n return((subroutine15(input)) + ((var0) * (0.0)))\n}\nsubroutine13 <- function(input) {\n var0 <- exp((-0.06389634699048878) * ((((((5.7) - (input[1])) ^ (2.0)) + (((3.8) - (input[2])) ^ (2.0))) + (((1.7) - (input[3])) ^ (2.0))) + (((0.3) - (input[4])) ^ (2.0))))\n return((subroutine16(input)) + ((var0) * (0.37953658977037247)))\n}\nsubroutine14 <- function(input) {\n var0 <- exp((-0.06389634699048878) * ((((((5.6) - (input[1])) ^ (2.0)) + (((2.9) - (input[2])) ^ (2.0))) + (((3.6) - (input[3])) ^ (2.0))) + (((1.3) - (input[4])) ^ (2.0))))\n return((subroutine17(input)) + ((var0) * (0.0)))\n}\nsubroutine15 <- function(input) {\n var0 <- exp((-0.06389634699048878) * ((((((5.4) - (input[1])) ^ (2.0)) + (((3.4) - (input[2])) ^ (2.0))) + (((1.7) - (input[3])) ^ (2.0))) + (((0.2) - (input[4])) ^ (2.0))))\n return((subroutine18(input)) + ((var0) * (0.7142250613852136)))\n}\nsubroutine16 <- function(input) {\n var0 <- exp((-0.06389634699048878) * ((((((5.4) - (input[1])) ^ (2.0)) + (((3.4) - (input[2])) ^ (2.0))) + (((1.7) - (input[3])) ^ (2.0))) + (((0.2) - (input[4])) ^ (2.0))))\n return((subroutine19(input)) + ((var0) * (0.0)))\n}\nsubroutine17 <- function(input) {\n var0 <- exp((-0.06389634699048878) * ((((((6.2) - (input[1])) ^ (2.0)) + (((2.2) - (input[2])) ^ (2.0))) + (((4.5) - (input[3])) ^ (2.0))) + (((1.5) - (input[4])) ^ (2.0))))\n return((subroutine20(input)) + ((var0) * (37.19509025661546)))\n}\nsubroutine18 <- function(input) {\n var0 <- exp((-0.06389634699048878) * ((((((5.0) - (input[1])) ^ (2.0)) + (((3.0) - (input[2])) ^ (2.0))) + (((1.6) - (input[3])) ^ (2.0))) + (((0.2) - (input[4])) ^ (2.0))))\n return((subroutine21(input)) + ((var0) * (0.04218875216876044)))\n}\nsubroutine19 <- function(input) {\n var0 <- exp((-0.06389634699048878) * ((((((5.0) - (input[1])) ^ (2.0)) + (((3.0) - (input[2])) ^ (2.0))) + (((1.6) - (input[3])) ^ (2.0))) + (((0.2) - (input[4])) ^ (2.0))))\n return((subroutine22(input)) + ((var0) * (0.0)))\n}\nsubroutine20 <- function(input) {\n var0 <- exp((-0.06389634699048878) * ((((((5.4) - (input[1])) ^ (2.0)) + (((3.0) - (input[2])) ^ (2.0))) + (((4.5) - (input[3])) ^ (2.0))) + (((1.5) - (input[4])) ^ (2.0))))\n return((subroutine23(input)) + ((var0) * (62.115561183470184)))\n}\nsubroutine21 <- function(input) {\n var0 <- exp((-0.06389634699048878) * ((((((5.7) - (input[1])) ^ (2.0)) + (((2.6) - (input[2])) ^ (2.0))) + (((3.5) - (input[3])) ^ (2.0))) + (((1.0) - (input[4])) ^ (2.0))))\n return((subroutine24(input)) + ((var0) * (-0.8898986041811555)))\n}\nsubroutine22 <- function(input) {\n var0 <- exp((-0.06389634699048878) * ((((((6.3) - (input[1])) ^ (2.0)) + (((2.8) - (input[2])) ^ (2.0))) + (((5.1) - (input[3])) ^ (2.0))) + (((1.5) - (input[4])) ^ (2.0))))\n return((subroutine25(input)) + ((var0) * (-0.0)))\n}\nsubroutine23 <- function(input) {\n var0 <- exp((-0.06389634699048878) * ((((((6.3) - (input[1])) ^ (2.0)) + (((2.5) - (input[2])) ^ (2.0))) + (((4.9) - (input[3])) ^ (2.0))) + (((1.5) - (input[4])) ^ (2.0))))\n return((subroutine26(input)) + ((var0) * (110.34516826676301)))\n}\nsubroutine24 <- function(input) {\n var0 <- exp((-0.06389634699048878) * ((((((5.9) - (input[1])) ^ (2.0)) + (((3.2) - (input[2])) ^ (2.0))) + (((4.8) - (input[3])) ^ (2.0))) + (((1.8) - (input[4])) ^ (2.0))))\n return((subroutine27(input)) + ((var0) * (-0.0)))\n}\nsubroutine25 <- function(input) {\n var0 <- exp((-0.06389634699048878) * ((((((6.0) - (input[1])) ^ (2.0)) + (((2.2) - (input[2])) ^ (2.0))) + (((5.0) - (input[3])) ^ (2.0))) + (((1.5) - (input[4])) ^ (2.0))))\n return((subroutine28(input)) + ((var0) * (-0.10077618026650095)))\n}\nsubroutine26 <- function(input) {\n var0 <- exp((-0.06389634699048878) * ((((((4.9) - (input[1])) ^ (2.0)) + (((2.4) - (input[2])) ^ (2.0))) + (((3.3) - (input[3])) ^ (2.0))) + (((1.0) - (input[4])) ^ (2.0))))\n return((subroutine29(input)) + ((var0) * (0.0)))\n}\nsubroutine27 <- function(input) {\n var0 <- exp((-0.06389634699048878) * ((((((6.0) - (input[1])) ^ (2.0)) + (((2.7) - (input[2])) ^ (2.0))) + (((5.1) - (input[3])) ^ (2.0))) + (((1.6) - (input[4])) ^ (2.0))))\n return((subroutine30(input)) + ((var0) * (-0.0)))\n}\nsubroutine28 <- function(input) {\n var0 <- exp((-0.06389634699048878) * ((((((6.2) - (input[1])) ^ (2.0)) + (((2.8) - (input[2])) ^ (2.0))) + (((4.8) - (input[3])) ^ (2.0))) + (((1.8) - (input[4])) ^ (2.0))))\n var1 <- exp((-0.06389634699048878) * ((((((7.2) - (input[1])) ^ (2.0)) + (((3.0) - (input[2])) ^ (2.0))) + (((5.8) - (input[3])) ^ (2.0))) + (((1.6) - (input[4])) ^ (2.0))))\n var2 <- exp((-0.06389634699048878) * ((((((6.1) - (input[1])) ^ (2.0)) + (((3.0) - (input[2])) ^ (2.0))) + (((4.9) - (input[3])) ^ (2.0))) + (((1.8) - (input[4])) ^ (2.0))))\n var3 <- exp((-0.06389634699048878) * ((((((6.0) - (input[1])) ^ (2.0)) + (((3.0) - (input[2])) ^ (2.0))) + (((4.8) - (input[3])) ^ (2.0))) + (((1.8) - (input[4])) ^ (2.0))))\n var4 <- exp((-0.06389634699048878) * ((((((4.9) - (input[1])) ^ (2.0)) + (((2.5) - (input[2])) ^ (2.0))) + (((4.5) - (input[3])) ^ (2.0))) + (((1.7) - (input[4])) ^ (2.0))))\n var5 <- exp((-0.06389634699048878) * ((((((7.9) - (input[1])) ^ (2.0)) + (((3.8) - (input[2])) ^ (2.0))) + (((6.4) - (input[3])) ^ (2.0))) + (((2.0) - (input[4])) ^ (2.0))))\n var6 <- exp((-0.06389634699048878) * ((((((5.6) - (input[1])) ^ (2.0)) + (((2.8) - (input[2])) ^ (2.0))) + (((4.9) - (input[3])) ^ (2.0))) + (((2.0) - (input[4])) ^ (2.0))))\n return((((((((-0.04261957451303831) + ((var0) * (-0.37953658977037247))) + ((var1) * (-0.0))) + ((var2) * (-0.0))) + ((var3) * (-0.37953658977037247))) + ((var4) * (-0.37953658977037247))) + ((var5) * (-0.26472396872040066))) + ((var6) * (-0.3745962010653211)))\n}\nsubroutine29 <- function(input) {\n var0 <- exp((-0.06389634699048878) * ((((((5.1) - (input[1])) ^ (2.0)) + (((2.5) - (input[2])) ^ (2.0))) + (((3.0) - (input[3])) ^ (2.0))) + (((1.1) - (input[4])) ^ (2.0))))\n return((subroutine31(input)) + ((var0) * (0.0)))\n}\nsubroutine30 <- function(input) {\n var0 <- exp((-0.06389634699048878) * ((((((5.0) - (input[1])) ^ (2.0)) + (((2.3) - (input[2])) ^ (2.0))) + (((3.3) - (input[3])) ^ (2.0))) + (((1.0) - (input[4])) ^ (2.0))))\n return((subroutine32(input)) + ((var0) * (-0.8898986041811555)))\n}\nsubroutine31 <- function(input) {\n var0 <- exp((-0.06389634699048878) * ((((((6.3) - (input[1])) ^ (2.0)) + (((2.8) - (input[2])) ^ (2.0))) + (((5.1) - (input[3])) ^ (2.0))) + (((1.5) - (input[4])) ^ (2.0))))\n return((subroutine33(input)) + ((var0) * (-110.34516826676301)))\n}\nsubroutine32 <- function(input) {\n var0 <- exp((-0.06389634699048878) * ((((((5.1) - (input[1])) ^ (2.0)) + (((2.5) - (input[2])) ^ (2.0))) + (((3.0) - (input[3])) ^ (2.0))) + (((1.1) - (input[4])) ^ (2.0))))\n var1 <- exp((-0.06389634699048878) * ((((((4.9) - (input[1])) ^ (2.0)) + (((2.4) - (input[2])) ^ (2.0))) + (((3.3) - (input[3])) ^ (2.0))) + (((1.0) - (input[4])) ^ (2.0))))\n var2 <- exp((-0.06389634699048878) * ((((((6.3) - (input[1])) ^ (2.0)) + (((2.5) - (input[2])) ^ (2.0))) + (((4.9) - (input[3])) ^ (2.0))) + (((1.5) - (input[4])) ^ (2.0))))\n var3 <- exp((-0.06389634699048878) * ((((((5.4) - (input[1])) ^ (2.0)) + (((3.0) - (input[2])) ^ (2.0))) + (((4.5) - (input[3])) ^ (2.0))) + (((1.5) - (input[4])) ^ (2.0))))\n var4 <- exp((-0.06389634699048878) * ((((((6.2) - (input[1])) ^ (2.0)) + (((2.2) - (input[2])) ^ (2.0))) + (((4.5) - (input[3])) ^ (2.0))) + (((1.5) - (input[4])) ^ (2.0))))\n var5 <- exp((-0.06389634699048878) * ((((((5.6) - (input[1])) ^ (2.0)) + (((2.9) - (input[2])) ^ (2.0))) + (((3.6) - (input[3])) ^ (2.0))) + (((1.3) - (input[4])) ^ (2.0))))\n var6 <- exp((-0.06389634699048878) * ((((((6.7) - (input[1])) ^ (2.0)) + (((3.0) - (input[2])) ^ (2.0))) + (((5.0) - (input[3])) ^ (2.0))) + (((1.7) - (input[4])) ^ (2.0))))\n return((((((((0.11172510039290856) + ((var0) * (-0.8898986041811555))) + ((var1) * (-0.8898986041811555))) + ((var2) * (-0.0))) + ((var3) * (-0.0))) + ((var4) * (-0.0))) + ((var5) * (-0.756413813553974))) + ((var6) * (-0.0)))\n}\nsubroutine33 <- function(input) {\n var0 <- exp((-0.06389634699048878) * ((((((6.0) - (input[1])) ^ (2.0)) + (((2.2) - (input[2])) ^ (2.0))) + (((5.0) - (input[3])) ^ (2.0))) + (((1.5) - (input[4])) ^ (2.0))))\n return((subroutine34(input)) + ((var0) * (-65.00217641452454)))\n}\nsubroutine34 <- function(input) {\n var0 <- exp((-0.06389634699048878) * ((((((6.2) - (input[1])) ^ (2.0)) + (((2.8) - (input[2])) ^ (2.0))) + (((4.8) - (input[3])) ^ (2.0))) + (((1.8) - (input[4])) ^ (2.0))))\n var1 <- exp((-0.06389634699048878) * ((((((7.2) - (input[1])) ^ (2.0)) + (((3.0) - (input[2])) ^ (2.0))) + (((5.8) - (input[3])) ^ (2.0))) + (((1.6) - (input[4])) ^ (2.0))))\n var2 <- exp((-0.06389634699048878) * ((((((6.1) - (input[1])) ^ (2.0)) + (((3.0) - (input[2])) ^ (2.0))) + (((4.9) - (input[3])) ^ (2.0))) + (((1.8) - (input[4])) ^ (2.0))))\n var3 <- exp((-0.06389634699048878) * ((((((6.0) - (input[1])) ^ (2.0)) + (((3.0) - (input[2])) ^ (2.0))) + (((4.8) - (input[3])) ^ (2.0))) + (((1.8) - (input[4])) ^ (2.0))))\n var4 <- exp((-0.06389634699048878) * ((((((4.9) - (input[1])) ^ (2.0)) + (((2.5) - (input[2])) ^ (2.0))) + (((4.5) - (input[3])) ^ (2.0))) + (((1.7) - (input[4])) ^ (2.0))))\n var5 <- exp((-0.06389634699048878) * ((((((7.9) - (input[1])) ^ (2.0)) + (((3.8) - (input[2])) ^ (2.0))) + (((6.4) - (input[3])) ^ (2.0))) + (((2.0) - (input[4])) ^ (2.0))))\n var6 <- exp((-0.06389634699048878) * ((((((5.6) - (input[1])) ^ (2.0)) + (((2.8) - (input[2])) ^ (2.0))) + (((4.9) - (input[3])) ^ (2.0))) + (((2.0) - (input[4])) ^ (2.0))))\n return((((((((1.8136162062461285) + ((var0) * (-110.34516826676301))) + ((var1) * (-13.999391039896215))) + ((var2) * (-108.44329471899991))) + ((var3) * (-110.34516826676301))) + ((var4) * (-22.21095753342801))) + ((var5) * (-0.0))) + ((var6) * (-0.0)))\n}\n", "meta": {"hexsha": "6dd3cbd001ea7e7278d7db820c626854bbfc8f81", "size": 14008, "ext": "r", "lang": "R", "max_stars_repo_path": "generated_code_examples/r/classification/svm.r", "max_stars_repo_name": "Symmetry-International/m2cgen", "max_stars_repo_head_hexsha": "3157e0cbd5bd1ee7e044a992223c60224e2b7709", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2161, "max_stars_repo_stars_event_min_datetime": "2019-01-13T02:37:56.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-30T13:24:09.000Z", "max_issues_repo_path": "generated_code_examples/r/classification/svm.r", "max_issues_repo_name": "Symmetry-International/m2cgen", "max_issues_repo_head_hexsha": "3157e0cbd5bd1ee7e044a992223c60224e2b7709", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 380, "max_issues_repo_issues_event_min_datetime": "2019-01-17T15:59:29.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-31T20:59:20.000Z", "max_forks_repo_path": "generated_code_examples/r/classification/svm.r", "max_forks_repo_name": "Symmetry-International/m2cgen", "max_forks_repo_head_hexsha": "3157e0cbd5bd1ee7e044a992223c60224e2b7709", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 201, "max_forks_repo_forks_event_min_datetime": "2019-02-13T19:06:44.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-12T09:45:46.000Z", "avg_line_length": 85.4146341463, "max_line_length": 265, "alphanum_fraction": 0.442318675, "num_tokens": 6261, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8652240930029118, "lm_q2_score": 0.4378234991142019, "lm_q1q2_score": 0.3788154399164465}} {"text": "# If you use this code or parts of it, please cite the following paper\n# Bruhin A., E. Fehr, D. Schunk (2018): \"The Many Faces of Human Sociality: Uncovering the Distribution and Stability of Social Preferences\",\n# Journal of the European Economic Association, forthcoming.\n# ===========================================================================================================================================\n\nrm(list=ls()) # Clear the memory\nlibrary(compiler)\nset.seed(51)\n\n# Data-Preparation-Function\nf.dataprep <- function(dat, persid, label_choice_x, label_indicators_x, label_indicators_y, label_self_x, label_other_x, label_self_y, label_other_y, nafiller=1) {\n\ttid <- table(dat[,persid]) #Table of individuals\n\tpid <- as.numeric(names(tid)) #Vector of individual identifiers\n\tj <- length(tid) #Number of individuals\n\tn <- max(tid) #Maximum number of choices per individual\n\tlk <- length(label_indicators_x) #Number of \"left\" regressors\n\trk <- length(label_indicators_y) #Number of \"right\" regressors\n\t{if (lk != rk) {stop(\"Length of label_indicators_x and label_indicators_y differ!\")}}\n\tk <- lk #Number of regressors\n\n\tindicators_x <- matrix(1, n*j, k) #\"left\" regressor matrix\n\tindicators_y <- matrix(1, n*j, k) #\"right\" regressor matrix\n\n\tnlist <- list(c(), pid)\n\tself_x <- matrix(0, n, j, dimnames=nlist) # Payoff matrix, player A, \"X\"\n\tother_x <- matrix(0, n, j, dimnames=nlist) # Payoff matrix, player B, \"X\"\n\tself_y <- matrix(0, n, j, dimnames=nlist) # Payoff matrix, player A, \"Y\"\n\tother_y <- matrix(0, n, j, dimnames=nlist) # Payoff matrix, player B, \"Y\"\n\tchoice_x <- matrix(0, n, j, dimnames=nlist) # Matrix indicating the choice (1=left, 0=right)\n\tsel <- matrix(0, n, j, dimnames=nlist) # Matrix indicating whether an observation is present (panel may be unbalanced!)\n\trm(nlist)\n\n\t#Fill the data and selection matrices individual by individual (could handle an unbalanced panel)\n\tfor (i in 1:j) {\n\t\tsel[,i] <- c(rep(1, tid[i]), rep(0, n-tid[i]))\n\n\t\tidx <- dat[,persid] == pid[i]\n\t\tself_x[,i] <- c(dat[idx, label_self_x], rep(nafiller, n-tid[i]))\n\t\tother_x[,i] <- c(dat[idx, label_other_x], rep(nafiller, n-tid[i]))\n\t\tself_y[,i] <- c(dat[idx, label_self_y], rep(nafiller, n-tid[i]))\n\t\tother_y[,i] <- c(dat[idx, label_other_y], rep(nafiller, n-tid[i]))\n\t\tchoice_x[,i] <- c(dat[idx, label_choice_x], rep(nafiller, n-tid[i]))\n\n\t\t{if (k > 1) {\n\t\t\tm1 <- as.matrix(dat[idx, label_indicators_x])\n\t\t\tm2 <- matrix(0, n-nrow(m1), ncol(m1))\n\t\t\tm <- rbind(m1, m2)\n\t\t\tindicators_x[(n*(i-1)+1):(i*n),] <- m\n\t\t\trm (m1,m2)\n\n\t\t\tm1 <- as.matrix(dat[idx, label_indicators_y])\n\t\t\tm2 <- matrix(0, n-nrow(m1), ncol(m1))\n\t\t\tm <- rbind(m1, m2)\n\t\t\tindicators_y[(n*(i-1)+1):(i*n),] <- m\n\t\t\trm(m1,m2)\n\t\t}}\n\t}\n\tlist(tid=tid, pid=pid, n=n, j=j, k=k, indicators_x=indicators_x, indicators_y=indicators_y, self_x=self_x, other_x=other_x, self_y=self_y, other_y=other_y, choice_x=choice_x, sel=sel)\n}\nf.dataprep <- cmpfun(f.dataprep)\n\n# Component Density Function\nf.compdens <- function(theta.v, choice_x, self_x, other_x, self_y, other_y, indicators_x, indicators_y, sel, nc ,k, n, j) {\n\ttheta.m <- matrix(theta.v, k+1, nc)\n\n\tlinindex_x <- indicators_x %*% theta.m[1:k,] # Linear index of X-choice, a (n*j x nc)-matrix\n\tlinindex_y <- indicators_y %*% theta.m[1:k,] # Linear index of Y-choice, a (n*j x nc)-matrix\n\n\tret <- matrix(0, j, nc)\n\n\t# Loop over all nc preference types\n\tfor (c in 1:nc) {\n\t\tli_x <- matrix(linindex_x[,c], n, j)\n\t\tli_y <- matrix(linindex_y[,c], n, j)\n\t\tchoicesens <- theta.m[k+1,c]\n\t\tcs_li_x <- choicesens * ((1-li_x)*self_x + li_x*other_x) #Type-specific deterministic utility of chosing \"X\" times choice sensitivity\n\t\tcs_li_y <- choicesens * ((1-li_y)*self_y + li_y*other_y) #Type-specific deterministic utility of chosing \"Y\" times choice sensitivity\n\n\t\tprobs <- ( (exp(cs_li_x)/(exp(cs_li_x)+exp(cs_li_y)))^choice_x * (exp(cs_li_y)/(exp(cs_li_x)+exp(cs_li_y)))^(1-choice_x) )^sel\n\n\t\tfor (i in 1:j) {\n\t\t\tret[i,c] <- prod(probs[,i])\n\t\t}\n\t}\n\tret\n}\nf.compdens <- cmpfun(f.compdens)\n\n# Log Likelihood of the Mixture Model and its Gradient\nf.totloglik <- function(psi, choice_x, self_x, other_x, self_y, other_y, indicators_x, indicators_y, sel, nc, k, n, j) {\n\tlpsi <- length(psi)\n\ttheta.v <- psi[1:(lpsi-nc+1)]\n\tmix <- psi[(lpsi-nc+2):lpsi]\n\tmix <- c(mix, 1-sum(mix))\n\tm <- matrix(mix, j, nc, byrow=T)\n\n\tsum(log(rowSums( m*f.compdens(theta.v, choice_x, self_x, other_x, self_y, other_y, indicators_x, indicators_y, sel, nc, k, n, j))))\n}\nf.totloglik <- cmpfun(f.totloglik)\n\nf.totloglik.gradient <- function(psi, choice_x, self_x, other_x, self_y, other_y, indicators_x, indicators_y, sel, nc, k, n, j) {\n\tlpsi <- length(psi)\n\ttheta.v <- psi[1:(lpsi-nc+1)]\n\ttheta.m <- matrix(theta.v, k+1, nc)\n\tmix <- psi[(lpsi-nc+2):lpsi]\n\tmix <- c(mix, 1-sum(mix))\n\tm <- matrix(mix, j, nc, byrow=T)\n\n\tnj <- n*j\n\tchoice_x.k <- matrix(as.vector(choice_x), nj, k)\n\tsel.k <- matrix(as.vector(sel) , nj, k)\n\tself_x.k <- matrix(as.vector(self_x) , nj, k)\n\tother_x.k <- matrix(as.vector(other_x) , nj, k)\n\tself_y.k <- matrix(as.vector(self_y) , nj, k)\n\tother_y.k <- matrix(as.vector(other_y) , nj, k)\n\n\tcdens.m <- f.compdens(theta.v, choice_x, self_x, other_x, self_y, other_y, indicators_x, indicators_y, sel, nc ,k, n, j)\n\tdenom.outerderiv <- 1/matrix(rowSums(m*cdens.m), n, j, byrow=T)\n\tdenom.outerderiv.k <- matrix(as.vector(denom.outerderiv), nj, k)\n\n\tret.theta <- rep(0, nc*(k+1))\n\tret.mix <- rep(0, nc)\n\n\tfor (c in 1:nc) {\n\t\tchoicesens <- theta.m[k+1, c]\n\t\tbeta <- theta.m[1:k, c]\n\n\t\tli_x <- matrix(as.vector(indicators_x %*% beta), n, j) # linear index X-choice\n\t\tli_y <- matrix(as.vector(indicators_y %*% beta), n, j) # linear index Y-choice\n\n\t\tul <- (1-li_x)*self_x + li_x*other_x # Deterministic utility from X-choice\n\t\tur <- (1-li_y)*self_y + li_y*other_y # Deterministic utility from Y-choice\n\t\tul.k <- matrix(as.vector(ul), nj, k)\n\t\tur.k <- matrix(as.vector(ur), nj, k)\n\n\t\tinnerderiv <- mix[c]*matrix(cdens.m[,c],n,j,byrow=T)/((exp(choicesens*ul)/(exp(choicesens*ul)+exp(choicesens*ur)))^choice_x * (exp(choicesens*ur)/(exp(choicesens*ul)+exp(choicesens*ur)))^(1-choice_x))\n\t\tinnerderiv.k <- matrix(as.vector(innerderiv), nj, k)\n\n\t\tchoicesens.grad <- sel * denom.outerderiv * innerderiv * ((1/(exp(choicesens*ul)+exp(choicesens*ur))^2) * ( (exp(choicesens*ul)/(exp(choicesens*ul)+exp(choicesens*ur)))^choice_x * exp(choicesens*(ul + 2*ur))*(-ur + ul) * (exp(choicesens*ur)/(exp(choicesens*ul)+exp(choicesens*ur)))^(-choice_x) * (choice_x * exp(-choicesens*ul) - exp(-choicesens*ur) + choice_x * exp(-choicesens*ur)) ))\n\t\tchoicesens.grad <- sum(choicesens.grad)\n\n\t\tbeta.grad <- sel.k * denom.outerderiv.k * innerderiv.k * ((-1/(exp(choicesens*ul.k)+exp(choicesens*ur.k))^2) * ( (exp(choicesens*ul.k)/(exp(choicesens*ul.k)+exp(choicesens*ur.k)))^choice_x.k * choicesens*exp(choicesens*(ul.k + 2*ur.k))*(indicators_x*(self_x.k-other_x.k) + indicators_y*(other_y.k-self_y.k)) * (exp(choicesens*ur.k)/(exp(choicesens*ul.k)+exp(choicesens*ur.k)))^(-choice_x.k) * (choice_x.k * exp(-choicesens*ul.k) - exp(-choicesens*ur.k) + choice_x.k * exp(-choicesens*ur.k)) ))\n\t\tbeta.grad <- colSums(beta.grad)\n\n\t\tmix.grad <- sum(cdens.m[,c] * denom.outerderiv[1,])\n\n\t\tret.theta[((c-1)*(k+1)+1):(c*(k+1))] <- c(beta.grad, choicesens.grad)\n\t\tret.mix[c] <- mix.grad\n\t}\n\tret.mix <- ret.mix - ret.mix[nc]\n\tret <- c(ret.theta, ret.mix[1:(nc-1)])\n\n\tret\n}\nf.totloglik.gradient <- cmpfun(f.totloglik.gradient)\n\n# Log Likelihood Part in the M-Step and its Gradient\nf.mloglik <- function(theta.v, choice_x, self_x, other_x, self_y, other_y, indicators_x, indicators_y, sel, nc, k, n, j, tau) {\n\tsum(tau * log(f.compdens(theta.v, choice_x, self_x, other_x, self_y, other_y, indicators_x, indicators_y, sel, nc, k, n, j)))\n}\nf.mloglik <- cmpfun(f.mloglik)\n\nf.mloglik.pregrad <- function(theta.c, weight, choice_x, self_x, other_x, self_y, other_y, indicators_x, indicators_y, sel, nc, k, n, j) {\n\tchoicesens <- theta.c[k+1]\n\tbeta <- theta.c[1:k]\n\n\tweights <- matrix(weight, n, j, byrow=T) #The individual weights (used for the taus)\n\n\tli_x <- matrix(as.vector(indicators_x %*% beta), n, j) # linear index X-choice\n\tli_y <- matrix(as.vector(indicators_y %*% beta), n, j) # linear index Y-choice\n\n\tul <- (1-li_x)*self_x + li_x*other_x # Deterministic utility from X-choice\n\tur <- (1-li_y)*self_y + li_y*other_y # Deterministic utility from Y-choice\n\n\tdenom <- 1/((exp(choicesens*ul)/(exp(choicesens*ul)+exp(choicesens*ur)))^choice_x * (exp(choicesens*ur)/(exp(choicesens*ul)+exp(choicesens*ur)))^(1-choice_x))\n\n\t#The gradient of choicesens (scalar)\n\tchoicesens.grad <- sel * weights * denom * ((1/(exp(choicesens*ul)+exp(choicesens*ur))^2) * ( (exp(choicesens*ul)/(exp(choicesens*ul)+exp(choicesens*ur)))^choice_x * exp(choicesens*(ul + 2*ur))*(-ur + ul) * (exp(choicesens*ur)/(exp(choicesens*ul)+exp(choicesens*ur)))^(-choice_x) * (choice_x * exp(-choicesens*ul) - exp(-choicesens*ur) + choice_x * exp(-choicesens*ur)) ))\n\tchoicesens.grad <- sum(choicesens.grad)\n\n\t#The gradient (k x 1)-vector of beta\n\tnj <- n*j\n\tchoice_x.k <- matrix(as.vector(choice_x), nj, k)\n\tdenom.k <- matrix(as.vector(denom) , nj, k)\n\tweights.k <- matrix(as.vector(weights) , nj, k)\n\tul.k <- matrix(as.vector(ul) , nj, k)\n\tur.k <- matrix(as.vector(ur) , nj, k)\n\tsel.k <- matrix(as.vector(sel) , nj, k)\n\tself_x.k <- matrix(as.vector(self_x) , nj, k)\n\tother_x.k <- matrix(as.vector(other_x) , nj, k)\n\tself_y.k <- matrix(as.vector(self_y) , nj, k)\n\tother_y.k <- matrix(as.vector(other_y) , nj, k)\n\n\tbeta.grad <- sel.k * weights.k * denom.k * ((-1/(exp(choicesens*ul.k)+exp(choicesens*ur.k))^2) * ( (exp(choicesens*ul.k)/(exp(choicesens*ul.k)+exp(choicesens*ur.k)))^choice_x.k * choicesens*exp(choicesens*(ul.k + 2*ur.k))*(indicators_x*(self_x.k-other_x.k) + indicators_y*(other_y.k-self_y.k)) * (exp(choicesens*ur.k)/(exp(choicesens*ul.k)+exp(choicesens*ur.k)))^(-choice_x.k) * (choice_x.k * exp(-choicesens*ul.k) - exp(-choicesens*ur.k) + choice_x.k * exp(-choicesens*ur.k)) ))\n\tbeta.grad <- colSums(beta.grad)\n\n\tc(beta.grad, choicesens.grad)\n}\nf.mloglik.pregrad <- cmpfun(f.mloglik.pregrad)\n\nf.mloglik.grad <- function(theta.v, choice_x, self_x, other_x, self_y, other_y, indicators_x, indicators_y, sel, nc, k, n, j, tau) {\n\tret <- rep(0, (k+1)*nc)\n\n\tfor (c in 1:nc) {\n\t\tret[((k+1)*(c-1)+1):((k+1)*c)] <- f.mloglik.pregrad(theta.v[((c-1)*(k+1)+1):(c*(k+1))], tau[,c], choice_x, self_x, other_x, self_y, other_y, indicators_x, indicators_y, sel, nc, k, n, j)\n\t}\n\n\tret\n}\nf.mloglik.grad <- cmpfun(f.mloglik.grad)\n\n# E-Step Function\nf.estep <- function(theta.v, choice_x, self_x, other_x, self_y, other_y, indicators_x, indicators_y, sel, nc, k, n, j, mix) {\n\tm <- matrix(mix, j, nc, byrow=T)\n\n\tnumerator <- m * f.compdens(theta.v, choice_x, self_x, other_x, self_y, other_y, indicators_x, indicators_y, sel, nc, k, n, j)\n\tdenominator <- matrix(rowSums(numerator), j, nc)\n\n\tret <- matrix(numerator/denominator, j, nc, dimnames=list(colnames(sel), paste(\"comp\",1:nc,sep=\"\")))\n\tret\n}\nf.estep <- cmpfun(f.estep)\n\n# S-Step-Function\nf.sstep <- function(em.tau,j,nc){\n\tsem.tau <- matrix(0,j,nc)\n\tfor (i in 1:j){\n\t\tsem.tau[i,] <- t(rmultinom(1,1,em.tau[i,]))\n\t}\n\tsem.tau\n}\nf.sstep <- cmpfun(f.sstep)\n\n# M-Step Function\nf.mstep <- function(theta.v0, choice_x, self_x, other_x, self_y, other_y, indicators_x, indicators_y, sel, nc, k, n, j, tau) {\n\tret <- optim(theta.v0, f.mloglik, f.mloglik.grad, method=\"BFGS\", control=list(maxit=10000, trace=0, fnscale=-1), hessian=F, choice_x=choice_x, self_x=self_x, other_x=other_x, self_y=self_y, other_y=other_y, indicators_x=indicators_x, indicators_y=indicators_y, sel=sel, nc=nc, k=k, n=n, j=j, tau=tau)\n\n\tmix <- colMeans(tau)\n\n\tlist(mix=mix, theta.v=ret$par)\n}\nf.mstep <- cmpfun(f.mstep)\n\n# Annealing-Part-Function for the SAEM-Algorithm\nf.annealing <- function(em.mix, em.vm, sem.mix, sem.vm, iter, b=20){\n\t{if (iter <= b)\n\t\t{q <- cos((iter/b)*acos(b/100))}\n\t else\n\t\t{q <- (b/100)*sqrt(b/iter)}\n\t}\n\n\tmix <- q*sem.mix+(1-q)*em.mix\n\tvm <- q*sem.vm+(1-q)*em.vm\n\n\tlist(mix=mix, vm=vm)\n}\nf.annealing <- cmpfun(f.annealing)\n\n# Sandwitch part of the clustered standard errors\nf.sandwich <- function(psi, choice_x, self_x, other_x, self_y, other_y, indicators_x, indicators_y, sel, nc, k, n, j) {\n\tlpsi <- length(psi);\n\ttheta.v <- psi[1:(lpsi-nc+1)];\n\ttheta.m <- matrix(theta.v, k+1, nc);\n\tmix <- psi[(lpsi-nc+2):lpsi];\n\tmix <- c(mix, 1-sum(mix));\n\tm <- matrix(mix, j, nc, byrow=T);\n\n\t# Individual gradient\n\tnj <- n*j;\n\tchoice_x.k <- matrix(as.vector(choice_x), nj, k);\n\tsel.k <- matrix(as.vector(sel) , nj, k);\n\tself_x.k <- matrix(as.vector(self_x) , nj, k);\n\tother_x.k <- matrix(as.vector(other_x) , nj, k);\n\tself_y.k <- matrix(as.vector(self_y) , nj, k);\n\tother_y.k <- matrix(as.vector(other_y) , nj, k);\n\n\tcdens.m <- f.compdens(theta.v, choice_x, self_x, other_x, self_y, other_y, indicators_x, indicators_y, sel, nc ,k, n, j);\n\tdenom.outerderiv <- 1/matrix(rowSums(m*cdens.m), n, j, byrow=T);\n\tdenom.outerderiv.k <- matrix(as.vector(denom.outerderiv), nj, k);\n\n\tret.theta <- matrix(0, nj, nc*(k+1));\n\tret.mix <- matrix(0, nj, nc);\n\n\tfor (c in 1:nc) {\n\t\tgamma <- theta.m[k+1, c];\n\t\tbeta <- theta.m[1:k, c];\n\n\t\tlli <- matrix(as.vector(indicators_x %*% beta), n, j); #Left linear index\n\t\trli <- matrix(as.vector(indicators_y %*% beta), n, j); #Right linear index\n\n\t\tul <- (1-lli)*self_x + lli*other_x; #Utility from \"left\" choice\n\t\tur <- (1-rli)*self_y + rli*other_y; #Utility from \"right\" choice\n\t\tul.k <- matrix(as.vector(ul), nj, k);\n\t\tur.k <- matrix(as.vector(ur), nj, k);\n\n\t\tinnerderiv <- mix[c]*matrix(cdens.m[,c],n,j,byrow=T)/((exp(gamma*ul)/(exp(gamma*ul)+exp(gamma*ur)))^choice_x * (exp(gamma*ur)/(exp(gamma*ul)+exp(gamma*ur)))^(1-choice_x));\n\t\tinnerderiv.k <- matrix(as.vector(innerderiv), nj, k);\n\n\t\tgamma.grad <- sel * denom.outerderiv * innerderiv * ((1/(exp(gamma*ul)+exp(gamma*ur))^2) * ( (exp(gamma*ul)/(exp(gamma*ul)+exp(gamma*ur)))^choice_x * exp(gamma*(ul + 2*ur))*(-ur + ul) * (exp(gamma*ur)/(exp(gamma*ul)+exp(gamma*ur)))^(-choice_x) * (choice_x * exp(-gamma*ul) - exp(-gamma*ur) + choice_x * exp(-gamma*ur)) ));\n\n\t\tbeta.grad <- sel.k * denom.outerderiv.k * innerderiv.k * ((-1/(exp(gamma*ul.k)+exp(gamma*ur.k))^2) * ( (exp(gamma*ul.k)/(exp(gamma*ul.k)+exp(gamma*ur.k)))^choice_x.k * gamma*exp(gamma*(ul.k + 2*ur.k))*(indicators_x*(self_x.k-other_x.k) + indicators_y*(other_y.k-self_y.k)) * (exp(gamma*ur.k)/(exp(gamma*ul.k)+exp(gamma*ur.k)))^(-choice_x.k) * (choice_x.k * exp(-gamma*ul.k) - exp(-gamma*ur.k) + choice_x.k * exp(-gamma*ur.k)) ));\n\n\t\tmix.grad <- cdens.m[,c] * denom.outerderiv[1,]\n\n\t\tret.theta[,((c-1)*(k+1)+1):(c*(k+1))] <- cbind(beta.grad, as.vector(gamma.grad));\n\t\tret.mix[,c] <- as.vector(matrix(mix.grad/n,n,j,byrow=T));\n\t};\n\n\tret.mix <- ret.mix - matrix(ret.mix[,nc], nj, nc)\n\tret <- cbind(ret.theta, ret.mix[,1:(nc-1)]);\n\n\t#Sandwich part\n\tsandwich <- matrix(0, lpsi, lpsi)\n\tfor (i in 1:j) {\n\t\tgradi <- colSums(ret[((i-1)*n+1):(i*n),])\n\t\tsandwich <- sandwich + (gradi %o% gradi)\n\t}\n\n\tqc <- (nj-1) / (nj-lpsi) * j/(j-1) #df adjustment\n\n\tlist(qc=qc, sandwich=sandwich)\n}\nf.sandwich <- cmpfun(f.sandwich)\n\n# Function to compute clustered standard errors, relies on f.sandwich\nf.clusterse <- function(estobj, dat, persid, label_choice_x, label_indicators_x, label_indicators_y, self_x, other_x, self_y, other_y, nc, sortrow=1) {\n\tprep <- f.dataprep(dat, persid, label_choice_x, label_indicators_x, label_indicators_y, self_x, other_x, self_y, other_y, nafiller=1);\n\tn <- prep$n;\n\tj <- prep$j;\n\tk <- prep$k;\n\tindicators_x <- prep$indicators_x;\n\tindicators_y <- prep$indicators_y;\n\tself_x <- prep$self_x;\n\tother_x <- prep$other_x;\n\tself_y <- prep$self_y;\n\tother_y <- prep$other_y;\n\tchoice_x <- prep$choice_x;\n\tsel <- prep$sel;\n\trm(prep);\n\n\tll1 <- f.totloglik(estobj$ret$par, choice_x, self_x, other_x, self_y, other_y, indicators_x, indicators_y, sel, nc, k, n, j)\n\tif (abs(ll1 - estobj$ret$value)>0.001) stop(paste(\"Saved loglik\", ll1, \"and computed loglik\", estobj$value, \"differ\"))\n\n\n\tsandwich <- f.sandwich(estobj$ret$par, choice_x, self_x, other_x, self_y, other_y, indicators_x, indicators_y, sel, nc, k, n, j)\n\n\tlpsi <- length(estobj$ret$par)\n\tvcm <- solve(-estobj$ret$hessian)\n\tvcm <- sandwich$qc * (vcm %*% sandwich$sandwich %*% vcm)\n\n\tse <- sqrt(diag(vcm))\n\tlastmix.se <- sqrt( rep(1,nc-1) %*% vcm[(lpsi-(nc-2)):lpsi, (lpsi-(nc-2)):lpsi] %*% rep(1,nc-1) )\n\tpsi.se <- c(se,lastmix.se)\n\tpsi <- estobj$ret$par\n\n\t#Extract the point estimates\n\ttheta.v <- psi[1:(lpsi-nc+1)];\n\tmix <- psi[(lpsi-nc+2):lpsi];\n\tmix <- c(mix, 1-sum(mix));\n\n\tmix.m <- matrix(mix, 1, nc, dimnames=list(c(\"mixture\"), paste(\"comp\",1:nc,sep=\"\")));\n\ttheta.m <- matrix(theta.v, k+1, nc, dimnames=list(c(paste(label_indicators_x,label_indicators_y),\"choicesens\"), paste(\"comp\",1:nc,sep=\"\")));\n\n\t#Extract the standard errors\n\ttheta.v.se <- psi.se[1:(lpsi-nc+1)];\n\tmix.se <- psi.se[(lpsi-nc+2):(lpsi+1)];\n\n\tmix.m.se <- matrix(mix.se, 1, nc, dimnames=list(c(\"mixture\"), paste(\"comp\",1:nc,sep=\"\")));\n\ttheta.m.se <- matrix(theta.v.se, k+1, nc, dimnames=list(c(paste(label_indicators_x,label_indicators_y),\"choicesens\"), paste(\"comp\",1:nc,sep=\"\")));\n\n\tpe.out <- rbind(mix.m, theta.m);\n\tse.out <- rbind(mix.m.se, theta.m.se);\n\n\t#Sort the groups according to their size to avoid problems of label switching\n\tsortidx <- order(pe.out[sortrow,]);\n\tpe.out <- pe.out[, sortidx];\n\tse.out <- se.out[, sortidx];\n\n\tp.out <- 2*(1-pnorm(abs(pe.out)/se.out));\n\n\tcat(\"POINT ESTIMATES\\n\")\n\tprint(round(pe.out,3));\n\tcat(\"\\n------------------------------------------------\\n\");\n\tcat(\"ROBUST STANDARD ERRORS\\n\")\n\tprint(round(se.out,3));\n\tcat(\"\\n------------------------------------------------\\n\");\n\tcat(\"ROBUST P-VALUES\\n\")\n\tprint(round(p.out,3));\n\n\tlist(se=se.out, p=p.out, vcm=vcm)\n}\nf.clusterse <- cmpfun(f.clusterse)\n\n# Main Estimation Function\nf.estim <- function(dat, v0path, persid, nc, label_choice_x, label_indicators_x, label_indicators_y, label_self_x, label_other_x, label_self_y, label_other_y, saem=F, loglik1=NA, maxemiter=50, diffcrit=5e-3, sortrow=1) {\n\n\t# Prepares the data and stores it\n\tprep <- f.dataprep(dat, persid, label_choice_x, label_indicators_x, label_indicators_y, label_self_x, label_other_x, label_self_y, label_other_y, nafiller=1)\n\tn <- prep$n\n\tj <- prep$j\n\tk <- prep$k\n\tindicators_x <- prep$indicators_x\n\tindicators_y <- prep$indicators_y\n\tself_x <- prep$self_x\n\tother_x <- prep$other_x\n\tself_y <- prep$self_y\n\tother_y <- prep$other_y\n\tchoice_x <- prep$choice_x\n\tsel <- prep$sel\n\trm(prep)\n\n\t# Prepares the start values\n\tv0 <- read.table(v0path, sep=\",\", header=F)[,1]\n\ttheta.v <- runif(nc*(1+k),0.8,1.2) * rep(v0,nc) # Random variation of the start values from the pooled model\n\taa <- runif(nc, 0.5, 2)\n\tmix <- aa/sum(aa) # Initial mixture\n\trm(aa)\n\n\t# Initial EM control flow parameters\n\titer <- 1\n\tdiff <- 1\n\tllold <- 0\n\tllnew <- 1\n\n\t# EM/SAEM algorithm (see Dempster et al. (1977) and book by McLachlan (2000))\n\tcat(\"Starting EM type maximization...\\n\")\n\twhile (iter < maxemiter+1 & abs(diff) > diffcrit) {\n\t\tcat(\"\\n EM-Type Iteration:\", iter,\"of max.\",maxemiter,\"\\n\")\n\t\tcat(\"\\n working on E-step.\\n\")\n\t\ttau.em <- f.estep(theta.v, choice_x, self_x, other_x, self_y, other_y, indicators_x, indicators_y, sel, nc, k, n, j, mix)\n\t\tcat(\" working on M-step (EM algorithm).\\n\")\n\t\tmstep <- f.mstep(theta.v, choice_x, self_x, other_x, self_y, other_y, indicators_x, indicators_y, sel, nc, k, n, j, tau.em)\n\t\ttheta.v.em <- mstep$theta.v\n\t\tmix.em <- mstep$mix\n\n\t\tif (saem==T) {\n\t\t\tcat(\"\\n working on S-step.\\n\")\n\t\t\ttau.sem <- f.sstep(tau.em, j, nc)\n\n\t\t\tcat(\" working on M-step (SEM algorithm).\\n\")\n\t\t\tmstep <- f.mstep(theta.v, choice_x, self_x, other_x, self_y, other_y, indicators_x, indicators_y, sel, nc, k, n, j, tau.sem)\n\t\t\ttheta.v.sem <- mstep$theta.v\n\t\t\tmix.sem <- mstep$mix\n\n\t\t\tann <- f.annealing(mix.em, theta.v.em, mix.sem, theta.v.sem, iter, b=20)\n\t\t\tmix <- ann$mix\n\t\t\ttheta.v <- ann$v\n\t\t } else {\n\t\t \tmix <- mix.em\n\t\t \ttheta.v <- theta.v.em\n\t\t }\n\n\t\t# Update the control flow parameters\n\t\titer <- iter+1\n\t\tllold <- llnew\n\t\tpsi <- c(theta.v, mix[1:(length(mix)-1)])\n\t\tllnew <- f.totloglik(psi, choice_x, self_x, other_x, self_y, other_y, indicators_x, indicators_y, sel, nc, k, n, j)\n\t\tdiff <- llnew-llold\n\t\tcat(\"\\n Achieved Log Likelihood:\", round(llnew,4),\"\\n\\n ----------\\n\")\n\t}\n\tcat(\"\\n...done. Parameters after EM-type estimation:\\n\")\n\tmix.m <- matrix(mix, 1, nc, dimnames=list(c(\"mixture\"), paste(\"comp\",1:nc,sep=\"\")))\n\ttheta.m <- matrix(theta.v, k+1, nc, dimnames=list(c(paste(label_indicators_x,label_indicators_y),\"choicesens\"), paste(\"comp\",1:nc,sep=\"\")))\n\tout <- rbind(mix.m, theta.m)\n\n\t#Direct ML estimation\n\tret <- optim(psi,f.totloglik, f.totloglik.gradient, method=\"BFGS\", control=list(maxit=100000,trace=1,REPORT=20, fnscale=-1), hessian=T, choice_x=choice_x, self_x=self_x, other_x=other_x, self_y=self_y, other_y=other_y, indicators_x=indicators_x, indicators_y=indicators_y, sel=sel, nc=nc, k=k, n=n, j=j)\n\n\tpsi <- ret$par #Extract the MLE\n\tlpsi <- length(psi)\n\tpsi.se <- sqrt(diag(solve(-ret$hessian))) #Standard errors\n\n\t#Extract the point estimates\n\ttheta.v <- psi[1:(lpsi-nc+1)]\n\tmix <- psi[(lpsi-nc+2):lpsi]\n\tmix <- c(mix, 1-sum(mix))\n\n\tmix.m <- matrix(mix, 1, nc, dimnames=list(c(\"mixture\"), paste(\"comp\",1:nc,sep=\"\")))\n\ttheta.m <- matrix(theta.v, k+1, nc, dimnames=list(c(paste(label_indicators_x,label_indicators_y),\"choicesens\"), paste(\"comp\",1:nc,sep=\"\")))\n\n\t#Extract the standard errors\n\ttheta.v.se <- psi.se[1:(lpsi-nc+1)]\n\tmix.se <- psi.se[(lpsi-nc+2):lpsi]\n\tmix.se <- c(mix.se,NA)\n\n\tmix.m.se <- matrix(mix.se, 1, nc, dimnames=list(c(\"mixture\"), paste(\"comp\",1:nc,sep=\"\")))\n\ttheta.m.se <- matrix(theta.v.se, k+1, nc, dimnames=list(c(paste(label_indicators_x,label_indicators_y),\"choicesens\"), paste(\"comp\",1:nc,sep=\"\")))\n\n\ttau <- f.estep(theta.v, choice_x, self_x, other_x, self_y, other_y, indicators_x, indicators_y, sel, nc, k, n, j, mix)\n\n\taic <- -2*ret$value + 2*lpsi\n\tbic <- -2*ret$value + log(sum(sel))*lpsi\n\n\ttauv <- as.vector(tau)\n\tnec <- sum(na.omit(-tauv*log(tauv)))/(ret$value-loglik1)\n\n\ti.out <- matrix(c(ret$value, lpsi, sum(sel), sortrow, aic, bic, nec), , 1, dimnames=list(c(\"Loglik:\", \"# of parameters:\", \"# of observations:\", \"Sortrow (to avoid label switching):\", \"AIC:\", \"BIC:\", \"NEC:\"), c()))\n\tpe.out <- rbind(mix.m, theta.m)\n\tse.out <- rbind(mix.m.se, theta.m.se)\n\n\t#Sort the groups according to their size to avoid problems of label switching\n\tsortidx <- order(pe.out[sortrow,])\n\tpe.out <- pe.out[, sortidx]\n\tse.out <- se.out[, sortidx]\n\ttau <- tau[, sortidx]\n\n\tp.out <- 2*(1-pnorm(abs(pe.out)/se.out))\n\n\tcat(\"\\n------------------------------------------------\\n\")\n\tcat(\"GENERAL INFORMATION\\n\")\n\tprint(round(i.out,3))\n\tcat(\"\\n------------------------------------------------\\n\")\n\tcat(\"POINT ESTIMATES (NOT CLUSTERED)\\n\")\n\tprint(round(pe.out,3))\n\tcat(\"\\n------------------------------------------------\\n\")\n\tcat(\"STANDARD ERRORS (NOT CLUSTERED)\\n\")\n\tprint(round(se.out,3))\n\tcat(\"\\n------------------------------------------------\\n\")\n\tcat(\"P-VALUES\\n\")\n\tprint(round(p.out,3))\n\tcat(\"\\n------------------------------------------------\\n\")\n\n\tlist(pe=pe.out, se=se.out, p=p.out, info=i.out, ret=ret, tau=tau, success=T)\n}\nf.estim <- cmpfun(f.estim)\n\n\n\n\n# Load choice data from both experiments\ndat1 <- read.table(\"choices_exp1.csv\", sep=\",\", header=T)\ndat2 <- read.table(\"choices_exp2.csv\", sep=\",\", header=T)\n\n# Remove erratic subjects (see 2nd paragraph of section 4; to replicate estimate individual parameters)\ndropped <- read.table(\"dropped_subjects_section4paragraph2.csv\", sep=\",\", header=F)[,1]\ndat1 <- dat1[(dat1$sid %in% dropped) == F, ]\ndat2 <- dat2[(dat2$sid %in% dropped) == F, ]\n\n\n# Estimating Finite Model with nc=3 Types using start values from aggregate estimation\ncat(\"\\n\\n\\n================== ESTIMATING SESSION 1 ================================\\n\")\npe1 <- f.estim(dat1, \"svExp1_1cl.csv\", \"sid\", nc=3, \"choice_x\", c(\"s_x\",\"r_x\",\"q\",\"v\"), c(\"s_y\",\"r_y\",\"q\",\"v\"), \"self_x\", \"other_x\", \"self_y\", \"other_y\", saem=T, loglik1=-5472.314, maxemiter=30, diffcrit=1e-3,sortrow=1)\n\ncat(\"\\n\\n\\n================== ESTIMATING SESSION 2 ================================\\n\")\npe2 <- f.estim(dat2, \"svExp2_1cl.csv\", \"sid\", nc=3, \"choice_x\", c(\"s_x\",\"r_x\",\"q\",\"v\"), c(\"s_y\",\"r_y\",\"q\",\"v\"), \"self_x\", \"other_x\", \"self_y\", \"other_y\", saem=T, loglik1=-4540.739, maxemiter=30, diffcrit=1e-3,sortrow=1)\n\ncat(\"\\n\\nTo extract the individual ex-post probabilities of type membership type pe1$tau or pe2$tau.\\n\")\n\n\n# Computing Robust Standard Errors\ncat(\"\\n\\n\\n================== ROBUST STANDARD ERRORS: SESSION 1 ===================\\n\")\nrse1 <- f.clusterse(pe1, dat1, \"sid\", \"choice_x\", c(\"s_x\",\"r_x\",\"q\",\"v\"), c(\"s_y\",\"r_y\",\"q\",\"v\"), \"self_x\", \"other_x\", \"self_y\", \"other_y\", 3, sortrow=1)\ncat(\"\\n\\n\\n================== ROBUST STANDARD ERRORS: SESSION 2 ===================\\n\")\nrse2 <- f.clusterse(pe2, dat2, \"sid\", \"choice_x\", c(\"s_x\",\"r_x\",\"q\",\"v\"), c(\"s_y\",\"r_y\",\"q\",\"v\"), \"self_x\", \"other_x\", \"self_y\", \"other_y\", 3, sortrow=1)\n\n# Save the R workspace\nsave.image(\"finmix_est_3cl.RData\")\n", "meta": {"hexsha": "8639c1859b97a116ae8a13b543ed33cd78a06693", "size": 25758, "ext": "r", "lang": "R", "max_stars_repo_path": "bruhin-fehr-schunk-2019/original_replication_files/3_replicate_finmix_results.r", "max_stars_repo_name": "rohit-21/python_julia_structural_behavioral_economics", "max_stars_repo_head_hexsha": "aa73881d9686840baad7c91fe40de39b64787c70", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 23, "max_stars_repo_stars_event_min_datetime": "2021-11-16T12:31:43.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-27T10:01:32.000Z", "max_issues_repo_path": "bruhin-fehr-schunk-2019/original_replication_files/3_replicate_finmix_results.r", "max_issues_repo_name": "rohit-21/python_julia_structural_behavioral_economics", "max_issues_repo_head_hexsha": "aa73881d9686840baad7c91fe40de39b64787c70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "bruhin-fehr-schunk-2019/original_replication_files/3_replicate_finmix_results.r", "max_forks_repo_name": "rohit-21/python_julia_structural_behavioral_economics", "max_forks_repo_head_hexsha": "aa73881d9686840baad7c91fe40de39b64787c70", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2021-11-16T12:31:56.000Z", "max_forks_repo_forks_event_max_datetime": "2022-01-25T14:40:37.000Z", "avg_line_length": 46.1612903226, "max_line_length": 495, "alphanum_fraction": 0.6225638637, "num_tokens": 8680, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419831347362, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.37869379784604373}} {"text": "\\name{HilbertCurve}\n\\alias{HilbertCurve}\n\\title{\nInitialize a Hilbert curve\n}\n\\description{\nInitialize a Hilbert curve\n}\n\\usage{\nHilbertCurve(s, e, level = 4, mode = c(\"normal\", \"pixel\"),\n reference = FALSE, reference_gp = gpar(lty = 3, col = \"#999999\"),\n arrow = TRUE, zoom = NULL, newpage = TRUE,\n background_col = \"transparent\", background_border = NA,\n title = NULL, title_gp = gpar(fontsize = 16),\n start_from = c(\"bottomleft\", \"topleft\", \"bottomright\", \"topright\"),\n first_seg = c(\"horizontal\", \"vertical\"), legend = list(),\n padding = unit(2, \"mm\"))\n}\n\\arguments{\n\n \\item{s}{position that will be mapped as the start of the Hilbert curve. The value should a single numeric value. If it is a vector, the minimum is used.}\n \\item{e}{position that will be mapped as the end of the Hilbert curve. The value should a single numeric value. If it is a vector, the maximum is used.}\n \\item{level}{iteration level of the Hilbert curve. There will by \\code{4^level - 1} segments in the curve.}\n \\item{mode}{\"normal\" mode is used for low \\code{level} value and \"pixel\" mode is always used for high \\code{level} value, so the \"normal\" mode is always for low-resolution visualization while \"pixel\" mode is used for high-resolution visualization. See 'details' for explanation.}\n \\item{reference}{whether add reference lines on the plot. Only works under 'normal' mode. The reference line is only used for illustrating how the curve folds.}\n \\item{reference_gp}{graphic settings for the reference lines. It should be specified by \\code{\\link[grid]{gpar}}.}\n \\item{arrow}{whether add arrows on the reference line. Only works under 'normal' mode.}\n \\item{zoom}{Internally, position are stored as integer values. To better map the data to the Hilbert curve, the original positions are zoomed according to the range and the level of Hilbert curve. E.g. if the curve visualizes data ranging from 1 to 2 but level of the curve is set to 4, the positions will be zoomed by ~x2000 so that values like 1.5, 1.555 can be mapped to the curve with more accuracy. You don't need to care the zooming thing, proper zooming factor is calculated automatically.}\n \\item{newpage}{whether call \\code{\\link[grid]{grid.newpage}} to draw on a new graphic device.}\n \\item{background_col}{background color.}\n \\item{background_border}{background border border.}\n \\item{title}{title of the plot.}\n \\item{title_gp}{graphic parameters for the title. It should be specified by \\code{\\link[grid]{gpar}}.}\n \\item{start_from}{which corner on the plot should the curve starts?}\n \\item{first_seg}{the orientation of the first segment.}\n \\item{legend}{a \\code{\\link[grid:grid.grob]{grob}} object, a \\code{\\link[ComplexHeatmap]{Legends-class}} object, or a list of them.}\n \\item{padding}{padding around the Hilbert curve.}\n\n}\n\\details{\nThis funciton initializes a Hilbert curve with level \\code{level} which corresponds \nto the range between \\code{s} and \\code{e}.\n\nUnder 'normal' mode, there is a visible Hilbert curve which plays like a folded axis and\ndifferent low-level graphics can be added afterwards according to the coordinates. \nIt works nice if the level of the Hilbert curve is small (say less than 6).\n\nWhen the level is high (e.g. > 10), the whole 2D space will be almost completely filled by the curve and\nit is impossible to add or visualize e.g. points on the curve. In this case, the 'pixel'\nmode visualizes each tiny 'segment' as a pixel and maps values to colors. Internally, the whole plot\nis represented as an RGB matrix and every time a new layer is added to the plot, the RGB matrix\nwill be updated according to the color overlay. When all the layers are added, normally a PNG figure is generated\ndirectly from the RGB matrix. So the Hilbert\ncurve with level 11 will generate a PNG figure with 2048x2048 resolution. This is extremely\nuseful for visualize genomic data. E.g. If we make a Hilbert curve for human chromosome 1 with\nlevel 11, then each pixel can represent 60bp (\\code{249250621/2048/2048}) which is of very high resolution.\n\nUnder 'pixel' mode, if the current device is an interactive deivce, every time a new layer is added, \nthe image will be add to the interactive device as a rastered image. But still you can use \\code{\\link{hc_png,HilbertCurve-method}}\nto export the plot as PNG file.\n\nTo make it short and clear, under \"normal\" mode, you can use following low-level graphic functions:\n\n\\itemize{\n \\item \\code{\\link{hc_points,HilbertCurve-method}}\n \\item \\code{\\link{hc_segments,HilbertCurve-method}}\n \\item \\code{\\link{hc_rect,HilbertCurve-method}}\n \\item \\code{\\link{hc_polygon,HilbertCurve-method}}\n \\item \\code{\\link{hc_text,HilbertCurve-method}}\n}\n\nAnd under \"pixel\" mode, you can use following functions:\n\n\\itemize{\n \\item \\code{\\link{hc_layer,HilbertCurve-method}}\n \\item \\code{\\link{hc_png,HilbertCurve-method}}\n \\item \\code{\\link{hc_polygon,HilbertCurve-method}}\n \\item \\code{\\link{hc_text,HilbertCurve-method}}\n}\n\nNotice, \\code{s} and \\code{e} are not necessarily to be integers, it can be any values (e.g. numeric or even negative values).\n}\n\\value{\nA \\code{\\link{HilbertCurve-class}} object.\n}\n\\author{\nZuguang Gu \n}\n\\examples{\nHilbertCurve(1, 100, reference = TRUE)\nHilbertCurve(1, 100, level = 5, reference = TRUE)\nHilbertCurve(1, 100, title = \"title\", reference = TRUE)\nHilbertCurve(1, 100, start_from = \"topleft\", reference = TRUE)\n\n# plot with one legend\nrequire(ComplexHeatmap)\nlegend = Legend(labels = c(\"a\", \"b\"), title = \"foo\", \n legend_gp = gpar(fill = c(\"red\", \"blue\")))\nhc = HilbertCurve(1, 100, title = \"title\", legend = legend)\nhc_segments(hc, x1 = 20, x2 = 40)\n\n# plot with more than one legend\nrequire(circlize)\nlegend1 = Legend(labels = c(\"a\", \"b\"), title = \"foo\", \n legend_gp = gpar(fill = c(\"red\", \"blue\")))\ncol_fun = colorRamp2(c(-1, 0, 1), c(\"green\", \"white\", \"red\"))\nlegend2 = Legend(col_fun = col_fun, title = \"bar\")\nhc = HilbertCurve(1, 100, title = \"title\", legend = list(legend1, legend2))\nhc_segments(hc, x1 = 20, x2 = 40)\n}\n", "meta": {"hexsha": "61c2d1313e976d08a62d2121de5d133c8fb349df", "size": 6033, "ext": "rd", "lang": "R", "max_stars_repo_path": "man/HilbertCurve.rd", "max_stars_repo_name": "jokergoo/HilbertCurve", "max_stars_repo_head_hexsha": "572d35a5a953a7b468338a142e51f828175fb7c6", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 37, "max_stars_repo_stars_event_min_datetime": "2016-02-22T16:46:55.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-23T09:35:43.000Z", "max_issues_repo_path": "man/HilbertCurve.rd", "max_issues_repo_name": "jokergoo/HilbertCurve", "max_issues_repo_head_hexsha": "572d35a5a953a7b468338a142e51f828175fb7c6", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2017-05-19T08:29:21.000Z", "max_issues_repo_issues_event_max_datetime": "2021-03-09T09:44:53.000Z", "max_forks_repo_path": "man/HilbertCurve.rd", "max_forks_repo_name": "jokergoo/HilbertCurve", "max_forks_repo_head_hexsha": "572d35a5a953a7b468338a142e51f828175fb7c6", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 8, "max_forks_repo_forks_event_min_datetime": "2016-04-22T10:44:09.000Z", "max_forks_repo_forks_event_max_datetime": "2021-08-16T07:48:16.000Z", "avg_line_length": 54.3513513514, "max_line_length": 502, "alphanum_fraction": 0.7334659373, "num_tokens": 1685, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.6150878555160666, "lm_q1q2_score": 0.37833307000335353}} {"text": "# Leap year calculator functions\n# Author: Dainius Masiliunas, team Rython\n# Date: 7th of January, 2016\n# License: Apache License 2.0\n\n# Calculates whether the year entered is a leap year or not.\nis.leap = function(year)\n{\n input = year\n\n # If characters, try coercing into a numeric\n if (is.character(year))\n year = suppressWarnings(as.numeric(year))\n \n # Sanity checks\n if (!is.numeric(year))\n stop(\"Error: argument of class numeric expected\")\n if (is.na(year))\n {\n # If it's NA, then it might be due to the user entering NA or a failed coercion; but it could be a date\n year = try(as.numeric(strsplit(input, \" \")[[1]][6]), TRUE)\n if (!is.numeric(year) || is.na(year) || class(year) == \"try-error\")\n stop(\"Error: failed to parse input argument\")\n }\n if (year < 1582)\n warning(paste(year, \"is out of the valid range\"))\n \n # Make sure input is integer\n year = floor(year)\n\n if (year %% 4 > 0)\n return(FALSE)\n else if (year %% 100 > 0)\n return(TRUE)\n else if (year %% 400 > 0)\n return(FALSE)\n return(TRUE)\n}\n", "meta": {"hexsha": "b8ea23a6ce023bd71eda26961f2d82402428aaba", "size": 1136, "ext": "r", "lang": "R", "max_stars_repo_path": "Lesson4/src/leap.r", "max_stars_repo_name": "GreatEmerald/geoscripting", "max_stars_repo_head_hexsha": "7133bc2275b9030f831860fd24cea53446fe3037", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2016-01-27T09:48:34.000Z", "max_stars_repo_stars_event_max_datetime": "2016-01-27T09:48:34.000Z", "max_issues_repo_path": "Lesson4/src/leap.r", "max_issues_repo_name": "GreatEmerald/geoscripting", "max_issues_repo_head_hexsha": "7133bc2275b9030f831860fd24cea53446fe3037", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Lesson4/src/leap.r", "max_forks_repo_name": "GreatEmerald/geoscripting", "max_forks_repo_head_hexsha": "7133bc2275b9030f831860fd24cea53446fe3037", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.1282051282, "max_line_length": 111, "alphanum_fraction": 0.6003521127, "num_tokens": 308, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.611381973294151, "lm_q1q2_score": 0.37831120261812573}} {"text": "# This is a test/example rd file\n\nDisplay \"Beautiful Picture\" \"Screen\" \"rgbobject\"\nFormat 640 480\n\nObjectBegin \"Pedestal\"\n\nXformPush # Pedestal Base\nScale 1 1 0.1\nTranslate 0 0 1\nCube\nXformPop # Pedestal Base\n\n# Column\nXformPush\nTranslate 0 0 0.2\nScale 0.5 0.5 4\nCylinder 1.0 0.0 1.0 360.0\nXformPop\n\nXformPush # Pedestal Top\nTranslate 0 0 4.2\nScale 1 1 0.1\nTranslate 0 0 1\nCube\nXformPop # Pedestal Top\n\nObjectEnd\n\nObjectBegin \"Tetrahedron\"\n# Tetrahedron\nPolySet \"P\"\n4 # Vertices\n4 # Faces\n\n# Vertex points\n 1.0 1.0 1.0\n 1.0 -1.0 -1.0\n-1.0 1.0 -1.0\n-1.0 -1.0 1.0\n\n# Face indices\n3 2 1 -1\n2 3 0 -1\n1 0 3 -1\n0 1 2 -1\n\nObjectEnd # Tetrahedron\n\nObjectBegin \"Octahedron\"\n\n# Octahedron\nPolySet \"P\"\n6 # Vertices\n\n8 # Faces\n\n# Vertex points\n 1.0 0.0 0.0\n-1.0 0.0 0.0\n 0.0 1.0 0.0\n 0.0 -1.0 0.0\n 0.0 0.0 1.0\n 0.0 0.0 -1.0\n\n# Face indices\n0 2 4 -1\n2 0 5 -1\n3 0 4 -1\n0 3 5 -1\n2 1 4 -1\n1 2 5 -1\n1 3 4 -1\n3 1 5 -1\n\nObjectEnd # Octahedron\n\nObjectBegin \"Icosahedron\"\n# Icosahedron\nPolySet \"P\"\n12 # Vertices\n20 # Faces\n\n# Vertex points\n 1.618034 1.0 0.0\n-1.618034 1.0 0.0\n 1.618034 -1.0 0.0\n-1.618034 -1.0 0.0\n\n 1.0 0.0 1.618034\n 1.0 0.0 -1.618034\n-1.0 0.0 1.618034\n-1.0 0.0 -1.618034\n\n 0.0 1.618034 1.0\n 0.0 -1.618034 1.0\n 0.0 1.618034 -1.0\n 0.0 -1.618034 -1.0\n\n# Face indices\n 0 8 4 -1\n 0 5 10 -1\n 2 4 9 -1\n 2 11 5 -1\n 1 6 8 -1\n 1 10 7 -1\n 3 9 6 -1\n 3 7 11 -1\n\n 0 10 8 -1\n 1 8 10 -1\n 2 9 11 -1\n 3 11 9 -1\n\n 4 2 0 -1\n 5 0 2 -1\n 6 1 3 -1\n 7 3 1 -1\n\n 8 6 4 -1\n 9 4 6 -1\n10 5 7 -1\n11 7 5 -1\n\nObjectEnd # Icosahedron\n\nObjectBegin \"Dodecahedron\"\n# Dodecahedron\nPolySet \"P\"\n20 # Vertices\n12 # Faces\n\n# Vertex points\n 1.0 1.0 1.0\n 1.0 1.0 -1.0\n 1.0 -1.0 1.0\n 1.0 -1.0 -1.0\n-1.0 1.0 1.0\n-1.0 1.0 -1.0\n-1.0 -1.0 1.0\n-1.0 -1.0 -1.0\n\n 0.618034 1.618034 0.0\n-0.618034 1.618034 0.0\n 0.618034 -1.618034 0.0\n-0.618034 -1.618034 0.0\n\n 1.618034 0.0 0.618034\n 1.618034 0.0 -0.618034\n-1.618034 0.0 0.618034\n-1.618034 0.0 -0.618034\n\n 0.0 0.618034 1.618034\n 0.0 -0.618034 1.618034\n 0.0 0.618034 -1.618034\n 0.0 -0.618034 -1.618034\n\n\n# Face indices\n 1 8 0 12 13 -1\n 4 9 5 15 14 -1\n 2 10 3 13 12 -1\n 7 11 6 14 15 -1\n\n 2 12 0 16 17 -1\n 1 13 3 19 18 -1\n 4 14 6 17 16 -1\n 7 15 5 18 19 -1\n\n 4 16 0 8 9 -1\n 2 17 6 11 10 -1\n 1 18 5 9 8 -1\n 7 19 3 10 11 -1\n\nObjectEnd # Dodecahdron\n\n\nFrameBegin 1\n\nCameraEye -25.0 -30.0 20.0\nCameraAt 0.0 0.0 3.0\nCameraUp 0 0 1\nCameraFOV 30.0\n\nWorldBegin\n\n# Lights\n#FarLight 0 1 -1 1.0 1.0 0.9 1.0\nPointLight 0 0 6 1.0 1.0 1.0 100\n# Visual representation of light\nSurface \"matte\"\nKa 1\nKd 0\nKs 0\nXformPush\nTranslate 0 0 6\nScale 0.3 0.3 0.3\nSphere 1.0 -1.0 1.0 360.0\nXformPop\n\n# Put a point light in the middle of each displayed object to \n# get a nice glow off of the pedastal surface\nPointLight 0 10 6 1.0 0.0 0.0 5.0 \nPointLight -7.81 6.23 6 0.0 0.0 1.0 5.0\nPointLight -9.75 -2.23 6 0.0 1.0 0.0 5.0\nPointLight -4.34 -9.01 6 0.5 0.3 0.0 5.0\nPointLight 4.34 -9.01 6 0.7 0.0 0.8 5.0\nPointLight 9.75 -2.23 6 1.0 0.7 0.7 5.0\nPointLight 7.81 6.23 6 1.0 1.0 0.0 5.0\n\nXformPush # Star Pattern on Floor\n\nSurface \"matte\"\nKa 1.0\nKd 0.0\n\nScale 8.5 8.5 1\nColor 1.0 0.7 0.3\nLine 0.000 1.000 0 0.975 -0.223 0\nLine 0.975 -0.223 0 -0.434 -0.901 0\nLine -0.434 -0.901 0 -0.782 0.623 0\nLine -0.782 0.623 0 0.782 0.623 0\nLine 0.782 0.623 0 0.434 -0.901 0\nLine 0.434 -0.901 0 -0.975 -0.223 0\nLine -0.975 -0.233 0 0.000 1.000 0\n\nXformPop\n\nSurface \"plastic\"\nKa 0.3\nKd 0.5\nKs 0.5\n\nXformPush # Sphere 1.0 -1.0 1.0 360.0 on Pedestal\n\nRotate \"Z\" 0\nTranslate 0 10 0\n\nColor 0.5 0.5 0.5\n\nObjectInstance \"Pedestal\"\n\nColor 1.0 0.0 0.0\nTranslate 0 0 6\nSphere 1.0 -1.0 1.0 360.0\n\nXformPop # Sphere 1.0 -1.0 1.0 360.0 on Pedestal\n\nXformPush # Cube on Pedestal\nRotate \"Z\" 51.43\nTranslate 0 10 0\n\nColor 0.5 0.5 0.5\n\nObjectInstance \"Pedestal\"\n\nColor 0.0 0.0 1.0\nTranslate 0 0 6.5\nRotate \"X\" 35.26\nRotate \"Y\" 45\nCube\n\nXformPop # Cube on Pedestal\n\nXformPush # Cone on Pedestal\nRotate \"Z\" 102.86\nTranslate 0 10 0\n\nColor 0.5 0.5 0.5\n\nObjectInstance \"Pedestal\"\n\nColor 0.0 1.0 0.0\nTranslate 0 0 5\nScale 1 1 2\nCone 1.0 1.0 360.0\n\nXformPop # Cone on Pedestal\n\nXformPush # Tetrahedron on Pedestal\nRotate \"Z\" 154.29\nTranslate 0 10 0\n\nColor 0.5 0.5 0.5\n\nObjectInstance \"Pedestal\"\n\nColor 0.5 0.3 0.0\nTranslate 0 0 6\nRotate \"X\" -35.2644\nRotate \"Y\" 45\n\nObjectInstance \"Tetrahedron\"\n\nXformPop # Tetrahedron on Pedestal\n\nXformPush # Octahedron on Pedestal\nRotate \"Z\" 205.71\nTranslate 0 10 0\n\nColor 0.5 0.5 0.5\n\nObjectInstance \"Pedestal\"\n\nColor 0.7 0.0 0.8\n\nTranslate 0 0 6\nRotate \"X\" -35.2644\nRotate \"Y\" 45\n\nObjectInstance \"Octahedron\"\n\nXformPop # Octahedron on Pedestal\n\nXformPush # Icosahedron on Pedestal\nRotate \"Z\" 257.14\nTranslate 0 10 0\n\nColor 0.5 0.5 0.5\n\nObjectInstance \"Pedestal\"\n\nColor 1.0 0.7 0.7\nTranslate 0 0 6\nRotate \"X\" -20.9051\n\nObjectInstance \"Icosahedron\"\n\nXformPop # Icosahedron on Pedestal\n\nXformPush # Dodecahedron on Pedestal\nRotate \"Z\" 308.57\nTranslate 0 10 0\n\nColor 0.5 0.5 0.5\n\nObjectInstance \"Pedestal\"\n\nColor 1.0 1.0 0.0\nTranslate 0 0 6\nRotate \"X\" -58.2825\n\nObjectInstance \"Dodecahedron\"\n\nXformPop # Dodecahedron on Pedestal\n\nWorldEnd\nFrameEnd\n", "meta": {"hexsha": "46de8bd5da3983fc4788d7475820d5aac78f7ae9", "size": 5190, "ext": "rd", "lang": "R", "max_stars_repo_path": "scenes/beautiful_picture_db.rd", "max_stars_repo_name": "Sergeant-Jaeger/rendering-engine-project", "max_stars_repo_head_hexsha": "2be3d19e422777a27db32f0e908ce5f9848786e0", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scenes/beautiful_picture_db.rd", "max_issues_repo_name": "Sergeant-Jaeger/rendering-engine-project", "max_issues_repo_head_hexsha": "2be3d19e422777a27db32f0e908ce5f9848786e0", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scenes/beautiful_picture_db.rd", "max_forks_repo_name": "Sergeant-Jaeger/rendering-engine-project", "max_forks_repo_head_hexsha": "2be3d19e422777a27db32f0e908ce5f9848786e0", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 14.8710601719, "max_line_length": 62, "alphanum_fraction": 0.6400770713, "num_tokens": 2950, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239836484144, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.3772548877998422}} {"text": "subroutine dqrls(x,dx,pivot,qraux,y,dy,beta,res,qt,tol,scrtch,rank)\ninteger pivot(*),dx(2),dy(2),rank\ndouble precision x(*), qraux(*), y(*), beta(*),res(*),qt(*),tol(*),\n\tscrtch(*)\n\ninteger n,p,q,kn,kp,k,info\n\nn=dx(1); p=dx(2); q=dy(2)\ncall dqrdca(x,n,n,p,qraux,pivot,scrtch,rank,tol(1))\n\nkn=1; kp=1\nif(rank>0)for(k=1;k<=q;k=k+1){\n\tcall dqrsl(x,n,n,rank,qraux,y(kn),scrtch,qt(kn),beta(kp),\n\t\tres(kn),scrtch,00110,info)\n\tkn = kn+n; kp=kp+p\n}\nreturn\nend\n\n#apply the qr decomposition to do various jobs\nsubroutine dqrsl1(qr,dq,qra,rank,y,k,qy,qb,job,info)\ndouble precision qr(*),qra(*),y(*),qy(*),qb(*); integer dq(2),job,k,rank\ninteger n,kn,kb,j\ndouble precision ourqty(1), ourqy(1), ourb(1), ourrsd(1), ourxb(1)\nourqty(1) = 0d0\nourqy(1) = 0d0\nourb(1) = 0d0\nourrsd(1) = 0d0\nourxb(1) = 0d0\nn = dq(1)\nkn = 1; kb = 1\nswitch(job) {\ncase 10000: #qy\nfor(j=0; j 0.)t = nrmxl/t\n\tif(t < eps){\n\t\tcall dshift(x,ldx,n,l,curpvt)\n\t\tjp = jpvt(l); t=qraux(l); tt=work(l); ww = work(l+p)\n\t\tfor(j=l+1; j<=curpvt; j=j+1){\n\t\t\tjj=j-1\n\t\t\tjpvt(jj)=jpvt(j); qraux(jj)=qraux(j)\n\t\t\twork(jj)=work(j); work(jj+p) = work(j+p)\n\t\t}\n\t\tjpvt(curpvt)=jp; qraux(curpvt)=t;\n\t\twork(curpvt)=tt; work(curpvt+p) = ww\n\t\tcurpvt=curpvt-1; if(lup>curpvt)lup=curpvt\n\t}\n\telse {\n\t\tif(l==n)break\n\t\tif (x(l,l)!=0.0d0)\n\t\t\tnrmxl = dsign(nrmxl,x(l,l))\n\t\tcall dscal(n-l+1,1.0d0/nrmxl,x(l,l),1)\n\t\tx(l,l) = 1.0d0+x(l,l)\n\t\tfor(j=l+1; j<=curpvt; j=j+1) {\n\t\t\tt = -ddot(n-l+1,x(l,l),1,x(l,j),1)/x(l,l)\n\t\t\tcall daxpy(n-l+1,t,x(l,l),1,x(l,j),1)\n\t\t\tif (qraux(j)!=0.0d0) {\n\t\t\t\ttt = 1.0d0-(dabs(x(l,j))/qraux(j))**2\n\t\t\t\ttt = dmax1(tt,0.0d0)\n\t\t\t\tt = tt\n\t\t\t\ttt = 1.0d0+0.05d0*tt*(qraux(j)/work(j))**2\n\t\t\t\tif (tt!=1.0d0)\n\t\t\t\t\tqraux(j) = qraux(j)*dsqrt(t)\n\t\t\t\telse {\n\t\t\t\t\tqraux(j) = dnrm2(n-l,x(l+1,j),1)\n\t\t\t\t\twork(j) = qraux(j)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tqraux(l) = x(l,l)\n\t\tx(l,l) = -nrmxl\n\t\tl=l+1\n\t}\n}\nrank = lup\nreturn\nend\n\nsubroutine dchdc(a,lda,p,work,jpvt,job,info)\ninteger lda,p,jpvt(p),job,info\ndouble precision a(lda,p),work(p)\ninteger pu,pl,plp1,j,jp,jt,k,kb,km1,kp1,l,maxl\ndouble precision temp\ndouble precision maxdia\nlogical swapk,negk\npl = 1\npu = 0\ninfo = p\nif (job!=0) {\n\tdo k = 1,p {\n\t\tswapk = jpvt(k)>0\n\t\tnegk = jpvt(k)<0\n\t\tjpvt(k) = k\n\t\tif (negk)\n\t\t\tjpvt(k) = -jpvt(k)\n\t\tif (swapk) {\n\t\t\tif (k!=pl) {\n\t\t\t\tcall dswap(pl-1,a(1,k),1,a(1,pl),1)\n\t\t\t\ttemp = a(k,k)\n\t\t\t\ta(k,k) = a(pl,pl)\n\t\t\t\ta(pl,pl) = temp\n\t\t\t\tplp1 = pl+1\n\t\t\t\tif (p>=plp1)\n\t\t\t\t\tdo j = plp1,p\n\t\t\t\t\t\tif (j=pl)\n\t\tdo kb = pl,p {\n\t\t\tk = p-kb+pl\n\t\t\tif (jpvt(k)<0) {\n\t\t\t\tjpvt(k) = -jpvt(k)\n\t\t\t\tif (pu!=k) {\n\t\t\t\t\tcall dswap(k-1,a(1,k),1,a(1,pu),1)\n\t\t\t\t\ttemp = a(k,k)\n\t\t\t\t\ta(k,k) = a(pu,pu)\n\t\t\t\t\ta(pu,pu) = temp\n\t\t\t\t\tkp1 = k+1\n\t\t\t\t\tif (p>=kp1)\n\t\t\t\t\t\tdo j = kp1,p\n\t\t\t\t\t\t\tif (j=pl&&kmaxdia) {\n\t\t\t\tmaxdia = a(l,l)\n\t\t\t\tmaxl = l\n\t\t\t\t}\n# quit if the pivot element is not positive.\n\tif (maxdia<=0.0d0)\n\t\tgo to 10\n\tif (k!=maxl) {\n# start the pivoting and update jpvt.\n\t\tkm1 = k-1\n\t\tcall dswap(km1,a(1,k),1,a(1,maxl),1)\n\t\ta(maxl,maxl) = a(k,k)\n\t\ta(k,k) = maxdia\n\t\tjp = jpvt(maxl)\n\t\tjpvt(maxl) = jpvt(k)\n\t\tjpvt(k) = jp\n\t\t}\n# reduction step. pivoting is contained across the rows.\n\twork(k) = dsqrt(a(k,k))\n\ta(k,k) = work(k)\n\tif (p>=kp1)\n\t\tdo j = kp1,p {\n\t\t\tif (k!=maxl)\n\t\t\t\tif (jnm)\n\tierr = 10*n\nelse {\n\tcall balanc(nm,n,a,is1,is2,fv1)\n\tcall elmhes(nm,n,is1,is2,a,iv1)\n\tif (matz==0)\n# .......... find eigenvalues only ..........\n\t\tcall hqr(nm,n,is1,is2,a,wr,wi,ierr)\n\telse {\n# .......... find both eigenvalues and eigenvectors ..........\n\t\tcall eltran(nm,n,is1,is2,a,iv1,z)\n\t\tcall hqr2(nm,n,is1,is2,a,wr,wi,z,ierr)\n\t\tif (ierr==0)\n\t\t\tcall balbak(nm,n,is1,is2,fv1,n,z)\n\t\t}\n\t}\nreturn\nend\n\nsubroutine chol(a,p,work,jpvt,job,info)\ninteger p,jpvt(*),job,info(*)\ndouble precision a(p,*),work(*)\ninteger i,j\n\tfor(j =2; j<=p; j = j+1)\n\t\tfor(i=1; i0; j=j-1 ){\n\t\tdo i = 1,l\n\t\t\tif (i!=j)\n\t\t\t\tif (a(j,i)!=0.0d0)\n\t\t\t\t\tnext 2\n\t\tgo to 10\n\t\t}\n\tgo to 20\n\t10 m = l\n\tiexc = 1\n\trepeat {\n# .......... in-line procedure for row and\n# column exchange ..........\n\t\tscale(m) = j\n\t\tif (j!=m) {\n\t\t\tdo i = 1,l {\n\t\t\t\tf = a(i,j)\n\t\t\t\ta(i,j) = a(i,m)\n\t\t\t\ta(i,m) = f\n\t\t\t\t}\n\t\t\tdo i = k,n {\n\t\t\t\tf = a(j,i)\n\t\t\t\ta(j,i) = a(m,i)\n\t\t\t\ta(m,i) = f\n\t\t\t\t}\n\t\t\t}\n\t\tswitch(iexc) {\n\t\t\tcase 1:\n# .......... search for rows isolating an eigenvalue\n# and push them down ..........\n\t\t\t\tif (l==1)\n\t\t\t\t\tgo to 40\n\t\t\t\tl = l-1\n\t\t\t\tbreak 1\n\t\t\tcase 2:\n# .......... search for columns isolating an eigenvalue\n# and push them left ..........\n\t\t\t\tk = k+1\n\t\t\t\t20 do j = k,l {\n\t\t\t\t\tdo i = k,l\n\t\t\t\t\t\tif (i!=j)\n\t\t\t\t\t\t\tif (a(i,j)!=0.0d0)\n\t\t\t\t\t\t\t\tnext 2\n\t\t\t\t\tgo to 30\n\t\t\t\t\t}\n\t\t\t\tbreak 2\n\t\t\t\t30 m = k\n\t\t\t\tiexc = 2\n\t\t\t}\n\t\t}\n\t}\n# .......... now balance the submatrix in rows k to l ..........\ndo i = k,l\n\tscale(i) = 1.0d0\nrepeat {\n# .......... iterative loop for norm reduction ..........\n\tnoconv = .false.\n\tdo i = k,l {\n\t\tc = 0.0d0\n\t\tr = 0.0d0\n\t\tdo j = k,l\n\t\t\tif (j!=i) {\n\t\t\t\tc = c+dabs(a(j,i))\n\t\t\t\tr = r+dabs(a(i,j))\n\t\t\t\t}\n# .......... guard against zero c or r due to underflow ..........\n\t\tif (c!=0.0d0&&r!=0.0d0) {\n\t\t\tg = r/radix\n\t\t\tf = 1.0d0\n\t\t\ts = c+r\n\t\t\twhile (c=g) {\n\t\t\t\tf = f/radix\n\t\t\t\tc = c/b2\n\t\t\t\t}\n# .......... now balance ..........\n\t\t\tif ((c+r)/f<0.95d0*s) {\n\t\t\t\tg = 1.0d0/f\n\t\t\t\tscale(i) = scale(i)*f\n\t\t\t\tnoconv = .true.\n\t\t\t\tdo j = k,n\n\t\t\t\t\ta(i,j) = a(i,j)*g\n\t\t\t\tdo j = 1,l\n\t\t\t\t\ta(j,i) = a(j,i)*f\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\tuntil(!noconv)\n40 low = k\nigh = l\nreturn\nend\n\n\n\nsubroutine balbak(nm,n,low,igh,scale,m,z)\ninteger i,j,k,m,n,ii,nm,igh,low\ndouble precision scale(n),z(nm,m)\ndouble precision s\nif (m!=0) {\n\tif (igh!=low)\n\t\tdo i = low,igh {\n\t\t\ts = scale(i)\n# .......... left hand eigenvectors are back transformed\n# if the foregoing statement is replaced by\n# s=1.0d0/scale(i). ..........\n\t\t\tdo j = 1,m\n\t\t\t\tz(i,j) = z(i,j)*s\n\t\t\t}\n# ......... for i=low-1 step -1 until 1,\n# igh+1 step 1 until n do -- ..........\n\tdo ii = 1,n {\n\t\ti = ii\n\t\tif (iigh) {\n\t\t\tif (i=kp1)\n\tdo m = kp1,la {\n\t\tmm1 = m-1\n\t\tx = 0.0d0\n\t\ti = m\n\t\tdo j = m,igh\n\t\t\tif (dabs(a(j,mm1))>dabs(x)) {\n\t\t\t\tx = a(j,mm1)\n\t\t\t\ti = j\n\t\t\t\t}\n\t\tint(m) = i\n\t\tif (i!=m) {\n# .......... interchange rows and columns of a ..........\n\t\t\tdo j = mm1,n {\n\t\t\t\ty = a(i,j)\n\t\t\t\ta(i,j) = a(m,j)\n\t\t\t\ta(m,j) = y\n\t\t\t\t}\n\t\t\tdo j = 1,igh {\n\t\t\t\ty = a(j,i)\n\t\t\t\ta(j,i) = a(j,m)\n\t\t\t\ta(j,m) = y\n\t\t\t\t}\n\t\t\t}\n# .......... end interchange ..........\n\t\tif (x!=0.0d0) {\n\t\t\tmp1 = m+1\n\t\t\tdo i = mp1,igh {\n\t\t\t\ty = a(i,mm1)\n\t\t\t\tif (y!=0.0d0) {\n\t\t\t\t\ty = y/x\n\t\t\t\t\ta(i,mm1) = y\n\t\t\t\t\tdo j = m,n\n\t\t\t\t\t\ta(i,j) = a(i,j)-y*a(m,j)\n\t\t\t\t\tdo j = 1,igh\n\t\t\t\t\t\ta(j,m) = a(j,m)+y*a(j,i)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\nreturn\nend\n\n\n\nsubroutine eltran(nm,n,low,igh,a,int,z)\ninteger i,j,n,kl,mp,nm,igh,low,mp1\ndouble precision a(nm,igh),z(nm,n)\ninteger int(igh)\n# .......... initialize z to identity matrix ..........\ndo j = 1,n {\n\tdo i = 1,n\n\t\tz(i,j) = 0.0d0\n\tz(j,j) = 1.0d0\n\t}\nkl = igh-low-1\nif (kl>=1)\n\tfor(mp = igh-1; mp > low; mp = mp -1) {\n\t\tmp1 = mp+1\n\t\tdo i = mp1,igh\n\t\t\tz(i,mp) = a(i,mp-1)\n\t\ti = int(mp)\n\t\tif (i!=mp) {\n\t\t\tdo j = mp,igh {\n\t\t\t\tz(mp,j) = z(i,j)\n\t\t\t\tz(i,j) = 0.0d0\n\t\t\t\t}\n\t\t\tz(i,mp) = 1.0d0\n\t\t\t}\n\t\t}\nreturn\nend\n\n\n\nsubroutine hqr(nm,n,low,igh,h,wr,wi,ierr)\ninteger i,j,k,l,m,n,en,mm,na,nm,igh,itn,its,low,mp2,enm2,ierr\ndouble precision h(nm,n),wr(n),wi(n)\ndouble precision p,q,r,s,t,w,x,y,zz,norm,tst1,tst2\nlogical notlas\nierr = 0\nnorm = 0.0d0\nk = 1\n# .......... store roots isolated by balanc\n# and compute matrix norm ..........\ndo i = 1,n {\n\tdo j = k,n\n\t\tnorm = norm+dabs(h(i,j))\n\tk = i\n\tif (iigh) {\n\t\twr(i) = h(i,i)\n\t\twi(i) = 0.0d0\n\t\t}\n\t}\nen = igh\nt = 0.0d0\nitn = 30*n\nrepeat {\n# .......... search for next eigenvalues ..........\n\tif (en low; l = l-1){\n\t\t\ts = dabs(h(l-1,l-1))+dabs(h(l,l))\n\t\t\tif (s==0.0d0)\n\t\t\t\ts = norm\n\t\t\ttst1 = s\n\t\t\ttst2 = tst1+dabs(h(l,l-1))\n\t\t\tif (tst2==tst1)\n\t\t\t\tbreak 1\n\t\t\t}\n# .......... form shift ..........\n\t\tx = h(en,en)\n\t\tif (l==en)\n\t\t\tgo to 50\n\t\ty = h(na,na)\n\t\tw = h(en,na)*h(na,en)\n\t\tif (l==na)\n\t\t\tbreak 1\n\t\tif (itn==0)\n\t\t\tbreak 2\n\t\tif (its==10||its==20) {\n# .......... form exceptional shift ..........\n\t\t\tt = t+x\n\t\t\tdo i = low,en\n\t\t\t\th(i,i) = h(i,i)-x\n\t\t\ts = dabs(h(en,na))+dabs(h(na,enm2))\n\t\t\tx = 0.75d0*s\n\t\t\ty = x\n\t\t\tw = -0.4375d0*s*s\n\t\t\t}\n\t\tits = its+1\n\t\titn = itn-1\n# .......... look for two consecutive small\n# sub-diagonal elements.\n# for m=en-2 step -1 until l do -- ..........\n\t\tdo mm = l,enm2 {\n\t\t\tm = enm2+l-mm\n\t\t\tzz = h(m,m)\n\t\t\tr = x-zz\n\t\t\ts = y-zz\n\t\t\tp = (r*s-w)/h(m+1,m)+h(m,m+1)\n\t\t\tq = h(m+1,m+1)-zz-r-s\n\t\t\tr = h(m+2,m+1)\n\t\t\ts = dabs(p)+dabs(q)+dabs(r)\n\t\t\tp = p/s\n\t\t\tq = q/s\n\t\t\tr = r/s\n\t\t\tif (m==l)\n\t\t\t\tbreak 1\n\t\t\ttst1 = dabs(p)*(dabs(h(m-1,m-1))+dabs(zz)+dabs(h(m+1,m+1)))\n\t\t\ttst2 = tst1+dabs(h(m,m-1))*(dabs(q)+dabs(r))\n\t\t\tif (tst2==tst1)\n\t\t\t\tbreak 1\n\t\t\t}\n\t\tmp2 = m+2\n\t\tdo i = mp2,en {\n\t\t\th(i,i-2) = 0.0d0\n\t\t\tif (i!=mp2)\n\t\t\t\th(i,i-3) = 0.0d0\n\t\t\t}\n# .......... double qr step involving rows l to en and\n# columns m to en ..........\n\t\tdo k = m,na {\n\t\t\tnotlas = k!=na\n\t\t\tif (k!=m) {\n\t\t\t\tp = h(k,k-1)\n\t\t\t\tq = h(k+1,k-1)\n\t\t\t\tr = 0.0d0\n\t\t\t\tif (notlas)\n\t\t\t\t\tr = h(k+2,k-1)\n\t\t\t\tx = dabs(p)+dabs(q)+dabs(r)\n\t\t\t\tif (x==0.0d0)\n\t\t\t\t\tnext 1\n\t\t\t\tp = p/x\n\t\t\t\tq = q/x\n\t\t\t\tr = r/x\n\t\t\t\t}\n\t\t\ts = dsign(dsqrt(p*p+q*q+r*r),p)\n\t\t\tif (k!=m)\n\t\t\t\th(k,k-1) = -s*x\n\t\t\telse if (l!=m)\n\t\t\t\th(k,k-1) = -h(k,k-1)\n\t\t\tp = p+s\n\t\t\tx = p/s\n\t\t\ty = q/s\n\t\t\tzz = r/s\n\t\t\tq = q/p\n\t\t\tr = r/p\n\t\t\tif (!notlas) {\n# .......... row modification ..........\n\t\t\t\tdo j = k,n {\n\t\t\t\t\tp = h(k,j)+q*h(k+1,j)\n\t\t\t\t\th(k,j) = h(k,j)-p*x\n\t\t\t\t\th(k+1,j) = h(k+1,j)-p*y\n\t\t\t\t\t}\n\t\t\t\tj = min0(en,k+3)\n# .......... column modification ..........\n\t\t\t\tdo i = 1,j {\n\t\t\t\t\tp = x*h(i,k)+y*h(i,k+1)\n\t\t\t\t\th(i,k) = h(i,k)-p\n\t\t\t\t\th(i,k+1) = h(i,k+1)-p*q\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\telse {\n# .......... row modification ..........\n\t\t\t\tdo j = k,n {\n\t\t\t\t\tp = h(k,j)+q*h(k+1,j)+r*h(k+2,j)\n\t\t\t\t\th(k,j) = h(k,j)-p*x\n\t\t\t\t\th(k+1,j) = h(k+1,j)-p*y\n\t\t\t\t\th(k+2,j) = h(k+2,j)-p*zz\n\t\t\t\t\t}\n\t\t\t\tj = min0(en,k+3)\n# .......... column modification ..........\n\t\t\t\tdo i = 1,j {\n\t\t\t\t\tp = x*h(i,k)+y*h(i,k+1)+zz*h(i,k+2)\n\t\t\t\t\th(i,k) = h(i,k)-p\n\t\t\t\t\th(i,k+1) = h(i,k+1)-p*q\n\t\t\t\t\th(i,k+2) = h(i,k+2)-p*r\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n# .......... two roots found ..........\n\tp = (y-x)/2.0d0\n\tq = p*p+w\n\tzz = dsqrt(dabs(q))\n\tx = x+t\n\tif (q<0.0d0) {\n# .......... complex pair ..........\n\t\twr(na) = x+p\n\t\twr(en) = x+p\n\t\twi(na) = zz\n\t\twi(en) = -zz\n\t\t}\n\telse {\n# .......... real pair ..........\n\t\tzz = p+dsign(zz,p)\n\t\twr(na) = x+zz\n\t\twr(en) = wr(na)\n\t\tif (zz!=0.0d0)\n\t\t\twr(en) = x-w/zz\n\t\twi(na) = 0.0d0\n\t\twi(en) = 0.0d0\n\t\t}\n\ten = enm2\n\tnext 1\n# .......... one root found ..........\n\t50 wr(en) = x+t\n\twi(en) = 0.0d0\n\ten = na\n\t}\n# .......... set error -- all eigenvalues have not\n# converged after 30*n iterations ..........\nierr = en\nreturn\nend\n\n\n\nsubroutine hqr2(nm,n,low,igh,h,wr,wi,z,ierr)\ninteger i,j,k,l,m,n,en,ii,jj,ll,mm,na,nm,nn,igh,itn,its,low,mp2,enm2,ierr\ndouble precision h(nm,n),wr(n),wi(n),z(nm,n)\ndouble precision p,q,r,s,t,w,x,y,ra,sa,vi,vr,zz,norm,tst1,tst2\nlogical notlas\nierr = 0\nnorm = 0.0d0\nk = 1\n# .......... store roots isolated by balanc\n# and compute matrix norm ..........\ndo i = 1,n {\n\tdo j = k,n\n\t\tnorm = norm+dabs(h(i,j))\n\tk = i\n\tif (iigh) {\n\t\twr(i) = h(i,i)\n\t\twi(i) = 0.0d0\n\t\t}\n\t}\nen = igh\nt = 0.0d0\nitn = 30*n\nrepeat {\n# .......... search for next eigenvalues ..........\n\tif (enigh)\n\t\t\tdo j = i,n\n\t\t\t\tz(i,j) = h(i,j)\n# .......... multiply by transformation matrix to give\n# vectors of original full matrix.\n# for j=n step -1 until low do -- ..........\n\tdo jj = low,n {\n\t\tj = n+low-jj\n\t\tm = min0(j,igh)\n\t\tdo i = low,igh {\n\t\t\tzz = 0.0d0\n\t\t\tdo k = low,m\n\t\t\t\tzz = zz+z(i,k)*h(k,j)\n\t\t\tz(i,j) = zz\n\t\t\t}\n\t\t}\n\t}\nreturn\nend\n\n\n\nsubroutine cdiv(ar,ai,br,bi,cr,ci)\ndouble precision ar,ai,br,bi,cr,ci\n# complex division, (cr,ci) = (ar,ai)/(br,bi)\ndouble precision s,ars,ais,brs,bis\ns = dabs(br)+dabs(bi)\nars = ar/s\nais = ai/s\nbrs = br/s\nbis = bi/s\ns = brs**2+bis**2\ncr = (ars*brs+ais*bis)/s\nci = (ais*brs-ars*bis)/s\nreturn\nend\n\n\n\nsubroutine rs(nm,n,a,w,matz,z,fv1,fv2,ierr)\ninteger n,nm,ierr,matz\ndouble precision a(nm,n),w(n),z(nm,n),fv1(n),fv2(n)\nif (n>nm)\n\tierr = 10*n\nelse\n if (matz!=0) {\n# .......... find both eigenvalues and eigenvectors ..........\n\tcall tred2(nm,n,a,w,fv1,z)\n\tcall tql2(nm,n,w,fv1,z,ierr)\n\t}\nelse {\n# .......... find eigenvalues only ..........\n\tcall tred1(nm,n,a,w,fv1,fv2)\n\tcall tqlrat(n,w,fv2,ierr)\n\t}\nreturn\nend\n\n\n\nsubroutine tql2(nm,n,d,e,z,ierr)\ninteger i,j,k,l,m,n,ii,l1,l2,nm,mml,ierr\ndouble precision d(n),e(n),z(nm,n)\ndouble precision c,c2,c3,dl1,el1,f,g,h,p,r,s,s2,tst1,tst2,pythag\nierr = 0\nif (n!=1) {\n\tdo i = 2,n\n\t\te(i-1) = e(i)\n\tf = 0.0d0\n\ttst1 = 0.0d0\n\te(n) = 0.0d0\n\tdo l = 1,n {\n\t\tj = 0\n\t\th = dabs(d(l))+dabs(e(l))\n\t\tif (tst1=d(i-1))\n\t\t\t\t\tgo to 10\n\t\t\t\td(i) = d(i-1)\n\t\t\t\t}\n\t\ti = 1\n\t\t10 d(i) = p\n\t\t}\n\treturn\n# .......... set error -- no convergence to an\n# eigenvalue after 30 iterations ..........\n\t20 ierr = l\n\t}\nreturn\nend\n\n\n\nsubroutine tred1(nm,n,a,d,e,e2)\ninteger i,j,k,l,n,ii,nm,jp1\ndouble precision a(nm,n),d(n),e(n),e2(n)\ndouble precision f,g,h,scale\ndo i = 1,n {\n\td(i) = a(n,i)\n\ta(n,i) = a(i,i)\n\t}\n# .......... for i=n step -1 until 1 do -- ..........\ndo ii = 1,n {\n\ti = n+1-ii\n\tl = i-1\n\th = 0.0d0\n\tscale = 0.0d0\n\tif (l>=1) {\n# .......... scale row (algol tol then not needed) ..........\n\t\tdo k = 1,l\n\t\t\tscale = scale+dabs(d(k))\n\t\tif (scale==0.0d0)\n\t\t\tdo j = 1,l {\n\t\t\t\td(j) = a(l,j)\n\t\t\t\ta(l,j) = a(i,j)\n\t\t\t\ta(i,j) = 0.0d0\n\t\t\t\t}\n\t\telse {\n\t\t\tdo k = 1,l {\n\t\t\t\td(k) = d(k)/scale\n\t\t\t\th = h+d(k)*d(k)\n\t\t\t\t}\n\t\t\te2(i) = scale*scale*h\n\t\t\tf = d(l)\n\t\t\tg = -dsign(dsqrt(h),f)\n\t\t\te(i) = scale*g\n\t\t\th = h-f*g\n\t\t\td(l) = f-g\n\t\t\tif (l!=1) {\n# .......... form a*u ..........\n\t\t\t\tdo j = 1,l\n\t\t\t\t\te(j) = 0.0d0\n\t\t\t\tdo j = 1,l {\n\t\t\t\t\tf = d(j)\n\t\t\t\t\tg = e(j)+a(j,j)*f\n\t\t\t\t\tjp1 = j+1\n\t\t\t\t\tif (l>=jp1)\n\t\t\t\t\t\tdo k = jp1,l {\n\t\t\t\t\t\t\tg = g+a(k,j)*d(k)\n\t\t\t\t\t\t\te(k) = e(k)+a(k,j)*f\n\t\t\t\t\t\t\t}\n\t\t\t\t\te(j) = g\n\t\t\t\t\t}\n# .......... form p ..........\n\t\t\t\tf = 0.0d0\n\t\t\t\tdo j = 1,l {\n\t\t\t\t\te(j) = e(j)/h\n\t\t\t\t\tf = f+e(j)*d(j)\n\t\t\t\t\t}\n\t\t\t\th = f/(h+h)\n# .......... form q ..........\n\t\t\t\tdo j = 1,l\n\t\t\t\t\te(j) = e(j)-h*d(j)\n# .......... form reduced a ..........\n\t\t\t\tdo j = 1,l {\n\t\t\t\t\tf = d(j)\n\t\t\t\t\tg = e(j)\n\t\t\t\t\tdo k = j,l\n\t\t\t\t\t\ta(k,j) = a(k,j)-f*e(k)-g*d(k)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\tdo j = 1,l {\n\t\t\t\tf = d(j)\n\t\t\t\td(j) = a(l,j)\n\t\t\t\ta(l,j) = a(i,j)\n\t\t\t\ta(i,j) = f*scale\n\t\t\t\t}\n\t\t\tnext 1\n\t\t\t}\n\t\t}\n\te(i) = 0.0d0\n\te2(i) = 0.0d0\n\t}\nreturn\nend\n\n\n\nsubroutine tred2(nm,n,a,d,e,z)\ninteger i,j,k,l,n,ii,nm,jp1\ndouble precision a(nm,n),d(n),e(n),z(nm,n)\ndouble precision f,g,h,hh,scale\ndo i = 1,n {\n\tdo j = i,n\n\t\tz(j,i) = a(j,i)\n\td(i) = a(n,i)\n\t}\nif (n!=1) {\n# .......... for i=n step -1 until 2 do -- ..........\n\tdo ii = 2,n {\n\t\ti = n+2-ii\n\t\tl = i-1\n\t\th = 0.0d0\n\t\tscale = 0.0d0\n\t\tif (l>=2) {\n# .......... scale row (algol tol then not needed) ..........\n\t\t\tdo k = 1,l\n\t\t\t\tscale = scale+dabs(d(k))\n\t\t\tif (scale!=0.0d0) {\n\t\t\t\tdo k = 1,l {\n\t\t\t\t\td(k) = d(k)/scale\n\t\t\t\t\th = h+d(k)*d(k)\n\t\t\t\t\t}\n\t\t\t\tf = d(l)\n\t\t\t\tg = -dsign(dsqrt(h),f)\n\t\t\t\te(i) = scale*g\n\t\t\t\th = h-f*g\n\t\t\t\td(l) = f-g\n# .......... form a*u ..........\n\t\t\t\tdo j = 1,l\n\t\t\t\t\te(j) = 0.0d0\n\t\t\t\tdo j = 1,l {\n\t\t\t\t\tf = d(j)\n\t\t\t\t\tz(j,i) = f\n\t\t\t\t\tg = e(j)+z(j,j)*f\n\t\t\t\t\tjp1 = j+1\n\t\t\t\t\tif (l>=jp1)\n\t\t\t\t\t\tdo k = jp1,l {\n\t\t\t\t\t\t\tg = g+z(k,j)*d(k)\n\t\t\t\t\t\t\te(k) = e(k)+z(k,j)*f\n\t\t\t\t\t\t\t}\n\t\t\t\t\te(j) = g\n\t\t\t\t\t}\n# .......... form p ..........\n\t\t\t\tf = 0.0d0\n\t\t\t\tdo j = 1,l {\n\t\t\t\t\te(j) = e(j)/h\n\t\t\t\t\tf = f+e(j)*d(j)\n\t\t\t\t\t}\n\t\t\t\thh = f/(h+h)\n# .......... form q ..........\n\t\t\t\tdo j = 1,l\n\t\t\t\t\te(j) = e(j)-hh*d(j)\n# .......... form reduced a ..........\n\t\t\t\tdo j = 1,l {\n\t\t\t\t\tf = d(j)\n\t\t\t\t\tg = e(j)\n\t\t\t\t\tdo k = j,l\n\t\t\t\t\t\tz(k,j) = z(k,j)-f*e(k)-g*d(k)\n\t\t\t\t\td(j) = z(l,j)\n\t\t\t\t\tz(i,j) = 0.0d0\n\t\t\t\t\t}\n\t\t\t\tgo to 10\n\t\t\t\t}\n\t\t\t}\n\t\te(i) = d(l)\n\t\tdo j = 1,l {\n\t\t\td(j) = z(l,j)\n\t\t\tz(i,j) = 0.0d0\n\t\t\tz(j,i) = 0.0d0\n\t\t\t}\n\t\t10 d(i) = h\n\t\t}\n# .......... accumulation of transformation matrices ..........\n\tdo i = 2,n {\n\t\tl = i-1\n\t\tz(n,l) = z(l,l)\n\t\tz(l,l) = 1.0d0\n\t\th = d(i)\n\t\tif (h!=0.0d0) {\n\t\t\tdo k = 1,l\n\t\t\t\td(k) = z(k,i)/h\n\t\t\tdo j = 1,l {\n\t\t\t\tg = 0.0d0\n\t\t\t\tdo k = 1,l\n\t\t\t\t\tg = g+z(k,i)*z(k,j)\n\t\t\t\tdo k = 1,l\n\t\t\t\t\tz(k,j) = z(k,j)-g*d(k)\n\t\t\t\t}\n\t\t\t}\n\t\tdo k = 1,l\n\t\t\tz(k,i) = 0.0d0\n\t\t}\n\t}\ndo i = 1,n {\n\td(i) = z(n,i)\n\tz(n,i) = 0.0d0\n\t}\nz(n,n) = 1.0d0\ne(1) = 0.0d0\nreturn\nend\n\n\n\nsubroutine dmatp(x,dx,y,dy,z)\ninteger dx(2),dy(2)\ndouble precision x(*), y(*),z(*),ddot\n\ninteger n,p,q,i,j\n\nn=dx(1); p=dx(2); q=dy(2)\ndo i = 1,n {\n\tjj = 1; ij = i\n\tdo j = 1, q {\n\t\tz(ij) = ddot(p,x(i),n,y(jj),1) # x[i,1] & y[1,j]\n\t\tif(j0)\n\tif (da!=0.0d0)\n\t\tif (incx!=1||incy!=1) {\n\t\t\tix = 1\n\t\t\tiy = 1\n\t\t\tif (incx<0)\n\t\t\t\tix = (-n+1)*incx+1\n\t\t\tif (incy<0)\n\t\t\t\tiy = (-n+1)*incy+1\n\t\t\tdo i = 1,n {\n\t\t\t\tdy(iy) = dy(iy)+da*dx(ix)\n\t\t\t\tix = ix+incx\n\t\t\t\tiy = iy+incy\n\t\t\t\t}\n\t\t\t}\n\t\telse {\n\t\t\tm = mod(n,4)\n\t\t\tif (m!=0) {\n\t\t\t\tdo i = 1,m\n\t\t\t\t\tdy(i) = dy(i)+da*dx(i)\n\t\t\t\tif (n<4)\n\t\t\t\t\treturn\n\t\t\t\t}\n\t\t\tmp1 = m+1\n\t\t\tdo i = mp1,n,4 {\n\t\t\t\tdy(i) = dy(i)+da*dx(i)\n\t\t\t\tdy(i+1) = dy(i+1)+da*dx(i+1)\n\t\t\t\tdy(i+2) = dy(i+2)+da*dx(i+2)\n\t\t\t\tdy(i+3) = dy(i+3)+da*dx(i+3)\n\t\t\t\t}\n\t\t\t}\nreturn\nend\n\n\n\nsubroutine dcopy(n,dx,incx,dy,incy)\ndouble precision dx(*),dy(*)\ninteger i,incx,incy,ix,iy,m,mp1,n\nif (n>0)\n\tif (incx!=1||incy!=1) {\n\t\tix = 1\n\t\tiy = 1\n\t\tif (incx<0)\n\t\t\tix = (-n+1)*incx+1\n\t\tif (incy<0)\n\t\t\tiy = (-n+1)*incy+1\n\t\tdo i = 1,n {\n\t\t\tdy(iy) = dx(ix)\n\t\t\tix = ix+incx\n\t\t\tiy = iy+incy\n\t\t\t}\n\t\t}\n\telse {\n\t\tm = mod(n,7)\n\t\tif (m!=0) {\n\t\t\tdo i = 1,m\n\t\t\t\tdy(i) = dx(i)\n\t\t\tif (n<7)\n\t\t\t\treturn\n\t\t\t}\n\t\tmp1 = m+1\n\t\tdo i = mp1,n,7 {\n\t\t\tdy(i) = dx(i)\n\t\t\tdy(i+1) = dx(i+1)\n\t\t\tdy(i+2) = dx(i+2)\n\t\t\tdy(i+3) = dx(i+3)\n\t\t\tdy(i+4) = dx(i+4)\n\t\t\tdy(i+5) = dx(i+5)\n\t\t\tdy(i+6) = dx(i+6)\n\t\t\t}\n\t\t}\nreturn\nend\n\n\n\ndouble precision function ddot(n,dx,incx,dy,incy)\ndouble precision dx(*),dy(*),dtemp\ninteger i,incx,incy,ix,iy,m,mp1,n\nddot = 0.0d0\ndtemp = 0.0d0\nif (n>0)\n\tif (incx==1&&incy==1) {\n\t\tm = mod(n,5)\n\t\tif (m!=0) {\n\t\t\tdo i = 1,m\n\t\t\t\tdtemp = dtemp+dx(i)*dy(i)\n\t\t\tif (n<5)\n\t\t\t\tgo to 10\n\t\t\t}\n\t\tmp1 = m+1\n\t\tdo i = mp1,n,5\n\t\t\tdtemp = dtemp+dx(i)*dy(i)+dx(i+1)*dy(i+1)+dx(i+2)*dy(i+2)+dx(i+3)*dy(i+3)+dx(i+4)*dy(i+4)\n\t\t10 ddot = dtemp\n\t\t}\n\telse {\n\t\tix = 1\n\t\tiy = 1\n\t\tif (incx<0)\n\t\t\tix = (-n+1)*incx+1\n\t\tif (incy<0)\n\t\t\tiy = (-n+1)*incy+1\n\t\tdo i = 1,n {\n\t\t\tdtemp = dtemp+dx(ix)*dy(iy)\n\t\t\tix = ix+incx\n\t\t\tiy = iy+incy\n\t\t\t}\n\t\tddot = dtemp\n\t\t}\nreturn\nend\n\n\n\ndouble precision function dnrm2(n,dx,incx)\ninteger nst\ndouble precision dx(*),cutlo,cuthi,hitest,sum,xmax,zero,one\ndata zero,one/0.0d0,1.0d0/\ndata cutlo,cuthi/8.232d-11,1.304d19/\nif (n<=0)\n\tdnrm2 = zero\nelse {\n\tnst = 20\n\tsum = zero\n\tnn = n*incx\n\ti = 1\n\trepeat {\n if (nst == 20) {\n goto 20\n } else if (nst == 30) {\n goto 30\n } else if (nst == 40) {\n goto 40\n } else if (nst == 80) {\n goto 80\n }\n\t\t20 if (dabs(dx(i))>cutlo)\n go to 50\n\t\tnst = 30\n\t\txmax = zero\n\t\t30 if (dx(i)==zero)\n go to 100\n\t\tif (dabs(dx(i))>cutlo)\n\t\t\tgo to 50\n\t\tnst = 40\n\t\tgo to 70\n\t\t40 if (dabs(dx(i))<=cutlo)\n\t\t\tgo to 80\n\t\tsum = (sum*xmax)*xmax\n\t\t50 hitest = cuthi/float(n)\n\t\tdo j = i,nn,incx {\n\t\t\tif (dabs(dx(j))>=hitest)\n\t\t\t\tgo to 60\n\t\t\tsum = sum+dx(j)**2\n\t\t\t}\n\t\tbreak 1\n\t\t60 i = j\n\t\tnst = 80\n\t\tsum = (sum/dx(i))/dx(i)\n\t\t70 xmax = dabs(dx(i))\n\t\tgo to 90\n\t\t80 if (dabs(dx(i))>xmax) {\n\t\t\tsum = one+sum*(xmax/dx(i))**2\n\t\t\txmax = dabs(dx(i))\n\t\t\tgo to 100\n\t\t\t}\n\t\t90 sum = sum+(dx(i)/xmax)**2\n\t\t100 i = i+incx\n\t\tif (i>nn)\n\t\t\tgo to 110\n\t\t}\n\tdnrm2 = dsqrt(sum)\n\treturn\n\t110 dnrm2 = xmax*dsqrt(sum)\n\t}\nreturn\nend\n\n\n\nsubroutine dscal(n,da,dx,incx)\ndouble precision da,dx(*)\ninteger i,incx,m,mp1,n,nincx\nif (n>0)\n\tif (incx!=1) {\n\t\tnincx = n*incx\n\t\tdo i = 1,nincx,incx\n\t\t\tdx(i) = da*dx(i)\n\t\t}\n\telse {\n\t\tm = mod(n,5)\n\t\tif (m!=0) {\n\t\t\tdo i = 1,m\n\t\t\t\tdx(i) = da*dx(i)\n\t\t\tif (n<5)\n\t\t\t\treturn\n\t\t\t}\n\t\tmp1 = m+1\n\t\tdo i = mp1,n,5 {\n\t\t\tdx(i) = da*dx(i)\n\t\t\tdx(i+1) = da*dx(i+1)\n\t\t\tdx(i+2) = da*dx(i+2)\n\t\t\tdx(i+3) = da*dx(i+3)\n\t\t\tdx(i+4) = da*dx(i+4)\n\t\t\t}\n\t\t}\nreturn\nend\n\n\n\nsubroutine dswap(n,dx,incx,dy,incy)\ndouble precision dx(*),dy(*),dtemp\ninteger i,incx,incy,ix,iy,m,mp1,n\nif (n>0)\n\tif (incx!=1||incy!=1) {\n\t\tix = 1\n\t\tiy = 1\n\t\tif (incx<0)\n\t\t\tix = (-n+1)*incx+1\n\t\tif (incy<0)\n\t\t\tiy = (-n+1)*incy+1\n\t\tdo i = 1,n {\n\t\t\tdtemp = dx(ix)\n\t\t\tdx(ix) = dy(iy)\n\t\t\tdy(iy) = dtemp\n\t\t\tix = ix+incx\n\t\t\tiy = iy+incy\n\t\t\t}\n\t\t}\n\telse {\n\t\tm = mod(n,3)\n\t\tif (m!=0) {\n\t\t\tdo i = 1,m {\n\t\t\t\tdtemp = dx(i)\n\t\t\t\tdx(i) = dy(i)\n\t\t\t\tdy(i) = dtemp\n\t\t\t\t}\n\t\t\tif (n<3)\n\t\t\t\treturn\n\t\t\t}\n\t\tmp1 = m+1\n\t\tdo i = mp1,n,3 {\n\t\t\tdtemp = dx(i)\n\t\t\tdx(i) = dy(i)\n\t\t\tdy(i) = dtemp\n\t\t\tdtemp = dx(i+1)\n\t\t\tdx(i+1) = dy(i+1)\n\t\t\tdy(i+1) = dtemp\n\t\t\tdtemp = dx(i+2)\n\t\t\tdx(i+2) = dy(i+2)\n\t\t\tdy(i+2) = dtemp\n\t\t\t}\n\t\t}\nreturn\nend\n\n\n\nsubroutine dshift(x,ldx,n,j,k)\ninteger ldx,n,j,k\ndouble precision x(ldx,k),tt\ninteger i,jj\nif (k>j)\n\tdo i = 1,n {\n\t\ttt = x(i,j)\n\t\tdo jj = j+1,k\n\t\t\tx(i,jj-1) = x(i,jj)\n\t\tx(i,k) = tt\n\t\t}\nreturn\nend\n\n\n\nsubroutine rtod(dx,dy,n)\nreal dx(*)\ndouble precision dy(*)\ninteger i,m,mp1,n\nif (n>0) {\n\tm = mod(n,7)\n\tif (m!=0) {\n\t\tdo i = 1,m\n\t\t\tdy(i) = dx(i)\n\t\tif (n<7)\n\t\t\treturn\n\t\t}\n\tmp1 = m+1\n\tdo i = mp1,n,7 {\n\t\tdy(i) = dx(i)\n\t\tdy(i+1) = dx(i+1)\n\t\tdy(i+2) = dx(i+2)\n\t\tdy(i+3) = dx(i+3)\n\t\tdy(i+4) = dx(i+4)\n\t\tdy(i+5) = dx(i+5)\n\t\tdy(i+6) = dx(i+6)\n\t\t}\n\t}\nreturn\nend\n\n\n\nsubroutine dtor(dx,dy,n)\ndouble precision dx(*)\nreal dy(*)\ninteger i,m,mp1,n\nif (n>0) {\n\tm = mod(n,7)\n\tif (m!=0) {\n\t\tdo i = 1,m\n\t\t\tdy(i) = dx(i)\n\t\tif (n<7)\n\t\t\treturn\n\t\t}\n\tmp1 = m+1\n\tdo i = mp1,n,7 {\n\t\tdy(i) = dx(i)\n\t\tdy(i+1) = dx(i+1)\n\t\tdy(i+2) = dx(i+2)\n\t\tdy(i+3) = dx(i+3)\n\t\tdy(i+4) = dx(i+4)\n\t\tdy(i+5) = dx(i+5)\n\t\tdy(i+6) = dx(i+6)\n\t\t}\n\t}\nreturn\nend\n\n\n\nsubroutine drot(n,dx,incx,dy,incy,c,s)\ndouble precision dx(*),dy(*),dtemp,c,s\ninteger i,incx,incy,ix,iy,n\nif (n>0)\n\tif (incx==1&&incy==1)\n\t\tdo i = 1,n {\n\t\t\tdtemp = c*dx(i)+s*dy(i)\n\t\t\tdy(i) = c*dy(i)-s*dx(i)\n\t\t\tdx(i) = dtemp\n\t\t\t}\n\telse {\n\t\tix = 1\n\t\tiy = 1\n\t\tif (incx<0)\n\t\t\tix = (-n+1)*incx+1\n\t\tif (incy<0)\n\t\t\tiy = (-n+1)*incy+1\n\t\tdo i = 1,n {\n\t\t\tdtemp = c*dx(ix)+s*dy(iy)\n\t\t\tdy(iy) = c*dy(iy)-s*dx(ix)\n\t\t\tdx(ix) = dtemp\n\t\t\tix = ix+incx\n\t\t\tiy = iy+incy\n\t\t\t}\n\t\t}\nreturn\nend\n\n\n\nsubroutine drotg(da,db,c,s)\ndouble precision da,db,c,s,roe,scale,r,z\nroe = db\nif (dabs(da)>dabs(db))\n\troe = da\nscale = dabs(da)+dabs(db)\nif (scale==0.0d0) {\n\tc = 1.0d0\n\ts = 0.0d0\n\tr = 0.0d0\n\t}\nelse {\n\tr = scale*dsqrt((da/scale)**2+(db/scale)**2)\n\tr = dsign(1.0d0,roe)*r\n\tc = da/r\n\ts = db/r\n\t}\nz = 1.0d0\nif (dabs(da)>dabs(db))\n\tz = s\nif (dabs(db)>=dabs(da)&&c!=0.0d0)\n\tz = 1.0d0/c\nda = r\ndb = z\nreturn\nend\n\n\n\nsubroutine dqrsl(x,ldx,n,k,qraux,y,qy,qty,b,rsd,xb,job,info)\ninteger ldx,n,k,job,info\ndouble precision x(ldx,*),qraux(*),y(*),qy(*),qty(*),b(*),rsd(*),xb(*)\ninteger i,j,jj,ju,kp1\ndouble precision ddot,t,temp\nlogical cb,cqy,cqty,cr,cxb\ninfo = 0\ncqy = job/10000!=0\ncqty = mod(job,10000)!=0\ncb = mod(job,1000)/100!=0\ncr = mod(job,100)/10!=0\ncxb = mod(job,10)!=0\nju = min0(k,n-1)\nif (ju==0) {\n\tif (cqy)\n\t\tqy(1) = y(1)\n\tif (cqty)\n\t\tqty(1) = y(1)\n\tif (cxb)\n\t\txb(1) = y(1)\n\tif (cb)\n\t\tif (x(1,1)!=0.0d0)\n\t\t\tb(1) = y(1)/x(1,1)\n\t\telse\n\t\t\tinfo = 1\n\tif (cr)\n\t\trsd(1) = 0.0d0\n\t}\nelse {\n\tif (cqy)\n\t\tcall dcopy(n,y,1,qy,1)\n\tif (cqty)\n\t\tcall dcopy(n,y,1,qty,1)\n\tif (cqy)\n\t\tdo jj = 1,ju {\n\t\t\tj = ju-jj+1\n\t\t\tif (qraux(j)!=0.0d0) {\n\t\t\t\ttemp = x(j,j)\n\t\t\t\tx(j,j) = qraux(j)\n\t\t\t\tt = -ddot(n-j+1,x(j,j),1,qy(j),1)/x(j,j)\n\t\t\t\tcall daxpy(n-j+1,t,x(j,j),1,qy(j),1)\n\t\t\t\tx(j,j) = temp\n\t\t\t\t}\n\t\t\t}\n\tif (cqty)\n\t\tdo j = 1,ju\n\t\t\tif (qraux(j)!=0.0d0) {\n\t\t\t\ttemp = x(j,j)\n\t\t\t\tx(j,j) = qraux(j)\n\t\t\t\tt = -ddot(n-j+1,x(j,j),1,qty(j),1)/x(j,j)\n\t\t\t\tcall daxpy(n-j+1,t,x(j,j),1,qty(j),1)\n\t\t\t\tx(j,j) = temp\n\t\t\t\t}\n\tif (cb)\n\t\tcall dcopy(k,qty,1,b,1)\n\tkp1 = k+1\n\tif (cxb)\n\t\tcall dcopy(k,qty,1,xb,1)\n\tif (cr&&k1)\n\tncu = min0(n,p)\nif (jobu!=0)\n\twantu = .true.\nif (mod(job,10)!=0)\n\twantv = .true.\ninfo = 0\nnct = min0(n-1,p)\nnrt = max0(0,min0(p-2,n))\nlu = max0(nct,nrt)\nif (lu>=1)\n\tdo l = 1,lu {\n\t\tlp1 = l+1\n\t\tif (l<=nct) {\n\t\t\ts(l) = dnrm2(n-l+1,x(l,l),1)\n\t\t\tif (s(l)!=0.0d0) {\n\t\t\t\tif (x(l,l)!=0.0d0)\n\t\t\t\t\ts(l) = dsign(s(l),x(l,l))\n\t\t\t\tcall dscal(n-l+1,1.0d0/s(l),x(l,l),1)\n\t\t\t\tx(l,l) = 1.0d0+x(l,l)\n\t\t\t\t}\n\t\t\ts(l) = -s(l)\n\t\t\t}\n\t\tif (p>=lp1)\n\t\t\tdo j = lp1,p {\n\t\t\t\tif (l<=nct)\n\t\t\t\t\tif (s(l)!=0.0d0) {\n\t\t\t\t\t\tt = -ddot(n-l+1,x(l,l),1,x(l,j),1)/x(l,l)\n\t\t\t\t\t\tcall daxpy(n-l+1,t,x(l,l),1,x(l,j),1)\n\t\t\t\t\t\t}\n\t\t\t\te(j) = x(l,j)\n\t\t\t\t}\n\t\tif (wantu&&l<=nct)\n\t\t\tdo i = l,n\n\t\t\t\tu(i,l) = x(i,l)\n\t\tif (l<=nrt) {\n\t\t\te(l) = dnrm2(p-l,e(lp1),1)\n\t\t\tif (e(l)!=0.0d0) {\n\t\t\t\tif (e(lp1)!=0.0d0)\n\t\t\t\t\te(l) = dsign(e(l),e(lp1))\n\t\t\t\tcall dscal(p-l,1.0d0/e(l),e(lp1),1)\n\t\t\t\te(lp1) = 1.0d0+e(lp1)\n\t\t\t\t}\n\t\t\te(l) = -e(l)\n\t\t\tif (lp1<=n&&e(l)!=0.0d0) {\n\t\t\t\tdo i = lp1,n\n\t\t\t\t\twork(i) = 0.0d0\n\t\t\t\tdo j = lp1,p\n\t\t\t\t\tcall daxpy(n-l,e(j),x(lp1,j),1,work(lp1),1)\n\t\t\t\tdo j = lp1,p\n\t\t\t\t\tcall daxpy(n-l,-e(j)/e(lp1),work(lp1),1,x(lp1,j),1)\n\t\t\t\t}\n\t\t\tif (wantv)\n\t\t\t\tdo i = lp1,p\n\t\t\t\t\tv(i,l) = e(i)\n\t\t\t}\n\t\t}\nm = min0(p,n+1)\nnctp1 = nct+1\nnrtp1 = nrt+1\nif (nct=nctp1)\n\t\tdo j = nctp1,ncu {\n\t\t\tdo i = 1,n\n\t\t\t\tu(i,j) = 0.0d0\n\t\t\tu(j,j) = 1.0d0\n\t\t\t}\n\tif (nct>=1)\n\t\tdo ll = 1,nct {\n\t\t\tl = nct-ll+1\n\t\t\tif (s(l)==0.0d0) {\n\t\t\t\tdo i = 1,n\n\t\t\t\t\tu(i,l) = 0.0d0\n\t\t\t\tu(l,l) = 1.0d0\n\t\t\t\t}\n\t\t\telse {\n\t\t\t\tlp1 = l+1\n\t\t\t\tif (ncu>=lp1)\n\t\t\t\t\tdo j = lp1,ncu {\n\t\t\t\t\t\tt = -ddot(n-l+1,u(l,l),1,u(l,j),1)/u(l,l)\n\t\t\t\t\t\tcall daxpy(n-l+1,t,u(l,l),1,u(l,j),1)\n\t\t\t\t\t\t}\n\t\t\t\tcall dscal(n-l+1,-1.0d0,u(l,l),1)\n\t\t\t\tu(l,l) = 1.0d0+u(l,l)\n\t\t\t\tlm1 = l-1\n\t\t\t\tif (lm1>=1)\n\t\t\t\t\tdo i = 1,lm1\n\t\t\t\t\t\tu(i,l) = 0.0d0\n\t\t\t\t}\n\t\t\t}\n\t}\nif (wantv)\n\tdo ll = 1,p {\n\t\tl = p-ll+1\n\t\tlp1 = l+1\n\t\tif (l<=nrt)\n\t\t\tif (e(l)!=0.0d0)\n\t\t\t\tdo j = lp1,p {\n\t\t\t\t\tt = -ddot(p-l,v(lp1,l),1,v(lp1,j),1)/v(lp1,l)\n\t\t\t\t\tcall daxpy(p-l,t,v(lp1,l),1,v(lp1,j),1)\n\t\t\t\t\t}\n\t\tdo i = 1,p\n\t\t\tv(i,l) = 0.0d0\n\t\tv(l,l) = 1.0d0\n\t\t}\nmm = m\niter = 0\nrepeat {\n\tif (m==0)\n\t\treturn\n\tif (iter>=maxit)\n\t\tbreak 1\n\tdo ll = 1,m {\n\t\tl = m-ll\n\t\tif (l==0)\n\t\t\tbreak 1\n\t\ttest = dabs(s(l))+dabs(s(l+1))\n\t\tztest = test+dabs(e(l))\n\t\tif (ztest==test)\n\t\t\tgo to 150\n\t\t}\n\tgo to 160\n\t150 e(l) = 0.0d0\n\t160 if (l==m-1)\n\t\tkase = 4\n\telse {\n\t\tlp1 = l+1\n\t\tmp1 = m+1\n\t\tdo lls = lp1,mp1 {\n\t\t\tls = m-lls+lp1\n\t\t\tif (ls==l)\n\t\t\t\tbreak 1\n\t\t\ttest = 0.0d0\n\t\t\tif (ls!=m)\n\t\t\t\ttest = test+dabs(e(ls))\n\t\t\tif (ls!=l+1)\n\t\t\t\ttest = test+dabs(e(ls-1))\n\t\t\tztest = test+dabs(s(ls))\n\t\t\tif (ztest==test)\n\t\t\t\tgo to 170\n\t\t\t}\n\t\tgo to 180\n\t\t170 s(ls) = 0.0d0\n\t\t180 if (ls==l)\n\t\t\tkase = 3\n\t\telse if (ls==m)\n\t\t\tkase = 1\n\t\telse {\n\t\t\tkase = 2\n\t\t\tl = ls\n\t\t\t}\n\t\t}\n\tl = l+1\n\tswitch(kase) {\n\t\tcase 1:\n\t\t\tmm1 = m-1\n\t\t\tf = e(m-1)\n\t\t\te(m-1) = 0.0d0\n\t\t\tdo kk = l,mm1 {\n\t\t\t\tk = mm1-kk+l\n\t\t\t\tt1 = s(k)\n\t\t\t\tcall drotg(t1,f,cs,sn)\n\t\t\t\ts(k) = t1\n\t\t\t\tif (k!=l) {\n\t\t\t\t\tf = -sn*e(k-1)\n\t\t\t\t\te(k-1) = cs*e(k-1)\n\t\t\t\t\t}\n\t\t\t\tif (wantv)\n\t\t\t\t\tcall drot(p,v(1,k),1,v(1,m),1,cs,sn)\n\t\t\t\t}\n\t\tcase 2:\n\t\t\tf = e(l-1)\n\t\t\te(l-1) = 0.0d0\n\t\t\tdo k = l,m {\n\t\t\t\tt1 = s(k)\n\t\t\t\tcall drotg(t1,f,cs,sn)\n\t\t\t\ts(k) = t1\n\t\t\t\tf = -sn*e(k)\n\t\t\t\te(k) = cs*e(k)\n\t\t\t\tif (wantu)\n\t\t\t\t\tcall drot(n,u(1,k),1,u(1,l-1),1,cs,sn)\n\t\t\t\t}\n\t\tcase 3:\n\t\t\tscale = dmax1(dabs(s(m)),dabs(s(m-1)),dabs(e(m-1)),dabs(s(l)),dabs(e(l)))\n\t\t\tsm = s(m)/scale\n\t\t\tsmm1 = s(m-1)/scale\n\t\t\temm1 = e(m-1)/scale\n\t\t\tsl = s(l)/scale\n\t\t\tel = e(l)/scale\n\t\t\tb = ((smm1+sm)*(smm1-sm)+emm1**2)/2.0d0\n\t\t\tc = (sm*emm1)**2\n\t\t\tshift = 0.0d0\n\t\t\tif (b!=0.0d0||c!=0.0d0) {\n\t\t\t\tshift = dsqrt(b**2+c)\n\t\t\t\tif (b<0.0d0)\n\t\t\t\t\tshift = -shift\n\t\t\t\tshift = c/(b+shift)\n\t\t\t\t}\n\t\t\tf = (sl+sm)*(sl-sm)+shift\n\t\t\tg = sl*el\n\t\t\tmm1 = m-1\n\t\t\tdo k = l,mm1 {\n\t\t\t\tcall drotg(f,g,cs,sn)\n\t\t\t\tif (k!=l)\n\t\t\t\t\te(k-1) = f\n\t\t\t\tf = cs*s(k)+sn*e(k)\n\t\t\t\te(k) = cs*e(k)-sn*s(k)\n\t\t\t\tg = sn*s(k+1)\n\t\t\t\ts(k+1) = cs*s(k+1)\n\t\t\t\tif (wantv)\n\t\t\t\t\tcall drot(p,v(1,k),1,v(1,k+1),1,cs,sn)\n\t\t\t\tcall drotg(f,g,cs,sn)\n\t\t\t\ts(k) = f\n\t\t\t\tf = cs*e(k)+sn*s(k+1)\n\t\t\t\ts(k+1) = -sn*e(k)+cs*s(k+1)\n\t\t\t\tg = sn*e(k+1)\n\t\t\t\te(k+1) = cs*e(k+1)\n\t\t\t\tif (wantu&&k=s(l+1))\n\t\t\t\t\tbreak 1\n\t\t\t\tt = s(l)\n\t\t\t\ts(l) = s(l+1)\n\t\t\t\ts(l+1) = t\n\t\t\t\tif (wantv&&l0; j = j-1) {\n\tif (x(j,j)==0.0d0)\n\t\t{info = j; break}\n\tfor(l=1; l<=q; l = l+1) {\n\tb(j,l) = b(j,l)/x(j,j)\n\tif (j!=1) {\n\t\tt = -b(j,l)\n\t\tcall daxpy(j-1,t,x(1,j),1,b(1,l),1)\n\t\t}\n\t}\n}\nreturn\nend\n\nsubroutine dtrsl(t,ldt,n,b,job,info)\ninteger ldt,n,job,info\ndouble precision t(ldt,*),b(*)\ndouble precision ddot,temp\ninteger which,j,jj\n# check for zero diagonal elements.\ndo info = 1,n\n\tif (t(info,info)==0.0d0)\n\t\treturn\ninfo = 0\n# determine the task and go to it.\nwhich = 1\nif (mod(job,10)!=0)\n\twhich = 2\nif (mod(job,100)/10!=0)\n\twhich = which+2\nswitch(which) {\n\tcase 1:\n\t\tb(1) = b(1)/t(1,1)\n\t\tif (n>=2)\n\t\t\tdo j = 2,n {\n\t\t\t\ttemp = -b(j-1)\n\t\t\t\tcall daxpy(n-j+1,temp,t(j,j-1),1,b(j),1)\n\t\t\t\tb(j) = b(j)/t(j,j)\n\t\t\t\t}\n\tcase 2:\n\t\tb(n) = b(n)/t(n,n)\n\t\tif (n>=2)\n\t\t\tdo jj = 2,n {\n\t\t\t\tj = n-jj+1\n\t\t\t\ttemp = -b(j+1)\n\t\t\t\tcall daxpy(j,temp,t(1,j+1),1,b(1),1)\n\t\t\t\tb(j) = b(j)/t(j,j)\n\t\t\t\t}\n\tcase 3:\n\t\tb(n) = b(n)/t(n,n)\n\t\tif (n>=2)\n\t\t\tdo jj = 2,n {\n\t\t\t\tj = n-jj+1\n\t\t\t\tb(j) = b(j)-ddot(jj-1,t(j+1,j),1,b(j+1),1)\n\t\t\t\tb(j) = b(j)/t(j,j)\n\t\t\t\t}\n\tcase 4:\n\t\tb(1) = b(1)/t(1,1)\n\t\tif (n>=2)\n\t\t\tdo j = 2,n {\n\t\t\t\tb(j) = b(j)-ddot(j-1,t(1,j),1,b(1),1)\n\t\t\t\tb(j) = b(j)/t(j,j)\n\t\t\t\t}\n\t}\nreturn\nend\n", "meta": {"hexsha": "de4a18f0739db3326fe73a022b87c187ee407b1b", "size": 48591, "ext": "r", "lang": "R", "max_stars_repo_path": "gam/ratfor/linear.r", "max_stars_repo_name": "solgenomics/R_libs", "max_stars_repo_head_hexsha": "a936847f6063cdf3d207e8364f05f2e13be2d878", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "gam/ratfor/linear.r", "max_issues_repo_name": "solgenomics/R_libs", "max_issues_repo_head_hexsha": "a936847f6063cdf3d207e8364f05f2e13be2d878", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-08-17T15:14:11.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-23T21:55:49.000Z", "max_forks_repo_path": "gam/ratfor/linear.r", "max_forks_repo_name": "solgenomics/R_libs", "max_forks_repo_head_hexsha": "a936847f6063cdf3d207e8364f05f2e13be2d878", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-11-04T05:34:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-04T05:34:16.000Z", "avg_line_length": 19.0105633803, "max_line_length": 97, "alphanum_fraction": 0.4581301064, "num_tokens": 22258, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7310585786300049, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.37694836270179066}} {"text": "library(tidyverse)\n\n# データ読み込み\ndata <- read_csv(\"Hackathon_Ideal_Data.csv\")\n\n# ビスケットのデータを取り出す\ndata_biscuits <- data %>% filter(GRP == \"BISCUITS - CORE & NON CORE\")\n\n## 前処理\n\n# ブランドをメーカーブランドにまとめる(ブランドにフレーバー含まれることあるため)\ndata_biscuits_agg <- data_biscuits %>% \n group_by(MONTH, STORECODE, SGRP, CMP, MBRD) %>% \n summarise(across(c(QTY, VALUE), sum), .groups=\"drop\") %>% \n filter(QTY > 0) # 数量が1以上のレコードだけ残す\n\n# 同じメーカーブランドでも企業名やジャンルが違うレコードあるか確認\ndata_biscuits_agg %>% distinct(SGRP, CMP, MBRD) %>% group_by(MBRD) %>% filter(n() > 1)\n\n# メーカーの表記ゆれと同一ブランドでも違うジャンルのものがあることがわかった\n# 前処理してからもう一度メーカブランドにまとめる処理する\ndata_biscuits <- data_biscuits %>% \n # メーカーの表記ゆれ直す\n mutate(CMP = case_when(\n CMP == \"KAIRA DISTRICT CO-OP MILK\" ~ \"G C M M F\",\n CMP == \"CHAMPION\" ~ \"SUKHDATA FOODS\",\n CMP == \"PATANJALI AYURVED LTD\" ~ \"PATANJALI BISCUITS PVT LTD\",\n CMP == \"PICKWICK HYGIENIC PRODUCTS\" ~ \"PRIMLAKS\",\n TRUE ~ CMP\n )) %>% \n # メーカブランド名にジャンルも含める\n mutate(MBRD2 = paste0(MBRD, \" (\", SGRP, \")\")) %>% \n # 集計\n group_by(MONTH, STORECODE, SGRP, CMP, MBRD2) %>% \n summarise(across(c(QTY, VALUE), sum), .groups=\"drop\") %>% \n filter(QTY > 0, VALUE > 0) # 数量および金額が0より大きい\n\n# いずれかの月において1店舗でしか販売されていない商品\nbiscuits_only1shop <- data_biscuits %>% \n distinct(MONTH, STORECODE, MBRD2) %>% \n group_by(MONTH, MBRD2) %>% \n filter(n() == 1) %>% \n ungroup() %>% \n distinct(MBRD2) %>% \n pull()\n\n# いずれかの月において1店舗でしか販売されていない商品をデータから除く\ndata_biscuits <- data_biscuits %>% \n filter(!(MBRD2 %in% biscuits_only1shop))\n\n## データ構築\n\n# 潜在的市場規模\ndata_biscuits <- data_biscuits %>% \n group_by(MONTH, STORECODE) %>% \n mutate(quantity_total = sum(QTY)) %>% # 各市場の総売上数量\n group_by(STORECODE) %>% \n mutate(market_size = max(quantity_total) * 2) %>% #各店舗の最大総売上数量の2倍を潜在的市場規模とする\n ungroup()\n\n# シェアの列作る\ndata_biscuits <- data_biscuits %>% \n mutate(share = QTY / market_size) %>% # シェア\n group_by(MONTH, STORECODE) %>% \n mutate(outshare = 1 - sum(share)) %>% # 「何も買わない」のシェア\n ungroup()\n\n# 価格の列作る\ndata_biscuits <- data_biscuits %>% \n mutate(price = VALUE / QTY)\n\n# 価格の操作変数として各商品の同月他店舗平均価格\ndata_biscuits <- data_biscuits %>% \n group_by(MONTH, MBRD2) %>% \n mutate(price_instruments = (sum(price) - price) / (n() - 1)) %>% \n ungroup()\n\n# グループ内シェア\n# ジャンルをグループにする\ndata_biscuits <- data_biscuits %>% \n group_by(MONTH, STORECODE, SGRP) %>% \n mutate(within_share = share / sum(share)) %>% \n ungroup()\n\n# グループ内シェアの操作変数として各商品の同月他店舗平均グループ内シェア\ndata_biscuits <- data_biscuits %>% \n group_by(MONTH, MBRD2) %>% \n mutate(within_share_instruments = (sum(within_share) - within_share) / (n() - 1)) %>% \n ungroup()\n\n## plain logit推定\n\nplain_logit <- estimatr::iv_robust(\n formula = log(share) - log(outshare) ~ log(price) | log(price_instruments),\n data = data_biscuits,\n fixed_effects = ~ MBRD2,\n clusters = MBRD2,\n se_type = 'stata'\n)\n\nsummary(plain_logit) # 推定結果\n\n## plain logit 反実仮想\n\n# 予測値を出すために商品ダミーを明示的に説明変数に入れる\nplain_logit_prediction <- estimatr::iv_robust(\n formula = log(share) - log(outshare) ~ log(price) + factor(MBRD2) | log(price_instruments) + factor(MBRD2),\n data = data_biscuits\n)\n\n# オレオの価格を20%安くしてみる\ndata_biscuits_counterfactual_plain <- data_biscuits %>% \n mutate(price_original = price, # 元の価格を残す\n price = if_else(MBRD2 == \"OREO (CREAM)\", 0.8 * price, price))\n\n# 平均効用deltaを計算\ndelta_plain <- predict(plain_logit_prediction,\n newdata = data_biscuits_counterfactual_plain)\n\n# 反実仮想シェアを計算\ndata_biscuits_counterfactual_plain <- \n data_biscuits_counterfactual_plain %>% \n mutate(delta_counterfactual = delta_plain, # 反実仮想の平均効用\n delta_fitted = fitted(plain_logit) # 元の価格での平均効用のフィット\n ) %>%\n group_by(MONTH, STORECODE) %>% # 市場でグループ化\n # シェア計算\n mutate(share_counterfactual = exp(delta_counterfactual) / (1 + sum(exp(delta_counterfactual))),\n share_fitted = exp(delta_fitted) / (1 + sum(exp(delta_fitted)))) %>%\n ungroup() %>% \n # 数量と金額を計算\n mutate(quantity_counterfactual = share_counterfactual * market_size,\n quantity_fitted = share_fitted * market_size,\n value_counterfactual = price * quantity_counterfactual,\n value_fitted = price_original * quantity_fitted)\n\n# MONDELEZの実際の売上と反実仮想売上を比較\ndata_biscuits_counterfactual_plain %>% \n filter(CMP == \"MONDELEZ INTERNATIONAL\") %>% \n group_by(MBRD2) %>% \n summarise(across(c(QTY, quantity_fitted, quantity_counterfactual,\n VALUE, value_fitted, value_counterfactual),\n sum),\n .groups=\"drop\") %>% \n modelsummary::datasummary_df(fmt=1, output='markdown')\n\n## nested logit推定\n\nnested_logit <- estimatr::iv_robust(\n formula = log(share) - log(outshare) ~ log(price) + log(within_share) | log(price_instruments) + log(within_share_instruments),\n data = data_biscuits,\n fixed_effects = MBRD2,\n clusters = MBRD2,\n se_type = 'stata')\n\nsummary(nested_logit) # 推定結果\n\n## nested logit 反実仮想\n\n# 予測値を出すために商品ダミーを明示的に説明変数に入れる\nnested_logit_prediction <- estimatr::iv_robust(\n formula = log(share) - log(outshare) ~ log(price) + log(within_share) + factor(MBRD2) | log(price_instruments) + log(within_share_instruments) + factor(MBRD2),\n data = data_biscuits\n)\n\n# オレオの価格を20%安くしてみる\ndata_biscuits_counterfactual_nested <- data_biscuits %>% \n mutate(price_original = price,\n price = if_else(MBRD2 == \"OREO (CREAM)\", 0.8 * price, price))\n\n# 平均効用deltaを計算\n# モデルの予測値にはrho*log(within_share)の部分も含まれているのでそれを除く\nrho <- coef(nested_logit)['log(within_share)'] # rho\ndelta_nested <- \n predict(nested_logit_prediction, newdata = data_biscuits_counterfactual_nested) -\n rho * log(data_biscuits$within_share)\n\n# deltaとrhoの列を加える\ndata_biscuits_counterfactual_nested <- data_biscuits_counterfactual_nested %>% \n mutate(rho = rho,\n delta_counterfactual = delta_nested,\n delta_fitted = fitted(nested_logit) - rho * log(within_share))\n\n# 各グループの包括的価値(inclusive value)を計算する\ndata_biscuits_counterfactual_nested_inclusive <- data_biscuits_counterfactual_nested %>% \n group_by(MONTH, STORECODE, SGRP) %>% \n # 各グループの包括的価値\n summarise(inclusive_counterfactual = sum(exp(delta_counterfactual / (1 - rho))),\n inclusive_fitted = sum(exp(delta_fitted / (1 - rho))),\n .groups=\"drop\") %>%\n mutate(rho = rho) %>% \n group_by(MONTH, STORECODE) %>% \n # 包摂的価値の市場内集計\n mutate(inclusive_counterfactual_sum = 1 + sum(inclusive_counterfactual^(1-rho)),\n inclusive_fitted_sum = 1 + sum(inclusive_fitted^(1-rho))) %>%\n ungroup() %>% \n select(!rho)\n\n# 元のデータフレームに包摂的価値を引っ付ける\ndata_biscuits_counterfactual_nested <- data_biscuits_counterfactual_nested %>% \n left_join(data_biscuits_counterfactual_nested_inclusive, by = c(\"MONTH\", \"STORECODE\", \"SGRP\"))\n\n# 予測シェアと数量と売上金額を計算\ndata_biscuits_counterfactual_nested <- data_biscuits_counterfactual_nested %>% \n mutate(share_counterfactual = exp(delta_counterfactual / (1 - rho)) / (inclusive_counterfactual^rho * inclusive_counterfactual_sum),\n share_fitted = exp(delta_fitted / (1 - rho)) / (inclusive_fitted^rho * inclusive_fitted_sum),\n quantity_counterfactual = share_counterfactual * market_size,\n quantity_fitted = share_fitted * market_size,\n value_counterfactual = price * quantity_counterfactual,\n value_fitted = price_original * quantity_fitted)\n\n# MONDELEZの実際の売上と反実仮想売上を比較\ndata_biscuits_counterfactual_nested %>% \n filter(CMP == \"MONDELEZ INTERNATIONAL\") %>% \n group_by(MBRD2) %>% \n summarise(across(c(QTY, quantity_fitted, quantity_counterfactual,\n VALUE, value_fitted, value_counterfactual),\n sum),\n .groups=\"drop\") %>% \n modelsummary::datasummary_df(fmt=1)\n", "meta": {"hexsha": "e1274f9d33a8cf112ac41694f65a85106ab143ca", "size": 7558, "ext": "r", "lang": "R", "max_stars_repo_path": "demand_estimation.r", "max_stars_repo_name": "mns54/tokyor-demand-estimation", "max_stars_repo_head_hexsha": "27aeb9d7a5585e0174a5f9ecfaf6a2d407f9cdf9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-05-29T07:02:44.000Z", "max_stars_repo_stars_event_max_datetime": "2021-05-29T18:38:42.000Z", "max_issues_repo_path": "demand_estimation.r", "max_issues_repo_name": "mns54/tokyor-demand-estimation", "max_issues_repo_head_hexsha": "27aeb9d7a5585e0174a5f9ecfaf6a2d407f9cdf9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "demand_estimation.r", "max_forks_repo_name": "mns54/tokyor-demand-estimation", "max_forks_repo_head_hexsha": "27aeb9d7a5585e0174a5f9ecfaf6a2d407f9cdf9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.1990950226, "max_line_length": 161, "alphanum_fraction": 0.7013760254, "num_tokens": 2988, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6992544210587585, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.3768863999423516}} {"text": "\n## ########################################### ##\n## SOFTWARE LICENSE AGREEMENT ##\n## ########################################### ##\n\n# This work is licensed under a Creative Commons Attribution 4.0 International License.\n# See http://creativecommons.org/licenses/by/4.0/ for details on license restrictions.\n# Please attribute any work that makes use or is derived from this work\n# by refering to https://github.com/jalmar/openmx-models\n\n\n## ########################################### ##\n## DESCRIPTION OF FILE ##\n## ########################################### ##\n\n# In this R script, a measurement model with two latent factors (nf=2) is provided.\n# This measurement model can be used to obtain a estimate of the association between\n# the reliable components of two constructs that is free of random measurement error.\n# In this example, there are two constructs with a total of three observed variables (nv=3).\n# Two parallel scores \"M1_H1\" and \"M1_H2\" are available for the first construct \"M1\".\n# The first latent factor \"F1\" is derived from these two parallel scores.\n# Since the two parallel scores are measurements of the same construct,\n# their expected means are constrained to be equal.\n# The second latent factor \"F1\" is derived from the single score of the second construct \"M2\".\n# If there are repeated measurements of the second construct \"M2\", the measurement model\n# can easily be expanded for reliablity modelling of the second construct \"M2\".\n# The quality of the fit is assessed with the Comparative Fit Index (CFI),\n# the Tucker-Lewis Index (TLI), and the Root Mean Square Error of the Approximation (RMSEA).\n# These fit indices are based on the comparison between the measurement model to\n# a saturated model and an independence (or null) model. The saturated model is a model that\n# estimates all means, variances and covariances freely for all variables (i.e. unconstrained).\n# The independence model estimates only the means and variances with covariances fixed to zero.\n# Finally, a summary of the most relevant parameters is printed.\n# For more details, see https://github.com/jalmar/openmx-models/reliability\n\n\n## ############################################################################\n\n\n## ########################################### ##\n## LOAD LIBRARIES AND SET OPTIONS ##\n## ########################################### ##\n\n## load OpenMx library\nrequire(OpenMx) # SEM\noptions(warn=1)\n\n\n## ########################################### ##\n## INPUT DATASETS AND SELECTED VARIABLES ##\n## ########################################### ##\n\n## INPUT: a data frame data_df with the parallel and single scores measurements\ndata_df <- readRDS(\"ExampleData.rds\")\nselVars <- c(\"FC_Z_H1\", \"FC_Z_H2\", \"BHV\")\n\n\n## ########################################### ##\n## CALCULATE MEANS AND (CO)VARIANCES ##\n## ########################################### ##\n\n## calculate initial mean and variance of measures\ninit_means <- apply(data_df[,selVars, drop=F], 2, mean, na.rm=T)\ninit_vars <- apply(data_df[,selVars, drop=F], 2, var, na.rm=T)\ninit_sds <- apply(data_df[,selVars, drop=F], 2, sd, na.rm=T)\n\n## calculate initial covariance matrices between measures\ninit_covars <- var(data_df[,selVars, drop=F], na.rm=T)\ninit_corrs <- cor(data_df[,selVars, drop=F], method=\"pearson\", use=\"pairwise.complete.obs\")\n\n\n## ########################################### ##\n## MEASUREMENT MODEL PARAMETERS ##\n## ########################################### ##\n\n## number of observed variables\nnf=2 # number of factors\nnv=3 # number of measurements\n\n## initial guess at factor variances [nf x nf matrices]; NOTE: standardized symmetric matrix with variances on diagnoal fixed to 1.0!\n# initialize with rough estimate of expected correlation; e.g. corr(M1_H1, M2)\ninit_factor_variance_values = c(1.0, 0.5,\n 0.5, 1.0)\ninit_factor_variance_paths = c(F, T,\n T, F)\ninit_factor_variance_labels = c(\"varF1\", \"covF12\",\n \"covF12\", \"varF2\")\n\n## loading of factors on the measures [nf x nv matrices]:\n# factor 1 loads on the two parallel scores of measure 1\n# factor 2 loads on the single score of measure 2\n# initialize with rough estimate of factor loadings; e.g. cov(M1_H1, M1_H2))\ninit_factor_loading_values = c(0.70, 0.70, 0.00, # factor 1\n 0.00, 0.00, 1.00) # factor 2\ninit_factor_loading_paths = c(T, T, F, # factor 1\n F, F, F) # factor 2; NOTE: third position fixed for single score measurement\ninit_factor_loading_labels = c(\"f1\", \"f1\", NA, # factor 1\n NA, NA, \"f2\") # factor 2\n\n## loadings of residual variances on the measures [1 x nv matrices]\n# initialize with rough estimate of residual variance; e.g. 1 - sqrt(corr(M1_H1, M1_H2)) or 1 - factor loading\ninit_es_loading_values = c(0.30, 0.30, 0.00)\ninit_es_loading_paths = c(T, T, F) # NOTE: third position fixed for single score measurement\ninit_es_loading_labels = paste0(\"es\", 1:nv)\n\n## restrict the means of variables to be equal through shared labels [1 x nv matrices]\n# Here, the means for parallel scores of the same construct are contrained to be equal\ninit_means_labels = c(\"mean_FC_Z\", \"mean_FC_Z\", \"mean_BHV\")\n\n\n## ########################################### ##\n## OPENMX SPECIFICATION OF MEASUREMENT MODEL ##\n## ########################################### ##\n\n## measurement model\nMeasurementModel <- mxModel(\"mm\",\n \n # variance matrix Vf to store total variance for latent phenotypic factor; NOTE: standardized with variance on diagonals fixed to 1.0\n mxMatrix(type=\"Full\", nrow=nf, ncol=nf, free=init_factor_variance_paths, values=init_factor_variance_values, labels=init_factor_variance_labels, name=\"Vf\", lbound=-1, ubound=1),\n \n # matrices for correlations between latent factors (only nf>1)\n mxMatrix(type=\"Iden\", ncol=nf, nrow=nf, name=\"Idnf\"), # identity matrix of size nf x nf\n mxAlgebra(expression=solve(sqrt(Idnf*Vf)) %*% Vf %*% solve(sqrt(Idnf*Vf)), name=\"Rphf\"),\n \n # matrix fs to store path coefficients for latent phenotypic factors loading on observed variables\n mxMatrix(type=\"Full\", nrow=nv, ncol=nf, free=init_factor_loading_paths, values=init_factor_loading_values*init_vars, labels=init_factor_loading_labels, name=\"fs\", lbound=0),\n \n # matrix es to store path coefficients for measurement-specific factors loading on each measurement; NOTE: fixing off-diagonals to zero assumes no correlation between residual variances of measurements\n mxMatrix(type=\"Diag\", nrow=nv, ncol=nv, free=init_es_loading_paths, values=init_es_loading_values*init_vars, labels=init_es_loading_labels, name=\"es\", lbound=0),\n \n # matrix Es to store variance for measurement-specific factors\n mxAlgebra(expression=es%*%t(es), name=\"Es\"),\n \n # total variance of the measures is the proportion of variance explained by the factor(s) plus residual variances\n mxAlgebra(expression=fs%&%Vf+Es, name=\"Vm\"), # (co)variances between the measures\n mxMatrix(type=\"Iden\", nrow=nv, ncol=nv, free=F, name=\"Inv\"),\n mxAlgebra(expression=solve(sqrt(Inv*Vm)), name=\"SDm\"), # standard deviation of the measures\n \n # phenotypic correlation between measures\n mxAlgebra(expression=solve(sqrt(Inv*Vm)) %*% Vm %*% solve(sqrt(Inv*Vm)), name=\"Rphm\"),\n \n # standardized estimates for loadings on latent factor\n mxAlgebra(expression=SDm%*%fs, \"Fs_std\"),\n mxAlgebra(expression=Fs_std*Fs_std, \"Fs_std2\"),\n \n # standardized estimates for measurement-specific factors\n mxAlgebra(expression=SDm%*%es, name=\"Es_std\"),\n mxAlgebra(expression=Es_std*Es_std, name=\"Es_std2\"),\n \n # observed data of subjects\n mxData(observed=data_df, type=\"raw\"),\n \n # expected means vector\n mxMatrix(type=\"Full\", nrow=1, ncol=nv, free=T, values=init_means, labels=init_means_labels, name=\"expMeans\"),\n \n # expected covariance matrix; NOTE: %&% is quadratic product (A %&% B == ABA'); same as Vm\n mxAlgebra(expression=mm.fs %&% mm.Vf + mm.Es, name=\"expCov\"),\n \n # optimization objective\n mxExpectationNormal(means=\"expMeans\", covariance=\"expCov\", dimnames=selVars),\n mxFitFunctionML(),\n \n # calculate confidence intervals of freely estimated parameters\n mxCI(sprintf(\"mm.Fs_std2[%s]\", apply(which(matrix(init_factor_loading_paths, nrow=nv, ncol=nf), arr.ind = TRUE), MARGIN=1, paste0, collapse=\",\")), interval = 0.95, type=\"both\"), # standardized factor loadings\n mxCI(sprintf(\"mm.Rphf[%s]\", apply(which(lower.tri(matrix(1,nf,nf)), arr.ind = TRUE), MARGIN=1, paste0, collapse=\",\")), interval = 0.95, type=\"both\"), # correlation between factors\n mxCI(sprintf(\"mm.Rphm[%s]\", apply(which(lower.tri(matrix(1,nv,nv)), arr.ind = TRUE), MARGIN=1, paste0, collapse=\",\")), interval = 0.95, type=\"both\") # correlation between measures\n \n) # END of mxModel MeasurementModel\n\n## assign first value to parameters with same labels but different starting values\nMeasurementModel <- omxAssignFirstParameters(MeasurementModel)\n\n\n## ########################################### ##\n## FIT THE MEASUREMENT MODEL ##\n## ########################################### ##\n\nMeasurementModelFit <- mxTryHard(MeasurementModel, extraTries=30, checkHess=F, intervals=T, silent=T)\n\n\n## ########################################### ##\n## EXTRACT PARAMETERS OF INTEREST FROM MODEL ##\n## ########################################### ##\n\n## summary of measurement model model fit\nprint(summary(MeasurementModelFit))\n\n## corrected/reliable association between the two constructs\nmessage(sprintf(\"Corrected association between the two constructs = %0.3f [%0.3f; %0.3f]\", MeasurementModelFit$output$algebras$mm.Rphf[2,1], MeasurementModelFit$output$confidenceIntervals[\"mm.Rphf[2,1]\",\"lbound\"], MeasurementModelFit$output$confidenceIntervals[\"mm.Rphf[2,1]\",\"ubound\"]))\n\n## standardized factor loading on parallel scores of the first construct\nmessage(sprintf(\"Standardized factor loading on first parallel score = %2.1f%% [%2.1f%%; %2.1f%%]\", MeasurementModelFit$output$algebras$mm.Fs_std2[1,1]*100, MeasurementModelFit$output$confidenceIntervals[\"mm.Fs_std2[1,1]\",\"lbound\"]*100, MeasurementModelFit$output$confidenceIntervals[\"mm.Fs_std2[1,1]\",\"ubound\"]*100))\nmessage(sprintf(\"Standardized factor loading on second parallel score = %2.1f%% [%2.1f%%; %2.1f%%]\", MeasurementModelFit$output$algebras$mm.Fs_std2[2,1]*100, MeasurementModelFit$output$confidenceIntervals[\"mm.Fs_std2[2,1]\",\"lbound\"]*100, MeasurementModelFit$output$confidenceIntervals[\"mm.Fs_std2[2,1]\",\"ubound\"]*100))\n\n## test-retest reliability between the two parallel scores\nmessage(sprintf(\"Test-retest reliability between the two parallel scores = %0.3f [%0.3f; %0.3f]\", MeasurementModelFit$output$algebras$mm.Rphm[2,1], MeasurementModelFit$output$confidenceIntervals[\"mm.Rphm[2,1]\",\"lbound\"], MeasurementModelFit$output$confidenceIntervals[\"mm.Rphm[2,1]\",\"ubound\"]))\n\n## uncorrected associations of the individual parallel scores with the second measurement\nmessage(sprintf(\"Uncorrected association between the first parallel score and second construct = %0.3f [%0.3f; %0.3f]\", MeasurementModelFit$output$algebras$mm.Rphm[3,1], MeasurementModelFit$output$confidenceIntervals[\"mm.Rphm[3,1]\",\"lbound\"], MeasurementModelFit$output$confidenceIntervals[\"mm.Rphm[3,1]\",\"ubound\"]))\nmessage(sprintf(\"Uncorrected association between the second parallel score and second construct = %0.3f [%0.3f; %0.3f]\", MeasurementModelFit$output$algebras$mm.Rphm[3,2], MeasurementModelFit$output$confidenceIntervals[\"mm.Rphm[3,2]\",\"lbound\"], MeasurementModelFit$output$confidenceIntervals[\"mm.Rphm[3,2]\",\"ubound\"]))\n\n\n## ########################################### ##\n## DETERMINE GOODNESS OF FIT ##\n## ########################################### ##\n\n## specification of the saturated model\nSaturatedModel <- mxModel(\"sat\",\n \n # expected (co)variance matrix; unconstrained variances and covariance estimates\n mxMatrix(type=\"Symm\", nrow=nv, ncol=nv, free=T, values=vech(init_covars), name=\"expCov\"),\n \n # observed data of subjects\n mxData(observed=data_df, type=\"raw\"),\n \n # expected means vector; unconstrained means estimates\n mxMatrix(type=\"Full\", nrow=1, ncol=nv, free=T, values=init_means, labels=paste0(\"mean_m\",1:nv), name=\"expMeans\"),\n \n # optimization objective\n mxExpectationNormal(means=\"expMeans\", covariance=\"expCov\", dimnames=selVars),\n mxFitFunctionML()\n \n) # END of mxModel SaturatedModel\n\nSaturatedModel <- omxAssignFirstParameters(SaturatedModel)\n\n## specification of the independence/null model\nIndependenceModel <- mxModel(\"indep\",\n \n # expected (co)variance matrix; unconstrained variances and covariance estimates\n mxMatrix(type=\"Diag\", nrow=nv, ncol=nv, free=T, values=init_vars, name=\"expCov\"),\n \n # observed data of subjects\n mxData(observed=data_df, type=\"raw\"),\n \n # expected means vector; same means constraints as substantive model\n mxMatrix(type=\"Full\", nrow=1, ncol=nv, free=T, values=init_means, labels=init_means_labels, name=\"expMeans\"),\n \n # optimization objective\n mxExpectationNormal(means=\"expMeans\", covariance=\"expCov\", dimnames=selVars),\n mxFitFunctionML()\n \n) # END of mxModel IndependenceModel\n\nIndependenceModel <- omxAssignFirstParameters(IndependenceModel)\n\n## fit saturated and independence model\nSaturatedModelFit <- mxTryHard(SaturatedModel, extraTries=10, checkHess=F, intervals=F)\nIndependenceModelFit <- mxTryHard(IndependenceModel, extraTries=10, checkHess=F, intervals=F)\n\n## print goodness of fit indices\ntmp_summary <- summary(MeasurementModelFit, refModels=list(Saturated=SaturatedModelFit, Independence=IndependenceModelFit))\nmessage(sprintf(\"Goodness of fit indices are CFI=%0.3f, TLI=%0.3f, and RMSEA=%0.3f\", tmp_summary$CFI, tmp_summary$TLI, tmp_summary$RMSEA))\n\n", "meta": {"hexsha": "ff92a2e0dcea98605a1a22aa69a68e47a24d6ed3", "size": 13983, "ext": "r", "lang": "R", "max_stars_repo_path": "reliability/MeasurementModel.r", "max_stars_repo_name": "jalmar/openmx-models", "max_stars_repo_head_hexsha": "550ba901a395d793739b2d4dcb9163159848528f", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-08-25T10:48:32.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-04T18:18:43.000Z", "max_issues_repo_path": "reliability/MeasurementModel.r", "max_issues_repo_name": "jalmar/openmx-models", "max_issues_repo_head_hexsha": "550ba901a395d793739b2d4dcb9163159848528f", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "reliability/MeasurementModel.r", "max_forks_repo_name": "jalmar/openmx-models", "max_forks_repo_head_hexsha": "550ba901a395d793739b2d4dcb9163159848528f", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 54.8352941176, "max_line_length": 318, "alphanum_fraction": 0.6709575914, "num_tokens": 3551, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.689305616785446, "lm_q2_score": 0.546738151984614, "lm_q1q2_score": 0.37686967907388924}} {"text": "#' Extract the midpoint of an interval assigned to a data frame.\r\n#'\r\n#' \\code{interval_mid} Calculates the mid-point of an interval to be used as an\r\n#' attractive label for plot axes when binning an axis. Intervals as defined by\r\n#' functions such as base-R \\code{\\link{cut}}.\r\n#'\r\n#' @author Alex M Trueman\r\n#'\r\n#' @param x A numeric vector or data frame column with intervals typically\r\n#' applied using the base-R \\code{cut} function.\r\n#' @param dp A numeric scalar (default 1) defining the number of decimal places\r\n#' for the base-R \\code{round} function. May be needed to ensure that\r\n#' mid-points are unique.\r\n#' @return A numeric vector containing the mid points of the intervals.\r\n#' @keywords internal\r\ninterval_mid <- function(x, dp = 1) {\r\n # Extract lower and upper bounds of the intervals.\r\n lower <- as.double(gsub(\",.*\", \"\", gsub(\"\\\\(|\\\\[|\\\\)|\\\\]\", \"\", x)))\r\n upper <- as.double(gsub(\".*,\", \"\", gsub(\"\\\\(|\\\\[|\\\\)|\\\\]\", \"\", x)))\r\n # Return midpoint.\r\n return(as.double(round(lower + (upper - lower) / 2, dp)))\r\n}\r\n\r\n#' Calculate Data for Contact Analysis\r\n#'\r\n#' \\code{contact_data} generates data from domain-coded drillhole data suitable\r\n#' for plotting contact analysis plots. For each possible pairing of categorical\r\n#' domain codes it reports the distance and grade of drillhole samples from each\r\n#' contact of the domain pairing. The distance for the first domain in the\r\n#' pairing ('left' side) is reported as a negative distance for plotting\r\n#' purposes.\r\n#'\r\n#' Uses nested for loops, which is not ideal for speed. I am sure that more can\r\n#' be done by vecorizing one or more loops, but, for now, it works and is fast\r\n#' enought to be practical. For example: the dataset 'dholes' contains 24,673\r\n#' records in 371 drillholes with 13 valid domain contact pairings. This dataset\r\n#' takes <50 seconds to process on a fast laptop (2018 i9 CPU).\r\n#'\r\n#' @param df Data frame with columns defined in the following arguments.\r\n#' @param grade Name of column in \\code{df} containing numeric values to be\r\n#' averaged by contact distance.\r\n#' @param bhid Name of column in \\code{df} containing character or numeric\r\n#' categorical hole ID (default `bhid`) identifying each unique drillhole.\r\n#' @param from,to Name of numeric columns of \\code{df} with the downhole\r\n#' distance to the start and end of sample intervals (defaults \\code{from} and\r\n#' \\code{to}).\r\n#' @param x,y,z Name of numeric columns of \\code{df} with the cartesian\r\n#' coordinates of the sample mid-points (defaults \\code{x}, \\code{y}, and\r\n#' \\code{z}).\r\n#' @param domain Name of the column in \\code{df} containing the character or\r\n#' numeric categorical codes for domains across which contact analysis will be\r\n#' performed (default \\code{domain}).\r\n#' @param pairs Matrix of domain pairs to be used in the contact analysis.\r\n#' Organized in columns of pairs with two rows each.\r\n#' @param max_dist Positive numeric scalar for the maximum contact distance to\r\n#' be calculated (default \\code{15}).\r\n#' @param min_samp Positive integer scalar for the minimum number of samples on\r\n#' each side of the contact (default \\code{5}). If less than this the data\r\n#' won't be returned. This helps remove domain pairings with too few data.\r\n#'\r\n#' @return A list of two data frames 'detail' and 'summary'. 'detail' contains\r\n#' all data points while 'summary' contains mean grade by binned distances.\r\n#' @export\r\n#' @importFrom assertthat assert_that is.scalar\r\n#' @importFrom dplyr group_by select mutate summarise\r\n#' @importFrom magrittr %<>% %>%\r\n#' @importFrom rlang !! .data enquo quo_name\r\n#' @importFrom stats na.omit\r\n#' @importFrom utils combn\r\n#' @examples\r\n#' # Smaller dataset for speed.\r\n#' dholes_sub <- dholes[dholes$domain < 4000,]\r\n#' ca <- contact_data(dholes_sub, grade, max_dist = 20)\r\n#'\r\n#' # Extract only certain contacts from contact data.\r\n#' ca_1100 <- purrr::map(ca, ~dplyr::filter(.x, grepl(\"1100\", contact)))\r\ncontact_data <- function(df, grade, bhid = bhid, from = from, to = to,\r\n x = x, y = y, z= z, domain = domain, max_dist = 15, min_samp = 5,\r\n pairs = NULL) {\r\n\r\n grade <- enquo(grade)\r\n grade_str <- quo_name(grade)\r\n domain <- enquo(domain)\r\n domain_str <- quo_name(domain)\r\n\r\n # All args passed as symbols (rather than strings) to be consistent.\r\n bhid_str <- quo_name(enquo(bhid))\r\n from_str <- quo_name(enquo(from))\r\n to_str <- quo_name(enquo(to))\r\n x_str <- quo_name(enquo(x))\r\n y_str <- quo_name(enquo(y))\r\n z_str <- quo_name(enquo(z))\r\n\r\n # Assertions on arguments.\r\n # 'df' is a data frame containing the columns defined by other arguments.\r\n assert_that(is.data.frame(df),\r\n msg = \"Argument `df` is not a data frame.\")\r\n assert_that(all(\r\n c(bhid_str, domain_str, grade_str, from_str, to_str, x_str, y_str, z_str)\r\n %in% colnames(df)),\r\n msg = paste0(\r\n \"One of the required columns not in the supplied data frame.\"))\r\n # 'grade' , 'from', 'to', 'x', 'y', 'z' are all numeric.\r\n assert_that(is.numeric(df[[grade_str]]),\r\n msg = \"`grade` must be numeric.\")\r\n assert_that(is.numeric(df[[from_str]]),\r\n msg = \"`from` must be numeric.\")\r\n assert_that(is.numeric(df[[to_str]]),\r\n msg = \"`to` must be numeric.\")\r\n assert_that(is.numeric(df[[x_str]]),\r\n msg = \"`x` must be numeric.\")\r\n assert_that(is.numeric(df[[y_str]]),\r\n msg = \"`y` must be numeric.\")\r\n assert_that(is.numeric(df[[z_str]]),\r\n msg = \"`z` must be numeric.\")\r\n # 'max_dist' is positive numeric scalar > 0.\r\n assert_that(is.scalar(max_dist))\r\n assert_that(max_dist > 0, msg = \"`max_dist` must be > 0\")\r\n # 'min_samp' is positive whole number scalar >= 1.\r\n assert_that(is.scalar(min_samp))\r\n assert_that(\r\n (function(x, tol = .Machine$double.eps^0.5) abs(x - round(x)) < tol)\r\n (min_samp),\r\n msg = \"`min_samp` must be a whole number\")\r\n assert_that(min_samp >= 1, msg = \"`min_samp` must be >= 1\")\r\n\r\n all_holes <- sort(unique(df[[bhid_str]]))\r\n sample_count <- nrow(df)\r\n cnt <- 0\r\n\r\n for (dom in 1:ncol(pairs)) {\r\n # Reset for each domain pairing.\r\n counti <- 0\r\n countj <- 0\r\n disti <- rep(NA_real_, sample_count)\r\n valuei <- rep(NA_real_, sample_count)\r\n distj <- rep(NA_real_, sample_count)\r\n valuej <- rep(NA_real_, sample_count)\r\n for (hole in 1:length(all_holes)) {\r\n samples <- df[df[[bhid_str]] == all_holes[hole],]\r\n samples <- samples[order(samples[[from_str]], samples[[to_str]]),]\r\n count_samples <- nrow(samples)\r\n # Make sure at least 2 samples in the drillhole.\r\n if(count_samples < 2) next\r\n for (sample in 2:count_samples) {\r\n this_samp <- samples[sample,]\r\n last_samp <- samples[sample - 1,]\r\n if (this_samp[[domain_str]] == pairs[2, dom] &\r\n last_samp[[domain_str]] == pairs[1, dom]) {\r\n xc <- (this_samp[[x_str]] + last_samp[[x_str]]) * 0.5\r\n yc <- (this_samp[[y_str]] + last_samp[[y_str]]) * 0.5\r\n zc <- (this_samp[[z_str]] + last_samp[[z_str]]) * 0.5\r\n for (consamp in (sample - 1):1) {\r\n con_samp <- samples[consamp,]\r\n if (con_samp[[domain_str]] == pairs[1, dom]) {\r\n d <-\r\n sqrt(\r\n (con_samp[[x_str]] - xc)^2 *\r\n (con_samp[[y_str]] - yc)^2 *\r\n (con_samp[[z_str]] - zc)^2\r\n )\r\n if (d <= max_dist) {\r\n counti <- counti + 1\r\n disti[counti] <- d\r\n valuei[counti] <- con_samp[[grade_str]]\r\n }\r\n }\r\n }\r\n for (consamp in sample:count_samples) {\r\n con_samp <- samples[consamp,]\r\n if (con_samp[[domain_str]] == pairs[2, dom]) {\r\n d <-\r\n sqrt(\r\n (con_samp[[x_str]] - xc)^2 *\r\n (con_samp[[y_str]] - yc)^2 *\r\n (con_samp[[z_str]] - zc)^2\r\n )\r\n if (d <= max_dist) {\r\n countj <- countj + 1\r\n distj[countj] <- d\r\n valuej[countj] <- con_samp[[grade_str]]\r\n }\r\n }\r\n }\r\n }\r\n if (this_samp[[domain_str]] == pairs[1, dom] &\r\n last_samp[[domain_str]] == pairs[2, dom]) {\r\n xc <- (this_samp[[x_str]] + last_samp[[x_str]]) * 0.5\r\n yc <- (this_samp[[y_str]] + last_samp[[y_str]]) * 0.5\r\n zc <- (this_samp[[z_str]] + last_samp[[z_str]]) * 0.5\r\n for (consamp in (sample - 1):1) {\r\n con_samp <- samples[consamp,]\r\n if (con_samp[[domain_str]] == pairs[2, dom]) {\r\n d <-\r\n sqrt(\r\n (con_samp[[x_str]] - xc)^2 *\r\n (con_samp[[y_str]] - yc)^2 *\r\n (con_samp[[z_str]] - zc)^2\r\n )\r\n if (d <= max_dist) {\r\n countj <- countj + 1\r\n distj[countj] <- d\r\n valuej[countj] <- con_samp[[grade_str]]\r\n }\r\n }\r\n }\r\n for (consamp in sample:count_samples) {\r\n con_samp <- samples[consamp,]\r\n if (con_samp[[domain_str]] == pairs[1, dom]) {\r\n d <-\r\n sqrt(\r\n (con_samp[[x_str]] - xc)^2 *\r\n (con_samp[[y_str]] - yc)^2 *\r\n (con_samp[[z_str]] - zc)^2\r\n )\r\n if (d <= max_dist) {\r\n counti <- counti + 1\r\n disti[counti] <- d\r\n valuei[counti] <- con_samp[[grade_str]]\r\n }\r\n }\r\n }\r\n }\r\n }\r\n }\r\n # Skip to next if not enough samples.\r\n if(counti < min_samp & countj < min_samp) next\r\n # Build the detailed dataframe.\r\n cnt <- cnt + 1\r\n tempdatai <- data.frame(dist = -disti, value = valuei)\r\n tempdatai[,\"domain\"] <- pairs[1, dom]\r\n tempdataj <- data.frame(dist = distj, value = valuej)\r\n tempdataj[,\"domain\"] <- pairs[2, dom]\r\n tempdata <- na.omit(rbind(tempdatai, tempdataj))\r\n # Create a contact label with the total number of samples.\r\n ni <- nrow(tempdata[tempdata[[\"domain\"]] == pairs[1, dom], ])\r\n nj <- nrow(tempdata[tempdata[[\"domain\"]] == pairs[2, dom], ])\r\n tempdata[, \"contact\"] <-\r\n paste0(\r\n pairs[1, dom], \"(\", ni, \"):\", pairs[2, dom], \"(\", nj, \")\"\r\n )\r\n if(cnt == 1) {\r\n cdata_detail <- tempdata\r\n } else {\r\n cdata_detail <- rbind(cdata_detail, tempdata)\r\n }\r\n }\r\n\r\n cdata_detail <- cdata_detail[,c(\"contact\", \"domain\", \"dist\", \"value\")]\r\n\r\n # Create summary data.\r\n cdata_summary <- cdata_detail %>%\r\n group_by(.data$contact, .data$domain, bin = cut(.data$dist, seq(-max_dist, max_dist))) %>%\r\n summarise(value = mean(.data$value, na.rm = TRUE)) %>%\r\n mutate(dist = interval_mid(.data$bin, 1)) %>%\r\n select(-.data$bin)\r\n\r\n return(list(detail = cdata_detail, summary = cdata_summary))\r\n}\r\n\r\n#' Produce Basic Contact Analysis Plots.\r\n#'\r\n#' \\code{contact_plot} produces a minimally formatted contact analysis plot\r\n#' facetted by domain using \\code{\\link{ggplot2}}. The input data is created by\r\n#' \\code{\\link{contact_data}}. Additonal formatting can be applied using\r\n#' \\code{\\link{ggplot2}} functions (see example).\r\n#'\r\n#' @param data List of data frames created by \\code{\\link{contact_data}} with\r\n#' 'detail' and 'summary' contact data.\r\n#'\r\n#' @return A \\code{\\link{ggplot2}} plot object.\r\n#' @export\r\n#' @importFrom ggplot2 aes ggplot geom_smooth geom_line geom_vline facet_wrap\r\n#' @importFrom rlang .data\r\n#' @examples\r\n#' library(ggplot2)\r\n#' cdata <- contact_data(dholes, grade)\r\n#' p <- contact_plot(cdata)\r\n#' p +\r\n#' labs(x = \"Distance (m)\", y = \"Mean grade (g/t)\") +\r\n#' theme_bw()\r\ncontact_plot <- function(data) {\r\n ggplot() +\r\n geom_smooth(\r\n data = data$detail,\r\n aes(x = .data$dist, y = .data$value, group = .data$domain),\r\n method = \"lm\",\r\n linetype = \"dashed\",\r\n colour = \"black\",\r\n fill = \"grey75\",\r\n alpha = 0.5,\r\n size = 0.25\r\n ) +\r\n geom_line(\r\n data = data$summary,\r\n aes(.data$dist, .data$value, group = .data$domain),\r\n size = 0.25, colour = \"black\"\r\n ) +\r\n geom_vline(xintercept = 0, colour = \"black\") +\r\n facet_wrap(~contact, scales = \"free_y\")\r\n}\r\n", "meta": {"hexsha": "afdefe11c15347a61e17e2cfcfe5fc052019b508", "size": 12304, "ext": "r", "lang": "R", "max_stars_repo_path": "R/contact-analysis.r", "max_stars_repo_name": "truemoid/contactr", "max_stars_repo_head_hexsha": "16df43c224d01b77f4ecef637ad07c3d80bc1b1b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/contact-analysis.r", "max_issues_repo_name": "truemoid/contactr", "max_issues_repo_head_hexsha": "16df43c224d01b77f4ecef637ad07c3d80bc1b1b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2018-10-22T17:30:18.000Z", "max_issues_repo_issues_event_max_datetime": "2018-10-22T17:30:18.000Z", "max_forks_repo_path": "R/contact-analysis.r", "max_forks_repo_name": "truemoid/contactr", "max_forks_repo_head_hexsha": "16df43c224d01b77f4ecef637ad07c3d80bc1b1b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.7417218543, "max_line_length": 95, "alphanum_fraction": 0.5826560468, "num_tokens": 3382, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6477982179521103, "lm_q2_score": 0.5813030906443134, "lm_q1q2_score": 0.3765671062094403}} {"text": "# --------------------------------------------------------------------------------------\n# Programmer: Jason Thorpe\n# Date 03/17/2011\n# Language: R (Version 2.12.0)\n# Purpose: \n# Comments: \n# --------------------------------------------------------------------------------------\n\n#' Estimate the PEB parameters\n#'\n#' Estimate the PEB parameters from a set of marker values (x) from individuals\n#'\n#' @export\n#' @param x observations of the for the variable of intereset\n#'\n#' @param id a 'factor' with identifiers for the individuals who contributed \n#' the observations in \\code{x}\n#'\n#' @param method Either 'ICC1' or 'iterative' (matched via match.arg). \n#' If method == 'ICC1' (default) multilevel::ICC1 is used to estimate the \n#' within and between group variation. Otherwise an iterative approach is used.\n#'\n#' @param iterations The number of iterations for estimating the tau \n#' squared parameter (and it's error variance) (default = 2)\n#'\n#' @param conf.level The width of the confidence interval for sigma-squared \n#' and tau-squared \n#'\n#' @family peb\n#' @return a list with the following values:\n#' s2: sigma quared\n#' s2.ev: the error variance for sigma squared\n#' t2: tau squared\n#' t2.ev: the error variance for tau squared\n#' mu: mu \n#' mu.ev: the error variance for mu\n#' m: the number of individuals contributing to the estimates\n#' N: the nubmer so observations contributing to the estimates\n#' mu.ci: confidence interval for mu\n#' t2.ci: confidence interval for tau squared\n#' s2.ci: confidence interval for sigma squared\n#' nstar: an average sample size for use in calcualing the CI for tau sauqred\n#'\n#' @examples\n#' n = 10\n#' m = 200\n#' PEBparams(x = rnorm(m*n) + rep(rnorm(m),each=n), id=gl(m,n,m*n))\n#'\n#' @importFrom multilevel ICC1\n\nPEBparams <- function(x,\n\t\t\t\t\t id,\n\t\t\t\t\t method='ICC1',\n\t\t\t\t\t iterations =2 ,\n\t\t\t\t\t conf.level = 0.9,\n\t\t\t\t\t verbose=FALSE){\n\n\tmethod = match.arg(method,c('ICC1','iterative'))\n\tif(method == 'ICC1' && !missing(iterations))\n\t\tstop(\"parameter 'iterations' is not used when method == 'ICC1'\")\n\n\tstopifnot(all(is.finite(x)))\n\tif(!inherits(id,'factor'))\n\t\tstop(\"parameter 'id' must be a factor\")\n\tif(! all(levels(id) %in% id)){\n\t\twarning(paste(\"unused factor levels in 'id':\",\n\t\t\t\t\t paste(levels(id)[!levels(id) %in% id],\n\t\t\t\t\t\t\tcollapse = ', ')))\n\t\tid <- factor(as.character(id))\n\t}\n\n\n\tN <- length(id)\n\tm <- length(levels(id))\n\n\tif(method == 'ICC1'){\n\t\ttryCatch({\n\t\t\tAOV = aov(formula(x~id))\n\t\t},error=function(err){\n\t\t\tstop('Internal call to `aov()` failed with error message: \"%s\". \\n\\nSuggest using: PEBparams( ... , method=\"iterative\")')\n\t\t})\n\t\t(B1 = multilevel::ICC1(AOV))\n\t\tV <- var(x)\n\t\tout <- list(s2 = (1-B1) * V,\n\t\t\t\t\t\t t2 = B1 * V,\n\t\t\t\t\t\t mu = mean(x),\n\t\t\t\t\t\t m = m,\n\t\t\t\t\t\t N = N,\n\t\t\t\t\t\t method=method)\n\t\tclass(out) <- c('PEBparams','list')\n\t\treturn(out)\n\n\t}else{#(method == )\n\t\t# --------------------------------------------------\n\t\t# part 1: non-iterative calculations\n\t\t# --------------------------------------------------\n\n\t\t#calcualte various constants\t\n\t\tnresults <- tapply(id,id,length) # results per person\n\t\tybari <- tapply(x,id,mean)\n\n\t\t#############################################\n\t\t# estiamte sigma^2\n\t\t#############################################\n\t\ts2i \t<- tapply(x,id,var)\n#-- \t\tif(!all(is.na(s2i) == (nresults == 1)))\n#-- \t\t\tbrowser()\n\n\t\tstopifnot(is.na(s2i) == (nresults == 1))\n\n\t\t#relative error variances of \n\t\ts2i_weights\t<- (nresults - 1) / 2\n\t\tstopifnot( (s2i_weights ==0) == is.na(s2i))\n\n\t\ts2 <- sum((s2i_weights[!is.na(s2i)])*(s2i[!is.na(s2i)])) / sum(s2i_weights[!is.na(s2i)])\n\t\ts2ev <- 2*(s2^2)/(N - m)\n\n\t\trm(s2i,s2i_weights)\n\n\t\t# --------------------------------------------------\n\t\t# --------------------------------------------------\n\t\t# part 2: iterative calculations of mu and Tau^2\n\t\t# --------------------------------------------------\n\t\t# --------------------------------------------------\n\n\t\t# ------------------------------\n\t\t# part 2a: fixed parameters for the iterative processes\n\t\t# ------------------------------\n\t\ttr <- table(nresults)\n\t\tuk <- as.numeric(names(tr[tr>1]))\n\t\trm(tr)\n\n\t\t# estimates of the t2k's \n\t\tt2k <- numeric(0)\n\t\tfor(k in uk)\n\t\t\tt2k \t<- c(t2k, var(ybari[nresults == k] ) - (s2/k) )\n\n\t\t# initialize the variables involved in the iterative process\n\t\tt2kev_list <- list()\n\t\tt2ev <- muev <- t2 <- numeric(0)\n\n\t\t# ------------------------------\n\t\t# part 2b: initial estiamte of EV(T_k^2) from the tk's\n\t\t# ------------------------------\n\t\t# Next, estimate the error variances which DOES depend on the estimate for tau^2\n\t\t# We use the unweighted average of the t2k's because the t2k's are unbaiased.\n\t\t# We cannot weight them according to their value because then underestimates \n\t\t# become overweitghted and underestimated become underweighted and the result \n\t\t# is a biased estimate of t2k and of it's error variance. we do however weight \n\t\t# them according to their m_k's becaue there is not bias there.\n\n\t\tt2kev_temp <- numeric(0)#initialization\n\t\tfor(k in uk){# this would be more efficient with an apply stmt.\n\t\t\tm_k \t\t<- sum(nresults == k)\n\t\t\t#in the alternate version we estimate all the t2k's then estimate the t2kev's\n\t\t\t#this estimate DOES depend on the estimate for tau^2\n\t\t\tt2kev_temp \t <- c(t2kev_temp, \n\t\t\t\t\t\t\t\t\t2*((mean(t2k) + s2/k)^2) / (m_k - 1) + (s2ev/(k^2))\n\t\t\t\t\t\t\t\t\t)\n\t\t}\n\t\tt2kev_list <- list(t2kev_temp)\n\t\trm(k,m_k)\n\n\t\t# ------------------------------\n\t\t# part 2c: iterative re-estimation of Tau2 and mu\n\t\t# ------------------------------\n\t\tt2 <- mu <- t2ev <- muev <- numeric(0)\n\t\t# This function nested for lexical scoping \n\t\tt2_mu <- function(){\n\t\t\t#re-estimate t2 using the latest t2kev estimates\n\t\t\tt2new <- sum((1/(t2kev_list[[j]]))*(t2k))/sum(1/(t2kev_list[[j]]))\n\n\t\t\t#re-estimate t2_ev using the latest t2 estimates\n\t\t\tt2kev_temp <- numeric(0) #initialize\n\t\t\tfor(k in uk){\n\t\t\t\tm_k \t\t<- sum(nresults == k)\n\t\t\t\tt2kev_temp \t<- c(t2kev_temp, \n\t\t\t\t\t\t\t\t\t2*((t2new + s2/k)^2) / (m_k - 1) + (s2ev/(k^2)))\n\t\t\t}\n\t\t\tt2kev_list <<- c(t2kev_list,list(t2kev_temp))\n\n\t\t\t#############################################\n\t\t\t# estimate mu (which depends on the estimate for tau^2)\n\t\t\t#############################################\n\t\t\tybari_weights\t<- 1/(t2new + (s2/nresults))\n\t\t\tbn <- (t2new)/((t2new) + (s2/nresults))\n\n\t\t\t# extend the lists of estmates\n\t\t\tt2 <<- c(t2,t2new )\n\t\t\tmu <<- c(mu, sum(ybari_weights*ybari) / sum(ybari_weights))\n\n\t\t\tt2ev <<- c(t2ev, 1/sum(1/t2kev_temp)) #estimate t2ev from the new t2kev's\n\t\t\tmuev <<- c(muev, (t2new)/sum(bn))\n\n\t\t}\n\n\t\tstopifnot(iterations>0)\n\n\t\tprobs <- c(((1-conf.level)/2),1-((1-conf.level)/2)) # probabilities for the CI\n\n\t\tfor(j in 1:iterations){\n\t\t\tt2_mu()\n\t\t\tif(verbose){\n\t\t\t\tnstar <- ((m-length(uk))/sqrt((t2ev[j]) / (2*((t2[j])^2)/(m-length(uk)))))\n\t\t\t\tcat('iteration:',j,\n\t\t\t\t\t'| Tau Squared CI width: ',\n\t\t\t\t\tformat(diff((t2[j]*(nstar))/qchisq(p=probs[2:1],df = nstar)),8),\n\t\t\t\t\t'| Mu CI width: ',\n\t\t\t\t\tformat(diff(mu[j] + sqrt(muev[j])*qnorm(p=probs)),8),'\\n')\n\t\t\t}\n\t\t}\n\n\t\t#############################################\n\t\t# return the estimates\n\t\t#############################################\n\n\t\tnstar <- ((m-length(uk))/sqrt((t2ev[j]) / (2*((t2[j])^2)/(m-length(uk)))))\n\n\t\tout <- list(s2 = s2,\n\t\t\t\t s2.ev = s2ev,\n\t\t\t\t t2 = t2[iterations],\n\t\t\t\t t2.ev = t2ev[iterations],\n\t\t\t\t mu = mu[iterations],\n\t\t\t\t mu.ev = muev[iterations],\n\t\t\t\t m = m,\n\t\t\t\t N = N,\n\t\t\t\t mu.ci = mu[iterations] + sqrt(muev[iterations])*qnorm(p=probs),\n\t\t\t\t t2.ci = t2[iterations]*qchisq(p=probs[2:1],df = nstar)/nstar,\n\t\t\t\t s2.ci = s2*qchisq(p=probs[2:1],df = N-m )/(N-m),\n\t\t\t\t nstar = nstar,\n\t\t\t\t conf.level = conf.level, \n\t\t\t\t method=method)\n\t\tclass(out) <- c('PEBparams','list')\n\t\treturn(out)\n\n\t}\n\n}\n\n\n#' @export\nprint.PEBparams <- function(x,digits=4){\n\tcat('mu:',format(x$mu[1],digits=digits))\n\tif(x$method == 'iterative')\n\t\tcat(' [',format(x$mu.ci[1],digits=digits),\n\t\t \t',',format(x$mu.ci[2],digits=digits),']')\n\tcat('\\n')\n\n\tcat('sigma^2:',format(x$s2[1],digits=digits))\n\tif(x$method == 'iterative')\n\t\tcat(' [',format(x$s2.ci[1],digits=digits),\n\t\t \t',',format(x$s2.ci[2],digits=digits),']')\n\tcat('\\n')\n\n\tcat('tau^2:',format(x$t2[1],digits=digits))\n\tif(x$method == 'iterative')\n\t\tcat(' [',format(x$t2.ci[1],digits=digits),\n\t\t \t',',format(x$t2.ci[2],digits=digits),']')\n\tcat('\\n')\n\n\tcat('Calculated using',x$N,'observations, from ',x$m, 'inidividuals.\\n',sep = ' ')\n\tif(x$method == 'iterative')\n\t\tcat('([x,y] indicates the ',format(100*x$conf.level,2),'% confidence interval for each parameter)\\n',sep = '')\n}\n\n\nqpeb.alt<-function(p,...,n,ybar,conf.level,details=FALSE) {\n\twith(pebVarArgs(...),{\n\t\t\t\tbn <- bn(n)\n\t\t\t\tsd_n <<- sqrt(sigma + (tau*(1-bn)))\n\t\t\t\tmu_n <<- mu*(1-bn) + ybar*bn\n\t\t\t\t})\n\tif(length(p) == 1)\n\t\treturn(qnorm(p,mean = mu_n,sd=sd_n))\n\tout <- matrix(NA,length(n),length(p))\n\tfor(i in 1:length(p))\n\t\tout[,i] <- qnorm(p[i],mean = mu_n,sd=sd_n)\n\tdimnames(out) <- list(if(!is.null(names(n)))names(N) else seq(length(n)),\n\t\t\t\t\t\t paste('p =',p))\n\treturn(out)\n}\n\n", "meta": {"hexsha": "074e929f8594e6bb00a8714aa3b07e5a6e8dc3cb", "size": 9028, "ext": "r", "lang": "R", "max_stars_repo_path": "R/PEB-parameters.r", "max_stars_repo_name": "jdthorpe/PEB", "max_stars_repo_head_hexsha": "23c0f8d6a6e81d9d2e8e3a74c40027b74e97a97c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/PEB-parameters.r", "max_issues_repo_name": "jdthorpe/PEB", "max_issues_repo_head_hexsha": "23c0f8d6a6e81d9d2e8e3a74c40027b74e97a97c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/PEB-parameters.r", "max_forks_repo_name": "jdthorpe/PEB", "max_forks_repo_head_hexsha": "23c0f8d6a6e81d9d2e8e3a74c40027b74e97a97c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.9010600707, "max_line_length": 125, "alphanum_fraction": 0.5476295968, "num_tokens": 2822, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548782017745, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.3761544232526937}} {"text": "#!/usr/bin/env Rscript\n\n#########################################################################################\n# __ o __ __ __ |__ __ #\n# |__) | | ' (__( | ) | ) (__( # \n# | #\n# #\n# File: 2logeB10.r (Rscript) #\n# VERSION=\"v1.2\" #\n# Author: Justin C. Bagley #\n# Date: Created by Justin Bagley on Fri, 19 Aug 2016 00:23:07 -0300. #\n# Last update: March 6, 2019 #\n# Copyright (c) 2016-2021 Justin C. Bagley. All rights reserved. #\n# Please report bugs to . #\n# #\n# Description: #\n# #\n#########################################################################################\n\n####################################### START ###########################################\n\ncat('INFO | $(date) |----------------------------------------------------------------\\n')\ncat('INFO | $(date) | 2logeB10.r, v1.2 March 2019 (part of PIrANHA v0.3a2) \\n')\ncat('INFO | $(date) | Copyright (c) 2016-2021 Justin C. Bagley. All rights reserved. \\n')\ncat('INFO | $(date) |----------------------------------------------------------------\\n')\n\n# Load needed library, R code, or package stuff. Install package if not present.\n#source(\"2logeB10.R\", chdir = TRUE)\npackages <- c(\"psych\")\nif (length(setdiff(packages, rownames(installed.packages()))) > 0) {\n install.packages(setdiff(packages, rownames(installed.packages())))\n}\n\nlibrary(psych)\n\n########### Read data and output to file\n# Read in the data, output from STEP #1 of MLEResultsProc.sh script.\ndata <- read.table(file=\"MLE.output.txt\", header=TRUE, sep=\"\\t\")\n\nsink(\"2logeB10.output.txt\")\ncat(\"############################# MARGINAL-LIKELIHOOD ESTIMATES ##############################\\n\")\ndata\ncat(\"\\n \\n\")\nsink()\n\n\n########### Get marginal likelihood values and calculate 2loge B10 Bayes factors (2loge(B10))\n# Raw path-sampling (PS) log-marginal likelihood estimates:\nPS_vec <- data[,2]\nPS_vec\n\n# Raw stepping-stone (SS) sampling log-marginal likelihood estimates:\nSS_vec <- data[,3]\nSS_vec\n\n# Make matrix of zeros for correcting signs of each BF below:\nif(length(PS_vec) > 0){\n\tzeros <- c()\n\tfor(i in 1:length(PS_vec)){\n\t\tzeros[i] <- 0\n\t}\n}\nif(length(SS_vec) > 0){\n\tzeros <- c()\n\tfor(i in 1:length(SS_vec)){\n\t\tzeros[i] <- 0\n\t}\n}\nzeros\nzeros_mat <- 2*(outer(zeros, zeros, '-'))\nzeros_mat\n\n# Matrix of 2loge BFs calculated from PS log-marginal likelihood estimates:\nPS_2logeB10 = 2*(outer(PS_vec, PS_vec, '-'))\nPS_2logeB10 <- zeros_mat - PS_2logeB10\n\n# Matrix of 2loge BFs calculated from SS log-marginal likelihood estimates:\nSS_2logeB10 = 2*(outer(SS_vec, SS_vec, '-'))\nSS_2logeB10 <- zeros_mat - SS_2logeB10\n\n\n########### Summarize results and output to file\n# Use psych package function to combine the resulting matrices into a single, nice\n# output table with Bayes factors (BF) from PS MLEs below the diagonal and BFs from SS \n# MLEs above the diagonal:\nsink(\"2logeB10.output.txt\", append=TRUE)\ncat(\"##################################### BAYES FACTORS ######################################\nBelow diagonal: 2loge(B10) values based on path sampling (PS) log-marginal likelihood estimates\nAbove diagonal: 2loge(B10) values based on stepping-stone (SS) log-marginal likelihood estimates\\n\")\nif(sum(PS_vec) == '0'){ \n\tBF_mat <- lowerUpper(PS_2logeB10, SS_2logeB10, diff=FALSE)\n\tBF_mat[lower.tri(BF_mat)] <- NA\n\trownames(BF_mat) <- 1:length(PS_vec)\n\tcolnames(BF_mat) <- 1:length(PS_vec)\n\tBF_mat\n}\nif(sum(SS_vec) == '0'){ \n\tBF_mat <- lowerUpper(PS_2logeB10, SS_2logeB10, diff=FALSE)\n\tBF_mat[upper.tri(BF_mat)] <- NA\n\trownames(BF_mat) <- 1:length(PS_vec)\n\tcolnames(BF_mat) <- 1:length(PS_vec)\n\tBF_mat\n}\nif( (sum(PS_vec) != '0') & (sum(SS_vec) != '0') ){ \n\tBF_mat <- lowerUpper(PS_2logeB10, SS_2logeB10, diff=FALSE)\n\trownames(BF_mat) <- 1:length(PS_vec)\n\tcolnames(BF_mat) <- 1:length(PS_vec)\n\tBF_mat\n}\ncat(\"\\n \\n\")\nsink()\n\n# Next, report PS MLE BFs below the diagonal and report the difference between PS- and \n# SS-based BF matrices, placing the results in the above-the-diagonal entries. However, \n# we only report the differences if both PS- and SS-based BFs could be calculated; otherwise,\n# we do not report the differences at all! If PS MLEs or SS MLEs were missing in the input \n# (as is usually the case for BEAST2 MLE runs), then either PS_vec or SS_vec would be filled \n# with zeros. If we computed differences in such a case, then we would be left with a square \n# matrix in which the above-diagonal elements were the same as the below-diagonal elements, \n# only with the opposite sign. Such a table would be equivalent to the Bayes factors table \n# already written to file in the step above, and thus would be unnecessary.\n\nsink(\"2logeB10.output.txt\", append=TRUE)\nif( (sum(PS_vec) != '0') & (sum(SS_vec) != '0') ){ \ncat(\"################################ BAYES FACTOR DIFFERENCES ################################\nBelow diagonal: 2loge(B10) values based on path sampling (PS) log-marginal likelihood estimates\nAbove diagonal: differences between PS- and SS-based BF values\\n\")\n\tBF_diff_mat <- lowerUpper(PS_2logeB10, SS_2logeB10, diff=TRUE)\n\trownames(BF_diff_mat) <- 1:length(PS_vec)\n\tcolnames(BF_diff_mat) <- 1:length(PS_vec)\n\tBF_diff_mat\n}\ncat(\"\\n \\n\")\nsink()\n\n\n######################################## END ############################################\n", "meta": {"hexsha": "fc2e32900e207dac7343a55ab85db0923ad0964c", "size": 6143, "ext": "r", "lang": "R", "max_stars_repo_path": "bin/2logeB10.r", "max_stars_repo_name": "justincbagley/PAmPAS", "max_stars_repo_head_hexsha": "4a27375170b2c01fe30fd7460ec7b7313f2cd8c0", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 10, "max_stars_repo_stars_event_min_datetime": "2019-07-26T19:17:42.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-08T21:12:26.000Z", "max_issues_repo_path": "bin/2logeB10.r", "max_issues_repo_name": "justincbagley/PAmPAS", "max_issues_repo_head_hexsha": "4a27375170b2c01fe30fd7460ec7b7313f2cd8c0", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2019-07-30T02:49:38.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-18T13:04:55.000Z", "max_forks_repo_path": "bin/2logeB10.r", "max_forks_repo_name": "justincbagley/PAmPAS", "max_forks_repo_head_hexsha": "4a27375170b2c01fe30fd7460ec7b7313f2cd8c0", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2019-07-31T23:16:29.000Z", "max_forks_repo_forks_event_max_datetime": "2021-01-27T07:17:53.000Z", "avg_line_length": 44.5144927536, "max_line_length": 100, "alphanum_fraction": 0.5196158229, "num_tokens": 1521, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548511303338, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.37615440761906216}} {"text": "#' Data Fit Assessment\n#' \n#' Calculates \\eqn{R^2} values for correct and incorrect mean reaction times and RMSE values\n#' for the proportions of correct answers per reaction times cuantiles. \n#' @export\n#' @param experim_dat Experimental data in the form produced by \\code{\\link{experimental_data_processing}}.\n#' @param experim_dat Simulated data in the form produced by \\code{\\link{simulDat}}.\n#' @param model_name Optional name for the model to distinguish to which data/model the\n#' function was applied to. Default is 'NAME_UNDEFINED'.\n#' \n#' @return Prints a table with RMSE and \\eqn{R^2} values.\nfit_quality <- function(experim_dat, simul_dat, model_name='NAME_UNDEFINED'){\n \n experim_dat$cond <- \"Data\"\n \n dat <- rbind(experim_dat, simul_dat$data)\n \n ##########\n nbins <- 6\n \n dat_cuants <- quantile(experim_dat$rt, probs = seq(0, 1, length.out = nbins+1)) \n dat_cuants[length(dat_cuants)] <- tail(dat_cuants, n=1)+0.1\n \n sim_cuants <- quantile(simul_dat$data$rt, probs = seq(0, 1, length.out = nbins+1)) \n sim_cuants[length(sim_cuants)] <- tail(sim_cuants, n=1)+0.1\n \n dat$cuants[dat$cond=='Data'] <- experim_dat %>%\n select(-cond) %>%\n split(experim_dat$suj) %>% map(c('rt')) %>%\n map(function(x) {cut(x, breaks = dat_cuants, right=FALSE, na.rm = TRUE)}) %>%\n as_tibble() %>% tidyr::pivot_longer(cols=everything(), names_to = 'variable', values_to = 'value') %>% .$value\n \n dat$cuants[dat$cond=='Sim'] <- simul_dat$data %>%\n split(simul_dat$data$suj) %>% map(c('rt')) %>%\n map(function(x) {cut(x, breaks = sim_cuants, right=FALSE, na.rm = TRUE)}) %>%\n as_tibble() %>% tidyr::pivot_longer(cols=everything(), names_to = 'variable', values_to = 'value') %>% .$value\n \n dat$cuants <- unlist(dat$cuants) %>% as.factor()\n dat$cor <- as.numeric(levels(dat$cor))[dat$cor]\n #########\n \n a <- dat %>% group_by(cond, cuants) %>%\n dplyr::summarise(mean = mean(cor)) %>% \n spread(cond,mean) %>%\n select(-cuants) %>%\n rmse()\n \n \n b <- dat %>% \n group_by(suj, cond) %>% \n dplyr::summarize(mean_rt = mean(rt)) %>%\n spread(cond, mean_rt) %>%\n ungroup() %>%\n dplyr::summarise(rmse = rmse(.)) %>%\n pull()\n \n c <- dat %>% \n group_by(suj, cond) %>% \n dplyr::summarize(mean_rt = mean(rt)) %>%\n spread(cond, mean_rt) %>%\n ungroup() %>%\n dplyr::summarise(r2 = summary(lm(data=., Data~Sim))$adj.r.squared) %>%\n pull() \n \n d <- dat %>% group_by(cor, cond, suj) %>%\n dplyr::summarise(mean = mean(rt)) %>% \n ungroup() %>%\n spread(cond,mean) %>%\n nest(-cor) %>%\n mutate(data = map(data, ~ rmse(as.data.frame(.x)))) %>%\n mutate(data = unlist(data)) %>%\n pull(data)\n \n e <- dat %>% group_by(cor, cond, suj) %>%\n dplyr::summarise(mean = mean(rt)) %>% \n ungroup() %>%\n spread(cond,mean) %>%\n nest(-cor) %>%\n mutate(data = map(data, ~ summary(lm(data=as.data.frame(.x), Data~Sim))$adj.r.squared)) %>%\n mutate(data = unlist(data)) %>%\n pull(data) \n \n stats <- list(\"RMSE (Correct answers per RT cuantiles)\" = a,\n \"RMSE (Overall Means of RTs aggr. by Subj.)\" = b,\n \"R2 (Overall Means of RTs aggr. by Subj.)\" = c,\n \"RMSE (For Incorrect Mean RTs aggr. by Subj.)\" = d[1],\n \"RMSE (For Correct Mean RTs aggr. by Subj.)\" = d[2], \n \"R2 (For Incorrect Mean RTs aggr. by Subj.)\" = e[1],\n \"R2 (For Correct Mean RTs aggr. by Subj.)\" = e[2]\n )\n \n print(data.frame(stats=unlist(stats)))\n \n}", "meta": {"hexsha": "8a9d7eee3d8891fac7d034c7eca647265f202bc6", "size": 3733, "ext": "r", "lang": "R", "max_stars_repo_path": "R/fit_quality.r", "max_stars_repo_name": "Seneketh/StanDDM", "max_stars_repo_head_hexsha": "994c96fb00e6719f5e22c130e4844c62f14fc928", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 28, "max_stars_repo_stars_event_min_datetime": "2019-06-04T13:56:15.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-11T15:53:37.000Z", "max_issues_repo_path": "R/fit_quality.r", "max_issues_repo_name": "Seneketh/StanDDM", "max_issues_repo_head_hexsha": "994c96fb00e6719f5e22c130e4844c62f14fc928", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 3, "max_issues_repo_issues_event_min_datetime": "2019-07-02T06:45:23.000Z", "max_issues_repo_issues_event_max_datetime": "2021-06-28T20:36:29.000Z", "max_forks_repo_path": "R/fit_quality.r", "max_forks_repo_name": "Seneketh/StanDDM", "max_forks_repo_head_hexsha": "994c96fb00e6719f5e22c130e4844c62f14fc928", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-06-23T01:52:34.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-10T12:36:06.000Z", "avg_line_length": 39.7127659574, "max_line_length": 119, "alphanum_fraction": 0.5563889633, "num_tokens": 1117, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548511303338, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.37615440761906216}} {"text": "BoundModwpt<- function(x, wf=\"la8\", n.levels=4, oldtargets)\n{\n \n N <- length(x); storage.mode(N) <- \"integer\"\n J <- n.levels\n if(2^J > N) stop(\"Too many depth levels in the wavelet transform\")\n \n dict <- wave.filter(wf)\n L <- dict$length\n storage.mode(L) <- \"integer\"\n ht <- dict$hpf/sqrt(2)\n storage.mode(ht) <- \"double\"\n gt <- dict$lpf/sqrt(2)\n storage.mode(gt) <- \"double\"\n \n targets=prepareTargets(oldtargets)#encoding targets using gray code\n \n y <- vector(\"list\", sum(2^(1:J)))\n yn <- length(y)\n crystals1 <- rep(1:J, 2^(1:J))\n crystals2 <- unlist(apply(as.matrix(2^(1:J) - 1), 1, seq, from=0))\n names(y) <- paste(\"w\", crystals1, \".\", crystals2, sep=\"\")\n \n W <- numeric(N);V<- numeric(N)\n storage.mode(W) <- \"double\"; storage.mode(V)<- \"double\"\n for(j in 1:J) {\n index <- 0\n jj <- min((1:yn)[crystals1 == j])\n for(n in 0:(2^j / 2 - 1)) {\n index <- index + 1\n #should filter parent node j-1,n\n sc=shouldCompute(c(j-1,n),targets)\n if(sum(sc)>0){\n if(j > 1)\n x <- y[[(1:yn)[crystals1 == j-1][index]]]\n if(n %% 2 == 0) {\n z <- .C(\"pmodwpt\", as.double(x), N, as.integer(j),as.integer(2), L, ht, gt,\n W = W, V = V, PACKAGE=\"RHRV\")[8:9]\n y[[jj + 2*n + 1]] <- z$W\n y[[jj + 2*n]] <- z$V\n }\n else {\n z <- .C(\"pmodwpt\", as.double(x), N, as.integer(j),as.integer(2), L, ht, gt,\n W = W, V = V, PACKAGE=\"RHRV\")[8:9]\n y[[jj + 2*n]] <- z$W\n y[[jj + 2*n + 1 ]] <- z$V\n }\n }\n \n }\n }\n \n return(y)\n}\n\n\nshouldCompute2intCode<-function(sc){\n if (codeEquals(sc,c(1,0))){ intCode=0}\n if (codeEquals(sc,c(0,1))) { intCode=1}\n if (codeEquals(sc,c(1,1))){intCode=2}\n return (intCode)\n}\n\nprepareTargets <- function(targets){\n newTargets=list()\n numberTargets=length(targets)/2;\n for (n in 1:numberTargets){ \n newTargets[[n]]=getC(targets[[2*n-1]],targets[[2*n]])\n }\n return(newTargets)\n}\n\nshouldCompute <- function(node,targets){\n \n #compute should be c(0,0)(none), c(1,0)(left),c(0,1)(right), c(1,1) (both)\n compute=c(0,0)\n # node c(0,0) must be computed\n if (nodeEquals(node,c(0,0))){\n len=length(targets)\n for (j in 1:len){\n if (targets[[j]][1]==0){\n compute[[1]]=1;\n }else{\n compute[[2]]=1;\n }\n if (codeEquals(compute,c(1,1))) break \n }\n \n }else{\n len=length(targets)\n nodeCode=getC(node[[1]],node[[2]])\n codeLen=length(nodeCode)\n compute=c(0,0)\n for (j in 1:len){\n if (length(targets[[j]])>codeLen){\n equals=codeEquals(nodeCode,targets[[j]][1:codeLen])\n if (equals){\n ntc=nodeToCompute(targets[[j]][[codeLen+1]])\n compute=compute+ntc\n compute=compute/max(compute)## avoid (2,0) or (0,2)\n if (codeEquals(compute,c(1,1))) break\t\n \n }\n }\n }\n return (compute)\n }\n \n \n \n return(compute);\n}\n\n\nnodeToCompute<-function(number){\n if (number==1){##high pass filter\n return (c(0,1))\n }else{## low pass filter\n return (c(1,0))\n }\n}\n\ncodeEquals<-function(c1,c2){\n if (length(c1)!=length(c2))\n { \n return (FALSE)\n }else{\n return (prod(c1==c2)==1)\n }\t\n}\n\nnodeEquals<-function(n1,n2){\n return ((n1[1]==n2[1])&&(n1[2]==n2[2]));\n \n}\n", "meta": {"hexsha": "25b39dae92abb7a4a1b7a5bb089d82440c1fba50", "size": 3290, "ext": "r", "lang": "R", "max_stars_repo_path": "RHRV/BoundModwpt.r", "max_stars_repo_name": "med-material/ArduinoLoggerShinyApp", "max_stars_repo_head_hexsha": "6c80e9a8015946dbdba29087e35e487dcd4493eb", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "RHRV/BoundModwpt.r", "max_issues_repo_name": "med-material/ArduinoLoggerShinyApp", "max_issues_repo_head_hexsha": "6c80e9a8015946dbdba29087e35e487dcd4493eb", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 17, "max_issues_repo_issues_event_min_datetime": "2020-01-23T08:30:21.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T11:58:03.000Z", "max_forks_repo_path": "RHRV/BoundModwpt.r", "max_forks_repo_name": "med-material/ArduinoLoggerShinyApp", "max_forks_repo_head_hexsha": "6c80e9a8015946dbdba29087e35e487dcd4493eb", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-01-30T09:42:11.000Z", "max_forks_repo_forks_event_max_datetime": "2020-01-30T09:42:11.000Z", "avg_line_length": 24.1911764706, "max_line_length": 85, "alphanum_fraction": 0.526443769, "num_tokens": 1138, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.757794360334681, "lm_q2_score": 0.4960938294709195, "lm_q1q2_score": 0.37593710616989773}} {"text": "#' Creates a new ARTMAP network.\n#' \n#' This function creates a new ARTMAP network with the specified number\n#' features and classes. The network is created to expand the number of \n#' categories as needed. The vigilance parameter defaults to 0.75.\n#' The initial number of categories is set to 1. The maximum number\n#' of categories defaults to 100. The bias defaults to 0.000001, the\n#' number of epochs defaults to 100, and the learning rate defaults \n#' to 1.0 (fast-learning).\n#' @title ARTMAP_Create_Network\n#' @param numFeatures Number of features that the network expects of the input data. Must be a positive integer.\n#' @param numClasses Number of classes that exist for the supervisory signal. Must be a positive integer greater than 1.\n#' @param maxNumCategories Maximum number of categories that can be activated during the training process. Defaults to 1000.\n#' @param vigilance Vigilance parameter that defines the minimum similarity allowed between the input pattern and the weights. Defaults to 0.75.\n#' @param bias Constant that is used to differentiate between very similar category activation values. Defaults to 0.000001\n#' @param numEpochs Maximum number of training iterations allowed. Defaults to 100.\n#' @param learningRate Learning rate. Defaults to 1.\n#' @return Structure that holds all of the information for the network. It must be passed into both ARTMAP_LEARN() and \n#' ARTMAP_CLASSIFY(). The fields of this structure are numFeatures, numCategories, maxNumCategories, numClasses, weight \n#' (an initialized weight vector with the right dimensions), mapField (an initialized map field with the right dimensions), \n#' vigilance, bias, numEpochs, neededEpochs (the number of epochs needed in the last training) and learningRate.\n#' @export\nARTMAP_Create_Network=function(numFeatures, numClasses,\n maxNumCategories = 1000, vigilance=0.75, \n bias=0.000001, numEpochs=100, learningRate=1.0)\n{\n if(is.null(numFeatures) || is.null(numClasses))\n {\n stop('You must specify the number of features and the number of classes.');\n }\n \n # Check the ranges of the input parameters.\n numFeatures = round(numFeatures);\n if(numFeatures < 1)\n {\n stop('The number of features must be a positive integer.');\n }\n numClasses = round(numClasses);\n if(numClasses < 2)\n {\n stop('The number of classes must be a positive integer greater than 1.');\n }\n \n # Create and initialize the weight matrix.\n weight = matrix(1,0,numFeatures);\n \n # Create and initialize the map field.\n mapField = matrix(0,0,1);\n \n # Create the structure and return.\n artmap_network = list(\"numFeatures\"= numFeatures, \"numCategories\" = 0, \"maxNumCategories\" = maxNumCategories, \n \"numClasses\"=numClasses, \"weight\"=weight, \"mapField\"=mapField, \n \"vigilance\"=vigilance, \"bias\"=bias, \"numEpochs\"=numEpochs, \n \"neededEpochs\"=0,\"learningRate\"=learningRate);\n \n return(artmap_network);\n}", "meta": {"hexsha": "b707ade0789a2d53bd6abaf07d13a05bd2417876", "size": 3026, "ext": "r", "lang": "R", "max_stars_repo_path": "R/ARTMAP_Create_Network.r", "max_stars_repo_name": "gbaquer/fuzzyARTMAP", "max_stars_repo_head_hexsha": "dc5378a742673f5279d054e7cc3bd92d601235cc", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/ARTMAP_Create_Network.r", "max_issues_repo_name": "gbaquer/fuzzyARTMAP", "max_issues_repo_head_hexsha": "dc5378a742673f5279d054e7cc3bd92d601235cc", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/ARTMAP_Create_Network.r", "max_forks_repo_name": "gbaquer/fuzzyARTMAP", "max_forks_repo_head_hexsha": "dc5378a742673f5279d054e7cc3bd92d601235cc", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 53.0877192982, "max_line_length": 144, "alphanum_fraction": 0.7204230007, "num_tokens": 722, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.658417487156366, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.3752009507935019}} {"text": " E04MTJ Example Program Results\n\n++++++++++ Use the Primal-Dual algorithm ++++++++++\n\n ----------------------------------------------\n E04MT, Interior point method for LP problems\n ----------------------------------------------\n\n Original Problem Statistics\n\n Number of variables 7\n Number of constraints 7\n Free variables 0\n Number of nonzeros 41\n\n\n Presolved Problem Statistics\n\n Number of variables 13\n Number of constraints 7\n Free variables 0\n Number of nonzeros 47\n\n\n ------------------------------------------------------------------------------\n it| pobj | dobj | optim | feas | compl | mu | mcc | I\n ------------------------------------------------------------------------------\n 0 -7.86591E-02 1.71637E-02 1.27E+00 1.06E+00 8.89E-02 1.5E-01\n 1 5.74135E-03 -2.24369E-02 6.11E-16 1.75E-01 2.25E-02 2.8E-02 0\n 2 1.96803E-02 1.37067E-02 5.06E-16 2.28E-02 2.91E-03 3.4E-03 0\n 3 2.15232E-02 1.96162E-02 7.00E-15 9.24E-03 1.44E-03 1.7E-03 0\n 4 2.30321E-02 2.28676E-02 1.15E-15 2.21E-03 2.97E-04 3.4E-04 0\n 5 2.35658E-02 2.35803E-02 1.32E-15 1.02E-04 8.41E-06 9.6E-06 0\n 6 2.35965E-02 2.35965E-02 1.64E-15 7.02E-08 6.35E-09 7.2E-09 0\nIteration 7\n monit() reports good approximate solution (tol = 1.20E-08):\n 7 2.35965E-02 2.35965E-02 1.35E-15 3.52E-11 3.18E-12 3.6E-12 0\n ------------------------------------------------------------------------------\n Status: converged, an optimal solution found\n ------------------------------------------------------------------------------\n Final primal objective value 2.359648E-02\n Final dual objective value 2.359648E-02\n Absolute primal infeasibility 4.168797E-15\n Relative primal infeasibility 1.350467E-15\n Absolute dual infeasibility 5.084353E-11\n Relative dual infeasibility 3.518607E-11\n Absolute complementarity gap 2.685778E-11\n Relative complementarity gap 3.175366E-12\n Iterations 7\n\n Primal variables:\n idx Lower bound Value Upper bound\n 1 -1.00000E-02 -1.00000E-02 1.00000E-02\n 2 -1.00000E-01 -1.00000E-01 1.50000E-01\n 3 -1.00000E-02 3.00000E-02 3.00000E-02\n 4 -4.00000E-02 2.00000E-02 2.00000E-02\n 5 -1.00000E-01 -6.74853E-02 5.00000E-02\n 6 -1.00000E-02 -2.28013E-03 inf\n 7 -1.00000E-02 -2.34528E-04 inf\n\n Box bounds dual variables:\n idx Lower bound Value Upper bound Value\n 1 -1.00000E-02 3.30098E-01 1.00000E-02 0.00000E+00\n 2 -1.00000E-01 1.43844E-02 1.50000E-01 0.00000E+00\n 3 -1.00000E-02 0.00000E+00 3.00000E-02 9.09967E-02\n 4 -4.00000E-02 0.00000E+00 2.00000E-02 7.66124E-02\n 5 -1.00000E-01 3.51391E-11 5.00000E-02 0.00000E+00\n 6 -1.00000E-02 3.42902E-11 inf 0.00000E+00\n 7 -1.00000E-02 8.61040E-12 inf 0.00000E+00\n\n Constraints dual variables:\n idx Lower bound Value Upper bound Value\n 1 -1.30000E-01 0.00000E+00 -1.30000E-01 1.43111E+00\n 2 -inf 0.00000E+00 -4.90000E-03 4.00339E-10\n 3 -inf 0.00000E+00 -6.40000E-03 1.54305E-08\n 4 -inf 0.00000E+00 -3.70000E-03 3.80136E-10\n 5 -inf 0.00000E+00 -1.20000E-03 4.72629E-11\n 6 -9.92000E-02 1.50098E+00 inf 0.00000E+00\n 7 -3.00000E-03 1.51661E+00 2.00000E-03 0.00000E+00\n\n++++++++++ Use the Self-Dual algorithm ++++++++++\n\n ----------------------------------------------\n E04MT, Interior point method for LP problems\n ----------------------------------------------\n\n Original Problem Statistics\n\n Number of variables 7\n Number of constraints 7\n Free variables 0\n Number of nonzeros 41\n\n\n Presolved Problem Statistics\n\n Number of variables 13\n Number of constraints 7\n Free variables 0\n Number of nonzeros 47\n\n\n ------------------------------------------------------------------------------\n it| pobj | dobj | p.inf | d.inf | d.gap | tau | mcc | I\n ------------------------------------------------------------------------------\n 0 -6.39941E-01 4.94000E-02 1.07E+01 2.69E+00 5.54E+00 1.0E+00\n 1 -8.56025E-02 -1.26938E-02 2.07E-01 2.07E-01 2.07E-01 1.7E+00 0\n 2 4.09196E-03 1.24373E-02 4.00E-02 4.00E-02 4.00E-02 2.8E+00 0\n 3 1.92404E-02 2.03658E-02 6.64E-03 6.64E-03 6.64E-03 3.2E+00 1\n 4 1.99631E-02 2.07574E-02 3.23E-03 3.23E-03 3.23E-03 2.3E+00 1\n 5 2.03834E-02 2.11141E-02 1.68E-03 1.68E-03 1.68E-03 1.4E+00 0\n 6 2.22419E-02 2.25057E-02 5.73E-04 5.73E-04 5.73E-04 1.4E+00 1\n 7 2.35051E-02 2.35294E-02 6.58E-05 6.58E-05 6.58E-05 1.4E+00 6\n 8 2.35936E-02 2.35941E-02 1.19E-06 1.19E-06 1.19E-06 1.4E+00 0\nIteration 9\n monit() reports good approximate solution (tol = 1.20E-08):\n 9 2.35965E-02 2.35965E-02 5.37E-10 5.37E-10 5.37E-10 1.4E+00 0\nIteration 10\n monit() reports good approximate solution (tol = 1.20E-08):\n 10 2.35965E-02 2.35965E-02 2.68E-13 2.68E-13 2.68E-13 1.4E+00 0\n ------------------------------------------------------------------------------\n Status: converged, an optimal solution found\n ------------------------------------------------------------------------------\n Final primal objective value 2.359648E-02\n Final dual objective value 2.359648E-02\n Absolute primal infeasibility 2.853383E-12\n Relative primal infeasibility 2.677658E-13\n Absolute dual infeasibility 1.485749E-12\n Relative dual infeasibility 2.679654E-13\n Absolute complementarity gap 7.228861E-13\n Relative complementarity gap 2.683908E-13\n Iterations 10\n\n Primal variables:\n idx Lower bound Value Upper bound\n 1 -1.00000E-02 -1.00000E-02 1.00000E-02\n 2 -1.00000E-01 -1.00000E-01 1.50000E-01\n 3 -1.00000E-02 3.00000E-02 3.00000E-02\n 4 -4.00000E-02 2.00000E-02 2.00000E-02\n 5 -1.00000E-01 -6.74853E-02 5.00000E-02\n 6 -1.00000E-02 -2.28013E-03 inf\n 7 -1.00000E-02 -2.34528E-04 inf\n\n Box bounds dual variables:\n idx Lower bound Value Upper bound Value\n 1 -1.00000E-02 3.30098E-01 1.00000E-02 0.00000E+00\n 2 -1.00000E-01 1.43844E-02 1.50000E-01 0.00000E+00\n 3 -1.00000E-02 0.00000E+00 3.00000E-02 9.09967E-02\n 4 -4.00000E-02 0.00000E+00 2.00000E-02 7.66124E-02\n 5 -1.00000E-01 3.66960E-12 5.00000E-02 0.00000E+00\n 6 -1.00000E-02 2.47652E-11 inf 0.00000E+00\n 7 -1.00000E-02 7.82645E-13 inf 0.00000E+00\n\n Constraints dual variables:\n idx Lower bound Value Upper bound Value\n 1 -1.30000E-01 0.00000E+00 -1.30000E-01 1.43111E+00\n 2 -inf 0.00000E+00 -4.90000E-03 1.07904E-10\n 3 -inf 0.00000E+00 -6.40000E-03 1.14799E-09\n 4 -inf 0.00000E+00 -3.70000E-03 4.09190E-12\n 5 -inf 0.00000E+00 -1.20000E-03 1.52421E-12\n 6 -9.92000E-02 1.50098E+00 inf 0.00000E+00\n 7 -3.00000E-03 1.51661E+00 2.00000E-03 0.00000E+00\n", "meta": {"hexsha": "033d40f6369c4057adcec6a79baa20b0168f53fb", "size": 7604, "ext": "r", "lang": "R", "max_stars_repo_path": "simple_examples/baseresults/e04mtje.r", "max_stars_repo_name": "numericalalgorithmsgroup/NAGJavaExamples", "max_stars_repo_head_hexsha": "f625b3f043c5c14a88d7ecbc04374acf75d63c82", "max_stars_repo_licenses": ["BSD-3-Clause"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2021-07-03T22:53:20.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-04T01:44:03.000Z", "max_issues_repo_path": "simple_examples/baseresults/e04mtje.r", "max_issues_repo_name": "numericalalgorithmsgroup/NAGJavaExamples", "max_issues_repo_head_hexsha": "f625b3f043c5c14a88d7ecbc04374acf75d63c82", "max_issues_repo_licenses": ["BSD-3-Clause"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "simple_examples/baseresults/e04mtje.r", "max_forks_repo_name": "numericalalgorithmsgroup/NAGJavaExamples", "max_forks_repo_head_hexsha": "f625b3f043c5c14a88d7ecbc04374acf75d63c82", "max_forks_repo_licenses": ["BSD-3-Clause"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-07-03T22:55:16.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-02T01:00:53.000Z", "avg_line_length": 46.6503067485, "max_line_length": 79, "alphanum_fraction": 0.5084166228, "num_tokens": 3236, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7217432062975979, "lm_q2_score": 0.519521321952093, "lm_q1q2_score": 0.37496098464567024}} {"text": "############################################################################################################\n############################################################################################################\n## Loading necessary libraries\n############################################################################################################\n############################################################################################################\n\nlibrary(ggplot2)\nlibrary(gridExtra)\nlibrary(lme4)\nlibrary(lmerTest)\nlibrary(robustlmm)\nlibrary(MCMCglmm)\nlibrary(xtable)\nlibrary(shinyBS)\nlibrary(nlme)\nlibrary(combinat)\n\n############################################################################################################\n############################################################################################################\n## Global functions\n############################################################################################################\n############################################################################################################\n\nggCaterpillar=function(re, QQ=TRUE, likeDotplot=TRUE) \n{\n require(ggplot2)\n f = function(x) {\n pv=attr(x, \"postVar\")\n cols=1:(dim(pv)[1])\n se=unlist(lapply(cols, function(i) sqrt(pv[i, i, ])))\n ord=unlist(lapply(x, order)) + rep((0:(ncol(x) - 1)) * nrow(x), each=nrow(x))\n pDf=data.frame(y=unlist(x)[ord],ci=1.96*se[ord],nQQ=rep(qnorm(ppoints(nrow(x))), ncol(x)),\n ID=factor(rep(rownames(x), ncol(x))[ord], levels=rownames(x)[ord]), ind=gl(ncol(x), nrow(x), labels=names(x)))\n \n if(QQ) { \n p = ggplot(pDf, aes(nQQ, y))\n p = p + facet_wrap(~ ind, scales=\"free\")\n p = p + xlab(\"Standard normal quantiles\") + ylab(\"Random effect quantiles\")\n } else { \n p = ggplot(pDf, aes(ID, y)) + coord_flip() + ggtitle(\"Caterpillar plot showing the group-level\\nerror terms for each random effect\") \n if(likeDotplot) { \n p = p + facet_wrap(~ ind)\n } else { \n p = p + facet_grid(ind ~ ., scales=\"free_y\")\n }\n p = p + xlab(\"Groups\") + ylab(\"Deviations\")\n }\n \n p = p + theme_bw() + theme(legend.position=\"none\") + geom_hline(yintercept=0) + \n geom_errorbar(aes(ymin=y-ci, ymax=y+ci), width=0, colour=\"black\") + geom_point(aes(size=2), shape=1) \n \n return(p)\n }\n lapply(re, f)\n}\n\n############################################################################################################\n############################################################################################################\n## Loading sample data sets\n############################################################################################################\n############################################################################################################\n\nkentucky=read.csv(\"data/KentuckyMathScores.csv\")\nmusic=read.csv(\"data/musicdata.csv\")\n\n############################################################################################################\n############################################################################################################\n## Shiny server\n############################################################################################################\n############################################################################################################\n\nshinyServer(function(input, output, session) {\n \n ############################################################################################################\n ############################################################################################################\n ## Upload Data Panel\n ############################################################################################################\n ############################################################################################################\n \n data = reactive({\n if(is.null(input$file) & !input$usesample) \n {\n return(NULL)\n } else if(!is.null(input$file) & !input$usesample)\n {\n file = read.csv(input$file$datapath, header=input$header, sep=input$sep, quote=input$quote)\n return(file)\n } else if(input$usesample)\n {\n return(music)\n }\n })\n \n output$datatable = renderDataTable({\n if(!input$usesample)\n {\n return(data())\n }\n })\n \n output$sampledata = renderDataTable({\n data()\n })\n \n output$selectresponse = renderUI({ \n selectInput(\"response\",\"Response variable:\",choices=names(data()),selectize=TRUE) \n })\n \n output$selectlevel1fixedpred = renderUI({\n selectInput(\"level1.fixed.pred\",\"Level 1 fixed predictors:\",choices=names(data()),multiple=TRUE,selectize=TRUE)\n })\n \n output$selectlevel1randpred = renderUI({\n selectInput(\"level1.rand.pred\",\"Level 1 random predictors:\",choices=names(data()),multiple=TRUE,selectize=TRUE)\n })\n \n output$selectlevel2id = renderUI({\n selectInput(\"level2.id\",\"Level 2 observational unit:\",choices=names(data()),selectize=TRUE)\n })\n \n output$selectlevel2pred = renderUI({\n selectInput(\"level2.pred\",\"Level 2 predictors\",choices=names(data()),multiple=TRUE,selectize=TRUE)\n })\n \n ############################################################################################################\n ############################################################################################################\n ## HLM Study Panel\n ############################################################################################################\n ############################################################################################################\n \n ############################################################################################################\n ############################################################################################################\n ## Varying-Intercept Only\n ############################################################################################################\n ############################################################################################################\n \n output$selectresponse1 = renderUI({ \n selectInput(\"response1\",\"Response variable:\",choices=names(data()),selectize=TRUE) \n })\n \n output$selectlevel2id1 = renderUI({\n selectInput(\"level2.id1\",\"Level 2 observational unit:\",choices=names(data()),selectize=TRUE)\n })\n \n dat.nopred = reactive({\n if(!input$usesample)\n {\n dat = data.frame(response = data()[,paste(input$response1)],\n level2.id = factor(data()[,paste(input$level2.id1)]))\n return(dat)\n } else if (input$usesample)\n {\n dat = data.frame(response = data()$negative_affect,\n level2.id = factor(data()$id))\n }\n })\n \n output$datatab1 = renderDataTable({\n if(!input$usesample) return(dat.nopred())\n })\n \n label = reactive({\n if(!input$usesample)\n {\n return(c(paste(input$response1),paste(input$level2.id1)))\n }else if(input$usesample)\n {\n return(c(\"negative affect\",\"musicians\"))\n }\n })\n \n ############################################################################################################\n ## Pooled Regression 1\n ############################################################################################################\n \n output$poolednopredgraph = renderPlot({\n ggplot(data=dat.nopred()) + geom_histogram(aes(x=response),fill=\"white\",color=\"navy\") + \n xlab(paste(label()[1])) + ylab(\"Frequency\") + ggtitle(paste(\"Histogram of\",label()[1],\"with pooled mean imposed\")) + \n theme_bw() + geom_vline(aes(xintercept=mean(response)),linetype=\"dashed\",color=\"navy\")\n })\n \n pooled.mod.nopred = reactive({\n lm(response~1, data=dat.nopred())\n })\n \n output$pooled.nopred.info = renderUI({\n mean = round(mean(dat.nopred()$response,na.rm=TRUE),digits=3)\n p(HTML(\"
  • all = pooled mean =\"), code(paste0(mean)))\n })\n \n ############################################################################################################\n ## Unpooled Regression 1\n ############################################################################################################\n \n output$unpooled.nopred.graph = renderPlot({\n ggplot(data=dat.nopred(),aes(x=level2.id,y=response)) + geom_hline(aes(yintercept=mean(response)),linetype=\"dashed\",color=\"navy\") + \n geom_boxplot(fill=\"white\",color=\"navy\") + xlab(paste(label()[2])) + ylab(paste(label()[1])) + \n ggtitle(paste(\"Boxplots of\",label()[1],\"by\",label()[2],\"with pooled and unpooled means imposed\")) +\n theme_bw() + theme(axis.text.x=element_text(angle=90)) +\n stat_summary(fun.y=\"mean\", geom=\"point\", shape=1, size=3, fill=\"white\", color=\"gold2\") \n })\n \n unpooled.mod.nopred = reactive({\n lm(response~level2.id+0, data=dat.nopred())\n })\n \n output$unpooled.mod.summary = renderTable({\n anova(unpooled.mod.nopred())\n })\n \n output$unpooled.nopred.info = renderDataTable({\n mean.dat = data.frame(tapply(dat.nopred()$response,dat.nopred()$level2.id,mean,na.rm=TRUE))\n mean = round(as.numeric(mean.dat[,1]),digits=3)\n var = round(as.numeric(tapply(dat.nopred()$response,dat.nopred()$level2.id,var,na.rm=TRUE)))\n n = as.numeric(tapply(dat.nopred()$response,dat.nopred()$level2.id, function(x) length(!is.na(x))))\n \n dat = data.frame(ID=rownames(mean.dat),Mean=mean,Variance=var,n=n)\n return(dat) \n })\n \n ############################################################################################################\n ## Hierarchical Linear Model 1\n ############################################################################################################\n \n hlm.mod.nopred = reactive({\n lmer(response ~ 1 + (1|level2.id), data=dat.nopred(),\n control=lmerControl(optCtrl=list(maxfun=50000)))\n })\n \n output$hlm.nopred1 = renderPrint({\n summary(hlm.mod.nopred())\n })\n\n coefs = reactive({\n data.frame(coef=coef(hlm.mod.nopred())$level2.id,ran=ranef(hlm.mod.nopred())$level2.id)\n })\n \n output$hlm.nopred2 = renderTable({\n conf = confint(hlm.mod.nopred(),method=\"boot\")\n colnames(conf) = c(\"95% Lower Bound\",\"95% Upper Bound\")\n rownames(conf) = c(\"Between-group SD\",\"Within-group SD\",\"Intercept\")\n return(conf)\n })\n \n output$intraclass1 = renderUI({\n withMathJax(\"$$\\\\hat{\\\\rho} = \\\\frac{\\\\hat{\\\\sigma}_\\\\alpha^{2}}{\\\\hat{\\\\sigma}_\\\\alpha^{2}+\\\\hat{\\\\sigma}_y^{2}}$$\")\n })\n \n variances = reactive({\n c(round(as.numeric(attr(VarCorr(hlm.mod.nopred())[[1]],\"stddev\")^2),digits=3),\n round(as.numeric(attr(VarCorr(hlm.mod.nopred()),\"sc\")^2),digits=3))\n })\n \n output$calcintraclass1 = renderUI({\n icc = round(variances()[1]/sum(variances()),digits=3)\n \n p(\"ICC =\",code(paste(variances()[1])),\" / (\",\n code(paste(variances()[1])),\"+\",\n code(paste(variances()[2])),\") = \",\n code(paste(icc)))\n })\n \n output$ratio1 = renderUI({\n withMathJax(\"$$Variance\\\\,ratio = \\\\frac{\\\\hat{\\\\sigma}_y^{2}}{\\\\hat{\\\\sigma}_\\\\alpha^{2}}$$\")\n })\n \n output$calcratiovariances1 = renderUI({\n ratio = round(variances()[2]/variances()[1],digits=3)\n \n p(\"Ratio =\",code(paste(variances()[2])),\" / \",\n code(paste(variances()[1])), \" = \", code(paste(ratio)))\n })\n \n output$hlmdist1 = renderPlot({ \n ggplot(data=coefs(),aes(x=X.Intercept.)) + geom_histogram(color=\"seagreen2\",fill=\"white\") +\n xlab(\"HLM means\") + ylab(\"Frequency\") + ggtitle(\"Histogram of HLM means\") + theme_bw()\n })\n\n output$hlmdisterror1 = renderPlot({\n ggplot(data=coefs(),aes(x=X.Intercept..1)) + geom_histogram(color=\"salmon\",fill=\"white\") +\n xlab(\"Group-level intercept errors\") + ylab(\"Frequency\") + \n ggtitle(\"Histogram of group-level intercept errors\") + theme_bw()\n })\n\n output$hlmdistinfo1 = renderUI({\n p(HTML(\"
    1. \"),withMathJax(\"\\\\(\\\\hat{\\\\mu}_{\\\\alpha} =\\\\)\"),code(paste(round(as.numeric(fixef(hlm.mod.nopred())),digits=3))),\n HTML(\"
    2. \"),withMathJax(\"\\\\(\\\\hat{\\\\sigma}_\\\\alpha^{2} =\\\\)\"),code(paste(variances()[1])),HTML(\"
    \"))\n })\n \n output$hlmtable = renderDataTable({\n mean.dat = data.frame(tapply(dat.nopred()$response,dat.nopred()$level2.id,mean,na.rm=TRUE))\n n = as.numeric(tapply(dat.nopred()$response,dat.nopred()$level2.id, function(x) length(!is.na(x))))\n rancoefs = round(coefs()$X.Intercept..1,digits=3)\n coefs = round(coefs()$X.Intercept.,digits=3)\n \n dat = matrix(c(rownames(mean.dat),coefs,rancoefs,n),ncol=4)\n colnames(dat) = c(\"Group\",\"Estimated intercept\",\"Group-level error\",\"Sample size\")\n return(dat) \n })\n \n output$ggcat1 = renderPlot({\n ggCaterpillar(ranef(hlm.mod.nopred(), condVar=TRUE), QQ=FALSE)\n })\n \n ############################################################################################################\n ## Comparison of Methods 1\n ############################################################################################################\n \n output$shrinkplot = renderPlot({\n samplesize = tapply(dat.nopred()$response,dat.nopred()$level2.id, function(x) length(x))\n ind = order(samplesize)\n hlmmean = as.vector(unlist(coef(hlm.mod.nopred())))\n hlmmean = hlmmean[ind]\n hlmse = sqrt(attr(ranef(hlm.mod.nopred(), condVar = TRUE)[[1]], \"postVar\")[1, , ])/samplesize\n hlmse = hlmse[ind]\n unpooledse = tapply(dat.nopred()$response,dat.nopred()$level2.id, function(x) sd(x,na.rm=TRUE)/sqrt(length(x)))\n unpooledse = unpooledse[ind]\n unpooledmean = tapply(dat.nopred()$response,dat.nopred()$level2.id,mean,na.rm=TRUE)\n unpooledmean = unpooledmean[ind]\n groups = levels(factor(dat.nopred()$level2.id))\n groups = groups[ind]\n samplesize1 = samplesize[ind]\n dat = data.frame(hlmse=hlmse,hlmmean=hlmmean,unpooledse=unpooledse,unpooledmean=unpooledmean,groups=groups,\n n=samplesize1)\n mean = data.frame(x=mean(dat.nopred()$response),na.rm=TRUE)\n \n g1=ggplot() + theme_bw() + geom_point(data=dat,aes(x=groups,y=unpooledmean,color=\"Unpooled\"),shape=1) +\n geom_point(data=dat,aes(x=groups,y=hlmmean,color=\"HLM\"),shape=16) + \n geom_hline(data=mean,aes(yintercept=x,color=\"Pooled\"),linetype=\"dashed\") + \n geom_errorbar(data=dat,aes(x=groups,y=unpooledmean,ymin=unpooledmean-1.96*unpooledse,ymax=unpooledmean+1.96*unpooledse,color=\"Unpooled\")) +\n geom_errorbar(data=dat,aes(x=groups,y=hlmmean,ymin=hlmmean-1.96*hlmse,ymax=hlmmean+1.96*hlmse,color=\"HLM\")) +\n ylab(\"Mean\") + xlab(\"Group\") + ggtitle(\"Shrinkage plot: 95% CIs using unpooled method and HLM with pooled mean imposed\") +\n scale_color_manual(name=\"Modelling method\",values=c(\"HLM\"=\"tomato\",\"Unpooled\"=\"gold2\",\"Pooled\"=\"navy\")) + theme(legend.position=\"bottom\")\n \n g2=ggplot() + theme_bw() + geom_histogram(data=dat,aes(x=unpooledmean,y=..density..,fill=\"Unpooled\"),alpha=.5) +\n geom_histogram(data=dat,aes(x=hlmmean,y=..density..,fill=\"HLM\"),alpha=.5) +\n geom_density(data=dat,aes(x=unpooledmean),color=\"gold2\") +\n geom_density(data=dat,aes(x=hlmmean),color=\"tomato\") +\n geom_vline(data=mean,aes(xintercept=x,fill=\"Pooled\"),color=\"navy\",linetype=\"dashed\") +\n scale_fill_manual(name=\"Modelling method\",values=c(\"HLM\"=\"tomato\",\"Unpooled\"=\"gold2\",\"Pooled\"=\"navy\")) + \n theme(legend.position=\"bottom\") + ylab(\"Relative frequency\") + xlab(\"Mean\") + ggtitle(\"Histogram of unpooled and HLM means with pooled mean imposed\") \n \n g3 = arrangeGrob(g1,g2,nrow=1)\n return(g3)\n },height=500)\n\n ############################################################################################################\n ## Bayesian Hierarchical Linear Model 1\n ############################################################################################################\n\n hlmbayes1 = reactive({\n MCMCglmm(response ~ 1, random=~level2.id, data=dat.nopred(), verbose=FALSE, pr=TRUE)\n })\n\n output$hlm.bayes1 = renderPrint({\n summary(hlmbayes1())\n })\n\n output$postdist = renderPlot({\n group.error = data.frame(x=as.vector(hlmbayes1()$VCV[,1]))\n indiv.error = data.frame(x=as.vector(hlmbayes1()$VCV[,2]))\n int = data.frame(x=as.vector(hlmbayes1()$Sol[,1]))\n \n group.plot = ggplot(data=group.error) + geom_density(aes(x=x)) + theme_bw() + ylab(\"\") + xlab(\"Between-group var in response\") +\n geom_vline(aes(xintercept=mean(x)),color=\"seagreen2\",size=1)\n group.trace = ggplot(data=group.error) + geom_line(aes(x=1:length(x),y=x)) + theme_bw() + \n geom_hline(aes(yintercept=mean(x)),color=\"seagreen2\",size=1) + \n xlab(\"Iteration\") + ylab(\"Between-group\\nvar in response\")\n indiv.plot = ggplot(data=indiv.error) + geom_density(aes(x=x)) + theme_bw() + ylab(\"\") + xlab(\"Within-group var in response\") +\n geom_vline(aes(xintercept=mean(x)),color=\"seagreen2\",size=1)\n indiv.trace = ggplot(data=indiv.error) + geom_line(aes(x=1:length(x),y=x)) + theme_bw() + \n geom_hline(aes(yintercept=mean(x)),color=\"seagreen2\",size=1) + \n xlab(\"Iteration\") + ylab(\"Within-group\\nvar in response\")\n int.plot = ggplot(data=int) + geom_density(aes(x=x)) + theme_bw() + ylab(\"\") + xlab(\"Intercept\") +\n geom_vline(aes(xintercept=mean(x)),color=\"seagreen2\",size=1)\n int.trace = ggplot(data=int) + geom_line(aes(x=1:length(x),y=x)) + theme_bw() + \n geom_hline(aes(yintercept=mean(x)),color=\"seagreen2\",size=1) + \n xlab(\"Iteration\") + ylab(\"Intercept\")\n graph = arrangeGrob(group.trace,group.plot,indiv.trace,indiv.plot,int.trace,int.plot,nrow=3,ncol=2,\n main=textGrob(\"Traceplots and Posterior Distributions\",gp=gpar(fontsize=15)))\n graph\n },height=500)\n\n ############################################################################################################\n ############################################################################################################\n ## Varying-intercept and varying-slope \n ############################################################################################################\n ############################################################################################################\n\n output$selectresponse2 = renderUI({ \n selectInput(\"response2\",\"Response variable:\",choices=names(data()),selectize=TRUE) \n })\n \n output$selectlevel2id2 = renderUI({\n selectInput(\"level2.id2\",\"Level 2 observational unit:\",choices=names(data()),selectize=TRUE)\n })\n\n output$selectlevel1pred1 = renderUI({\n selectInput(\"level1.pred1\",\"Level 1 predictor:\",choices=names(data()),selectize=TRUE)\n })\n\n dat.pred1 = reactive({\n if(!input$usesample)\n {\n dat = data.frame(predictor = data()[,paste(input$level1.pred1)],\n response = data()[,paste(input$response2)],\n level2.id = factor(data()[,paste(input$level2.id2)]))\n } else if (input$usesample)\n {\n dat = data.frame(predictor = data()$previous,\n response = data()$negative_affect,\n level2.id = factor(data()$id))\n return(dat)\n }\n })\n\n label1 = reactive({\n if(!input$usesample)\n {\n return(c(paste(input$response2),paste(input$level1.pred1),paste(input$level2.id2)))\n }else if(input$usesample)\n {\n return(c(\"negative affect\",\"previous\",\"musicians\"))\n }\n })\n \n ############################################################################################################\n ## Pooled Regression 2\n ############################################################################################################\n \n output$pooled.graph = renderPlot({\n ggplot(data=dat.pred1(), aes(x=predictor,y=response)) + \n geom_point(position = \"jitter\", size=3, shape=1) +\n geom_smooth(method=\"lm\",color=\"navy\",se=FALSE) + xlab(paste(label1()[2])) + ylab(paste(label1()[1])) +\n ggtitle(paste(\"Scatterplot of\",label1()[1],\"versus\", label1()[2],\"with pooled line imposed\")) + theme_bw()\n })\n \n pooled.mod = reactive({\n lm(response~predictor, data=dat.pred1())\n })\n \n output$pooled.output = renderTable({\n return(summary(pooled.mod()))\n })\n \n output$pooled.info = renderText({\n paste0(\"R-squared=\",round(summary(pooled.mod())$r.squared,digits=3),\"; Residual df=\",pooled.mod()$df.residual)\n })\n \n ############################################################################################################\n ## Unpooled Regression 2\n ############################################################################################################\n \n output$unpooled.graph = renderPlot({\n ggplot(data=dat.pred1(), aes(x=predictor,y=response)) + geom_point(position = \"jitter\", size=3, shape=1) +\n geom_smooth(aes(group=level2.id),method=\"lm\",color=\"gold2\",se=FALSE) + \n geom_smooth(aes(group=1),method=\"lm\",color=\"navy\",se=FALSE) + xlab(paste(label1()[2])) + ylab(paste(label1()[1])) +\n ggtitle(paste(\"Scatterplot of\",label1()[1],\"versus\",label1()[2],\"with unpooled lines imposed\")) + theme_bw()\n })\n \n unpooled.mod = reactive({\n lm(response~0+predictor+factor(level2.id)+factor(level2.id)*predictor, data=dat.pred1())\n })\n \n output$unpooled.output = renderTable({\n return(anova(unpooled.mod()))\n })\n \n output$unpooled.info = renderText({\n paste0(\"R-squared=\",round(sum(anova(unpooled.mod())$Sum[1:3])/sum(anova(unpooled.mod())$Sum),digits=3))\n })\n \n slope.intercept = reactive({\n id = unique(dat.pred1()$level2.id)\n slope=NULL\n intercept=NULL\n n=NULL\n i=0\n while(i
  • \"),withMathJax(\"\\\\(\\\\hat{\\\\mu}_{\\\\alpha} =\\\\)\"),code(paste(round(as.numeric(fixef(hlm.mod.nopred())),digits=3))),\n HTML(\"
  • \"),withMathJax(\"\\\\(\\\\hat{\\\\sigma}_\\\\alpha^{2} =\\\\)\"),code(paste(variances()[2])),HTML(\"\"))\n })\n\n output$hlmparamdist2 = renderPlot({\n dat = data.frame(ranef(hlm())$level2.id)\n plot1 = ggplot(dat) + geom_histogram(aes(x=X.Intercept.), color=\"salmon\",fill=\"white\") +\n xlab(\"Group-level intercept errors\") + ylab(\"Frequency\") +\n ggtitle(\"Histogram of group-level\\nintercept errors\") + theme_bw()\n plot2 = ggplot(dat) + geom_histogram(aes(x=predictor), color=\"salmon\",fill=\"white\") +\n xlab(\"Group-level slope errors\") + ylab(\"Frequency\") +\n ggtitle(\"Histogram of group-level\\nslope errors\") + theme_bw()\n plot3 = arrangeGrob(plot1,plot2,nrow=1)\n return(plot3)\n })\n\n output$ggcat2 = renderPlot({\n ggCaterpillar(ranef(hlm(), condVar=TRUE), QQ=FALSE)\n })\n \n ############################################################################################################\n ## Comparison of Methods 2\n ############################################################################################################\n \n output$slopeint.comp = renderPlot({\n dat = dat.pred1()\n mod = lm(response~predictor,data=dat)\n datline = data.frame(x=as.numeric(mod$coef[1]),y=as.numeric(mod$coef[2]))\n \n intercept = ggplot() + geom_histogram(data=slope.intercept(),aes(x=intercept,y=..density..,fill=\"Unpooled\"),alpha=.5) +\n geom_histogram(data=hlm.slope.intercept(),aes(x=int.vec,y=..density..,fill=\"HLM\"),alpha=.5) + \n geom_density(data=slope.intercept(),aes(x=intercept),color=\"gold2\") + \n geom_vline(data=datline,aes(xintercept=x),color=\"navy\",linetype=\"dashed\") +\n geom_density(data=hlm.slope.intercept(),aes(x=int.vec),color=\"tomato\") +\n ggtitle(\"Histogram of sample intercepts\") + xlab(\"Sample intercepts\") + ylab(\"Relative frequency\") +\n scale_fill_manual(name=\"Model\",values=c(\"HLM\"=\"tomato\",\"Unpooled\"=\"gold2\",\"Pooled\"=\"navy\")) + \n guides(fill=FALSE) + theme_bw()\n \n slope = ggplot() + geom_histogram(data=slope.intercept(),aes(x=slope,y=..density..,fill=\"Unpooled\"),alpha=.5) +\n geom_histogram(data=hlm.slope.intercept(),aes(x=slope.vec,y=..density..,fill=\"HLM\"),alpha=.5) + \n geom_density(data=slope.intercept(),aes(x=slope),color=\"gold2\") + \n geom_vline(data=datline,aes(xintercept=y),color=\"navy\",linetype=\"dashed\") +\n geom_density(data=hlm.slope.intercept(),aes(x=slope.vec),color=\"tomato\") + \n ggtitle(\"Histogram of sample slopes\") + xlab(\"Sample slopes\") + ylab(\"Relative frequency\") +\n scale_fill_manual(name=\"Model\",values=c(\"HLM\"=\"tomato\",\"Unpooled\"=\"gold2\",\"Pooled\"=\"navy\")) + \n guides(fill=FALSE) + theme_bw()\n \n graph1 = arrangeGrob(intercept,slope,nrow=1)\n \n graph2 = ggplot() + geom_vline(data=datline,aes(xintercept=x),color=\"navy\",linetype=\"dashed\") + \n geom_hline(data=datline,aes(yintercept=y),color=\"navy\",linetype=\"dashed\") + \n geom_point(data=hlm.slope.intercept(),aes(x=int.vec,y=slope.vec,color=\"HLM\"),size=3,shape=1) +\n geom_point(data=slope.intercept(),aes(x=intercept,y=slope,color=\"Unpooled\"),size=3,shape=1) +\n geom_smooth(data=hlm.slope.intercept(),aes(x=int.vec,y=slope.vec,color=\"HLM\"),method=\"lm\",se=FALSE) + \n geom_smooth(data=slope.intercept(),aes(x=intercept,y=slope,color=\"Unpooled\"),method=\"lm\",se=FALSE) + \n ggtitle(\"Scatterplot of sample slopes versus intercepts with pooled estimates imposed\") +\n xlab(\"Intercepts\") + ylab(\"Slopes\") + scale_color_manual(name=\"Modelling method\",values=c(\"HLM\"=\"tomato\",\"Unpooled\"=\"gold2\")) +\n theme_bw() + theme(legend.position=\"bottom\")\n \n graph3 = arrangeGrob(graph2,graph1,ncol=1)\n \n return(graph3)\n },height=800)\n\n output$comp.method = renderPlot({\n dat = dat.pred1()\n dat$hlmpred = fitted(hlm())\n \n mod = lm(response~predictor,data=dat)\n dat$x=as.numeric(mod$coef[1])\n dat$y=as.numeric(mod$coef[2])\n \n ggplot(data=dat) + geom_point(aes(x=predictor,y=response),shape=1) + facet_wrap(~level2.id) + theme_bw() +\n geom_smooth(aes(x=predictor,y=response, color=\"Unpooled\"), method=\"lm\", se=FALSE) +\n geom_abline(aes(intercept=x,slope=y, color=\"Pooled\"),size=.5) +\n geom_smooth(aes(x=predictor,y=hlmpred,color=\"HLM\"),method=\"lm\",se=FALSE) +\n scale_color_manual(name=\"Modelling method\", values=c(\"Pooled\"=\"navy\",\"Unpooled\"=\"gold2\",\"HLM\"=\"tomato\")) +\n theme(legend.position=\"bottom\", legend.direction=\"horizontal\") + xlab(paste(label1()[2])) + ylab(paste(label1()[1])) +\n ggtitle(\"Comparison of the three modelling methods\")\n },height=800)\n\n ############################################################################################################\n ## Bayesian Hierarchical Linear Model 2\n ############################################################################################################\n\n hlmbayes2 = reactive({\n MCMCglmm(response ~ predictor, random=~level2.id+predictor, data=dat.pred1(), \n verbose=FALSE, pr=TRUE)\n })\n \n output$hlm.bayes2 = renderPrint({\n summary(hlmbayes2())\n })\n \n output$postdist2 = renderPlot({\n slope.error = data.frame(x=as.vector(hlmbayes2()$VCV[,2]))\n indiv.error = data.frame(x=as.vector(hlmbayes2()$VCV[,3]))\n group.error = data.frame(x=as.vector(hlmbayes2()$VCV[,1]))\n int = data.frame(x=as.vector(hlmbayes2()$Sol[,1]))\n group.slope.plot = ggplot(data=slope.error) + geom_density(aes(x=x)) + theme_bw() + ylab(\"\") + xlab(\"Between-group var in slopes\") +\n geom_vline(aes(xintercept=mean(x)),color=\"seagreen2\",size=1)\n group.slope.trace = ggplot(data=slope.error) + geom_line(aes(x=1:length(x),y=x)) + theme_bw() + \n geom_hline(aes(yintercept=mean(x)),color=\"seagreen2\",size=1) + \n xlab(\"Iteration\") + ylab(\"Between-group\\nvar in slopes\")\n group.error.plot = ggplot(data=group.error) + geom_density(aes(x=x)) + theme_bw() + ylab(\"\") + xlab(\"Between-group var in intercepts\") +\n geom_vline(aes(xintercept=mean(x)),color=\"seagreen2\",size=1)\n group.error.trace = ggplot(data=group.error) + geom_line(aes(x=1:length(x),y=x)) + theme_bw() + \n geom_hline(aes(yintercept=mean(x)),color=\"seagreen2\",size=1) + \n xlab(\"Iteration\") + ylab(\"Between-group\\nvar in intercepts\")\n indiv.plot = ggplot(data=indiv.error) + geom_density(aes(x=x)) + theme_bw() + ylab(\"\") + xlab(\"Within-group var in response\") +\n geom_vline(aes(xintercept=mean(x)),color=\"seagreen2\",size=1)\n indiv.trace = ggplot(data=indiv.error) + geom_line(aes(x=1:length(x),y=x)) + theme_bw() + \n geom_hline(aes(yintercept=mean(x)),color=\"seagreen2\",size=1) + \n xlab(\"Iteration\") + ylab(\"Within-group\\nvar in response\")\n int.plot = ggplot(data=int) + geom_density(aes(x=x)) + theme_bw() + ylab(\"\") + xlab(\"Intercept\") +\n geom_vline(aes(xintercept=mean(x)),color=\"seagreen2\",size=1)\n int.trace = ggplot(data=int) + geom_line(aes(x=1:length(x),y=x)) + theme_bw() + \n geom_hline(aes(yintercept=mean(x)),color=\"seagreen2\",size=1) + \n xlab(\"Iteration\") + ylab(\"Intercept\")\n graph = arrangeGrob(group.error.trace,group.error.plot,group.slope.trace,group.slope.plot,indiv.trace,\n indiv.plot,int.trace,int.plot,nrow=4,ncol=2,main=textGrob(\"Traceplots and Posterior Distributions\",gp=gpar(fontsize=15)))\n return(graph)\n },height=600)\n\n ############################################################################################################\n ############################################################################################################\n ## Varying-intercept and varying-slope with level 2 predictor\n ############################################################################################################\n ############################################################################################################\n\n output$selectresponse3 = renderUI({ \n selectInput(\"response3\",\"Response variable:\",choices=names(data()),selectize=TRUE) \n })\n \n output$selectlevel2id3 = renderUI({\n selectInput(\"level2.id3\",\"Level 2 observational unit:\",choices=names(data()),selectize=TRUE)\n })\n \n output$selectlevel1pred2 = renderUI({\n selectInput(\"level1.pred2\",\"Level 1 predictor:\",choices=names(data()),selectize=TRUE)\n })\n\n output$selectlevel2pred1 = renderUI({\n selectInput(\"level2.pred1\",\"Level 2 predictor:\",choices=names(data()),selectize=TRUE)\n })\n\n dat.pred2 = reactive({\n if(!input$usesample)\n {\n dat = data.frame(predictor = data()[,paste(input$level1.pred2)],\n response = data()[,paste(input$response3)],\n level2.id = factor(data()[,paste(input$level2.id3)]),\n level2.predictor = data()[,paste(input$level2.pred1)])\n return(dat)\n }else if(input$usesample)\n {\n dat = data.frame(predictor = data()$previous,\n response = data()$negative_affect,\n level2.id = factor(data()$id),\n level2.predictor = data()$years_study)\n return(dat)\n }\n })\n\n label2 = reactive({\n if(!input$usesample)\n {\n return(c(paste(input$response3),paste(input$level1.pred2),paste(input$level2.id3),paste(input$level2.pred1)))\n } else if(input$usesample)\n {\n return(c(\"negative affect\",\"previous\",\"musicians\",\"years study\"))\n }\n })\n\n ############################################################################################################\n ## Two stage modelling\n ############################################################################################################\n\n stage2 = reactive({\n dat.pred2()[!duplicated(dat.pred2()$level2.id),]\n })\n\n output$int.mod = renderTable({ \n dat = data.frame(intercept=slope.intercept()$intercept,level2.predictor=stage2()$level2.predictor)\n \n lm(intercept ~ level2.predictor, data=dat)\n })\n\n output$slope.mod = renderTable({ \n dat = data.frame(slope=slope.intercept()$slope,level2.predictor=stage2()$level2.predictor)\n \n lm(slope ~ level2.predictor, data=dat)\n })\n\n output$stage2graph = renderPlot({\n dat = data.frame(int=slope.intercept()$intercept,slope=slope.intercept()$slope,pred=stage2()$level2.predictor)\n \n g1 = ggplot(data=dat,aes(x=pred,y=int)) + geom_point(shape=1) + geom_smooth(method=\"lm\",se=FALSE,color=\"gold2\") +\n xlab(paste(label2()[4])) + ylab(\"Unpooled intercepts\") + theme_bw() + \n ggtitle(paste(\"Scatterplot of unpooled\\nintercepts versus\",label2()[4]))\n \n g2 = ggplot(data=dat,aes(x=pred,y=slope)) + geom_point(shape=1) + geom_smooth(method=\"lm\",se=FALSE,color=\"gold2\") +\n xlab(paste(label2()[4])) + ylab(\"Unpooled slopes\") + theme_bw() +\n ggtitle(paste(\"Scatterplot of unpooled\\nslopes versus\",label2()[4]))\n \n g3 = arrangeGrob(g1,g2,nrow=1)\n return(g3)\n })\n\n ############################################################################################################\n ## Hierarchical Linear Model 3\n ############################################################################################################\n\n hlm2 = reactive({\n return(lmer(response ~ predictor + level2.predictor + predictor:level2.predictor + \n (1 + predictor|level2.id), data=dat.pred2(),\n control=lmerControl(optCtrl=list(maxfun=50000))))\n })\n \n output$hlm.summary1 = renderPrint({\n summary(hlm2())\n })\n\n output$hlm.confint2 = renderTable({\n conf = confint(hlm2(),method=\"boot\")\n colnames(conf) = c(\"95% Lower Bound\",\"95% Upper Bound\")\n rownames(conf) = c(\"Between-group Intercept SD\",\"Correlation\",\"Between-group Slope SD\",\"Within-group SD\",\n \"Intercept\",\"Level 1 Predictor\",\"Level 2 Predictor\",\"Cross-level Interaction\")\n return(conf)\n })\n\n output$hlmhyper1 = renderTable({\n vec = as.vector(fixef(hlm2()))\n tab = matrix(vec,nrow=1)\n colnames(tab) = c(\"Intercept\",\"Level 1 Predictor\",\"Level 2 Predictor\",\"Cross-level Interaction\")\n rownames(tab) = \"Estimates\"\n return(tab)\n })\n\n output$hlmhyper2 = renderPrint({\n VarCorr(hlm2())\n })\n\n output$ggcat3 = renderPlot({\n ggCaterpillar(ranef(hlm2(), condVar=TRUE), QQ=FALSE)\n })\n\n ############################################################################################################\n ## Comparison of Methods 3\n ############################################################################################################\n\n output$compgraph = renderPlot({\n dat = data.frame(int=slope.intercept()$intercept,slope=slope.intercept()$slope,pred=stage2()$level2.predictor)\n dat1 = data.frame(int1=fixef(hlm2())[1],slope1=fixef(hlm2())[3],int2=fixef(hlm2())[2],slope2=fixef(hlm2())[4])\n \n g1 = ggplot() + geom_point(data=dat,aes(x=pred,y=int,color=\"Unpooled\"),shape=1) + \n geom_smooth(data=dat,aes(x=pred,y=int,color=\"Unpooled\"),method=\"lm\",se=FALSE) +\n xlab(paste(label2()[4])) + ylab(\"Intercepts\") + theme_bw() +\n geom_abline(data=dat1,aes(intercept=int1,slope=slope1,color=\"HLM\")) +\n scale_color_manual(name=\"Modelling method\", values=c(\"Unpooled\"=\"gold2\",\"HLM\"=\"tomato\")) +\n theme(legend.position=\"bottom\", legend.direction=\"horizontal\") +\n ggtitle(paste(\"Scatterplot of intercepts versus\",label2()[4],\"\\ncomparing the unpooled method and HLM\"))\n \n g2 = ggplot() + geom_point(data=dat,aes(x=pred,y=slope,color=\"Unpooled\"),shape=1) + \n geom_smooth(data=dat,aes(x=pred,y=slope,color=\"Unpooled\"),method=\"lm\",se=FALSE) +\n xlab(paste(label2()[4])) + ylab(\"Slopes\") + theme_bw() +\n geom_abline(data=dat1,aes(intercept=int2,slope=slope2,color=\"HLM\")) +\n scale_color_manual(name=\"Modelling method\", values=c(\"Unpooled\"=\"gold2\",\"HLM\"=\"tomato\")) +\n theme(legend.position=\"bottom\", legend.direction=\"horizontal\") +\n ggtitle(paste(\"Scatterplot of slopes versus\",label2()[4],\"\\ncomparing the unpooled method and HLM\"))\n \n g3 = arrangeGrob(g1,g2,nrow=1)\n return(g3)\n },height=500)\n \n\n ############################################################################################################\n ############################################################################################################\n ## Analyze Data Tab\n ############################################################################################################\n ############################################################################################################\n \n output$selectresponse.analyze = renderUI({ \n selectInput(\"responseanalyze\",\"Response variable:\",choices=names(data()),selectize=TRUE) \n })\n \n output$selectlevel2id.anaylze = renderUI({\n selectInput(\"level2.idanalyze\",\"Level 2 observational unit:\",choices=names(data()),selectize=TRUE)\n })\n \n output$selectlevel1pred.analyze = renderUI({\n selectizeInput(\"level1.predanalyze\",\"Level 1 predictor(s):\",choices=names(data()),\n multiple=TRUE,options=list(placeholder=\"level 1 predictor(s)\"))\n })\n\n output$selectlevel1pred.analyze.rand = renderUI({\n selectizeInput(\"level1.predanalyze.rand\",\"Random predictor(s):\",choices=input$level1.predanalyze,\n multiple=TRUE,options=list(placeholder=\"random predictor(s)\"))\n })\n \n output$selectlevel2pred.analyze = renderUI({\n selectizeInput(\"level2.predanalyze\",\"Level 2 predictor(s):\",choices=names(data()),\n multiple=TRUE,options=list(placeholder=\"level 2 predictor(s)\"))\n })\n\n output$selectcrosslevint = renderUI({\n selectizeInput(\"crosslevelint\", \"Cross-level interaction(s):\", \n choices=as.vector(outer(input$level1.predanalyze.rand, input$level2.predanalyze, paste, sep=\":\")),\n multiple=TRUE,options=list(placeholder=\"cross-level interaction(s)\"))\n })\n\n dat.analyze = reactive({\n dat.pred1=matrix(nrow=dim(data())[1],ncol=length(input$level1.predanalyze))\n i=0\n formula1 = NULL\n formula1 = input$level1.predanalyze[1]\n while(i1) formula1 = paste0(formula1,\"+\",input$level1.predanalyze[i])\n }\n colnames(dat.pred1) = input$level1.predanalyze\n dat.pred1 = data.frame(dat.pred1)\n \n formula2=NULL\n dat.pred2=matrix(nrow=dim(data())[1],ncol=length(input$responseanalyze))\n if(length(input$level2.predanalyze)>0)\n {\n j=0\n formula2 = paste(\"+\",input$level2.predanalyze[1])\n while(j1) formula2 = paste0(formula2,\"+\",input$level2.predanalyze[j])\n }\n colnames(dat.pred2) = input$level2.predanalyze\n dat.pred2 = data.frame(dat.pred2)\n }\n \n formula3=NULL\n if(length(input$level1.predanalyze.rand)>0)\n {\n k=1\n formula3 = paste0(\"+\",input$level1.predanalyze.rand[1])\n while(k0)\n {\n l=1\n formula4 = paste0(\"+\",input$crosslevelint[1])\n while(l0)\n {\n summary = summary(mod.analyze())\n summary$call=NULL\n return(summary)\n }\n })\n }) \n\n})", "meta": {"hexsha": "061ac26c97ba035acc5babc7a781be0e0d4232e2", "size": 44032, "ext": "r", "lang": "R", "max_stars_repo_path": "Hierarchical_Models/server.r", "max_stars_repo_name": "townsenddw/shiny1", "max_stars_repo_head_hexsha": "62e2f54120aa4a3b75fc16da09999cec3c361947", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Hierarchical_Models/server.r", "max_issues_repo_name": "townsenddw/shiny1", "max_issues_repo_head_hexsha": "62e2f54120aa4a3b75fc16da09999cec3c361947", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Hierarchical_Models/server.r", "max_forks_repo_name": "townsenddw/shiny1", "max_forks_repo_head_hexsha": "62e2f54120aa4a3b75fc16da09999cec3c361947", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2019-11-06T12:59:23.000Z", "max_forks_repo_forks_event_max_datetime": "2020-06-21T12:48:05.000Z", "avg_line_length": 45.7237798546, "max_line_length": 156, "alphanum_fraction": 0.5285928416, "num_tokens": 11249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6406358411176238, "lm_q2_score": 0.5851011542032312, "lm_q1q2_score": 0.37483677006187954}} {"text": "# 3. faza: Vizualizacija podatkov\n#Delež ljudi glede na BDP, ki je v zadnjih 3 mesecih opravilo spletni nakup\ngraf1 <- ggplot(tabela1) + aes(x = BDPpc, y = Value, color = Education) + geom_point() + xlab(\"BDP na prebivalca\") + ylab(\"Delež ljudi, ki je v zadnjih 3 mesecih opravil spletni nakup\") + ggtitle(\"Delež ljudi glede na BDP na prebivalca, ki je opravil spletni nakup v zadnjih 3 mesecih\") + labs(color = \"Odstotek prebivalstva s 3. stopnjo izobrazbe\")\n\"Delež ljudi glede na delež ljudi s tretjo st izobrazbe, ki je opravil spletni nakup v zadnjih 3 mesecih\"\ngraf2 <- ggplot(tabela1) + aes(x = Education, y = Value, color = Area ) + geom_point() + xlab(\"Delež ljudi s tretjo stopnjo izobrazbe\") + ylab(\"Delež ljudi, ki je v zadnjih 3 mesecih opravil spletni nakup\") + ggtitle(\"Delež ljudi glede na delež ljudi s tretjo stopnjo izobrazbe, ki je opravilo spletni nakup v zadnjih 3 mesecih\") + scale_color_discrete(name=\"Predel\", labels=c(\"Živeči v mestih\", \"Živeči na ruralnih območjih\"))\n\n\n#tabela2 %>%\n# ggplot(\n# mapping = aes(x = tabela2)\n# ) +\n# geom_histogram() \n#\n\ngraf3 <- tabela1 %>%\n ggplot(\n mapping = aes(group= Country, x = Country, y = Value)\n ) +\n geom_boxplot() + \n xlab(\"Država\") + ylab(\"Kolikšen delež ljudi je v zadnjih 3 mesecih kupil nekaj preko spleta\") + theme(axis.text.x = element_text(angle = 45, vjust = 1, hjust = 1))\n\n\nn <- tabela1 %>% dplyr::group_by(Country) %>% dplyr::summarise(mean = mean(Value, na.rm = TRUE))\nv <- tabela1 %>% dplyr::group_by(Country) %>% dplyr::summarise(BDPmean = mean(BDPpc, na.rm = TRUE))\nn$BDP_mean <- v$BDPmean\n\n\ngraf4 <- ggplot(data = tabela1, aes(x = Year, y = Value, color = Country)) +\n geom_line() + xlab(\"Leto\") + ylab(\"Delež ljudi, ki je v zadnjih 3 mesecih kupil nekaj prek spleta\") + ggtitle(\"Spreminjanje odstotka ljudi po državah, ki so nakupovali prek spleta, čez leta\") + labs(color = \"Država\")\n\ngraf5 <- ggplot(data = tabela1, aes(x = Year, y = Value, color = Area)) +\n geom_line() +\n facet_wrap(facets = vars(Country)) + xlab('Leto') + ylab(\"Delež ljudi, ki je v zadnjih 3 mesecih kupil nekaj prek spleta\") + ggtitle(\"Spreminjanje odstotka ljudi po državah, ki so nakupovali prek spleta, čez leta\") + scale_color_discrete(name=\"Predel\", labels=c(\"Živeči v mestih\", \"Živeči na ruralnih območjih\"))\n\n\ngraf6 <- ggplot(data = tabela2, mapping = aes(x = Year, y = Koliko_vseh_nakupov_je_opravila_ta_skupina, color = Stopnja)) +\n geom_line() +\n facet_wrap(facets = vars(Country)) + xlab('Leto') + ylab(\"Kolikšen delež vseh nakupov je opravila določena skupina\") + ggtitle(\"Spreminjanje odstotka ljudi po državah in doseženi izobrazbi, ki so nakupovali prek spleta, čez leta\") + scale_color_discrete(name=\"Dosežena stopnja izobrazbe\", labels=c(\"Posamezniki z visoko formalno izobrazbo\", \"Posamezniki s srednjo formalno izobrazbo\", \"Posamezniki brez ali z nizko izobrazbo\", \"Študenti\"))\n\n\ngraf7 <- ggplot(data=n, aes(x=Country, y=mean, fill = BDP_mean)) +\n geom_bar(stat=\"identity\") + coord_flip() + scale_fill_gradient(low=\"pink\", high=\"magenta\")+ xlab('Država') + ylab('Povprečen odstotek ljudi, ki kupuje prek spleta v tej državi') + labs(fill = \"Povprečni BDP per capita\") + ggtitle(\"Odstotek ljudi, ki nakupuje prek spleta glede na BDP\")\n\n\nspr <- tabela1\nspr[\"Education\"] <- as.integer(unlist(spr[\"Education\"]))\nizobrazba <- spr %>% dplyr::group_by(Country) %>% dplyr::summarise(Edmean = mean(Education, na.rm = TRUE))\n\n\nn$Edmean <- izobrazba$Edmean\ngraf8 <- ggplot(data=n, aes(x=Country, y=mean, fill = Edmean)) +\n geom_bar(stat=\"identity\") + coord_flip() + scale_fill_gradient(low=\"yellow\", high=\"red\")+ ylab('Povprečen odstotek ljudi, ki nakupuje prek spleta v tej državi') + xlab('Država') + labs(fill = \"Povprečen delež ljudi s tretjo stopnjo izobrazbe\") + ggtitle(\"Odstotek ljudi, ki nakupuje prek spleta glede na odstotek ljudi z doseženo tretjo stopnjo izobrazbe\")\n\n\n\ntabela3_c[,3] <- as.integer(as.character(unlist(tabela3_c[,3])))\ntabela3_c[,4] <- as.integer(unlist(tabela3_c[,4]))\ntabela3_c[,5] <- as.integer(unlist(tabela3_c[,5]))\ntabela3_c[,6] <- as.integer(unlist(tabela3_c[,6]))\ntabela3_c[,7] <- as.integer(unlist(tabela3_c[,7]))\n\nttt <- tabela3_c %>% dplyr::filter(year == 2019, country == 'Slovenia') %>% pivot_longer(c(3, 4, 5, 6, 7), names_to = 'type', values_to = \"value\")\ngraf9 <- ggplot(data = ttt, mapping = aes(x = country, y = value, fill = type)) +\n geom_bar(width = 1, stat = 'identity') + coord_polar(\"y\", start=0) + xlab('') + ylab('') + ggtitle(\"Kaj kupujejo ljudje v posamezni državi?\") + scale_fill_discrete(name = \"Vrsta kupljenega izdelka\", labels = c(\"Knjige, revije, učenje,...\", \"Obleke, šport\", \"Filmi, glasba\", \"Gospodinjski pripomočki\", \"Potovanja, hoteli,...\"))\n\ntabela2_c[,4] <- as.integer(unlist(tabela2_c[,4]))\ntabela2_c[,5] <- as.integer(unlist(tabela2_c[,5]))\nfff1 <- tabela2_c %>% dplyr::filter(year == 2019, country == 'United Kingdom', stopnja == 'Individuals with high formal education') %>% pivot_longer(c(4, 5), names_to = 'type', values_to = 'value')\ngraf10 <- ggplot(data = fff1, mapping = aes(x = country, y = value, fill = type)) +\n geom_bar(width = 1, stat = 'identity') + coord_polar(\"y\", start=0) + ggtitle(\"Kaj kupujejo ljudje\\nz doseženo visoko izobrazbo\\nv Združenem kraljestvu?\") + xlab('') + ylab('') + scale_fill_discrete(name = 'Vrsta kupljenega izdelka', labels = c('Knjige, revije, učenje,...', \"Obleke, šport\")) +\n theme(legend.position = \"none\", axis.text = element_blank(), axis.ticks = element_blank(), panel.grid = element_blank())\n\nfff2 <- tabela2_c %>% dplyr::filter(year == 2019, country == 'United Kingdom', stopnja == 'Individuals with no or low formal education') %>% pivot_longer(c(4, 5), names_to = 'type', values_to = 'value')\ngraf11 <- ggplot(data = fff2, mapping = aes(x = country, y = value, fill = type)) +\n geom_bar(width = 1, stat = 'identity') + coord_polar(\"y\", start=0) + ggtitle(\"Kaj kupujejo ljudje \\nbrez izobrazbe ali \\nnizko izobrazbo\\nv Združenem kraljestvu?\") + xlab('') + ylab('') + scale_fill_discrete(name = 'Vrsta kupljenega izdelka', labels = c('Knjige, revije, učenje,...', \"Obleke, šport\")) +\n theme(axis.text = element_blank(),\n axis.ticks = element_blank(),\n panel.grid = element_blank())\n\n\n\n\nlibrary(tmap)\n\nworld <- ne_countries(scale = \"medium\", returnclass = \"sf\")\nEurope <- world[which(world$continent == \"Europe\"),]\nggplot(Europe) +\n geom_sf() +\n coord_sf(xlim = c(-25,50), ylim = c(35,70), expand = FALSE) +\n aes(fill = 'pink')\n\nlvls <-(Europe$sovereignt)\nprimerjava <- data.frame(Country = lvls) %>% left_join(tabela1, by = \"Country\")\nmanjkajoci <- primerjava[is.na(primerjava$BDPpc), ]\n\n\ndf = data.frame(drzava = manjkajoci$Country, Country = c(\"Albania\", \n \"Andorra\",\n \"Bosnia and Herzegovina\",\n \"Belarus\",\n \"Czechia\",\n \"Germany (until 1990 former territory of the FRG)\",\n \"Kosovo\",\n \"Liechtenstein\",\n \"Monaco\",\n \"Moldova\",\n \"North Macedonia\",\n \"Montenegro\",\n \"Russia\",\n \"San Marino\",\n \"Serbia\",\n \"Ukraine\",\n \"Vatican\"))\ntabela1 <- tabela1 %>% left_join(df) %>% dplyr::mutate(Country=ifelse(is.na(drzava), Country, drzava))\ntabela1 <- tabela1 %>% dplyr::select(-drzava)\nn2 <- tabela1 %>% dplyr::group_by(sovereignt = Country) %>% dplyr::summarise(mean = mean(Value, na.rm = TRUE))\nm <- merge(Europe, n2)\nz3 <- ggplot(m) +\n geom_sf() +\n coord_sf(xlim = c(-25,50), ylim = c(35,70), expand = FALSE) +\n aes(fill = mean) +\n scale_fill_gradient(low=\"yellow\", high=\"magenta\") + ggtitle('Katera država v povprečju največ spletno nakupuje?') + labs(fill = \"Odstotek ljudi,\\nki je v zadnjih 3 mesecih\\nspletno nakupoval\\n(povprečno)\")\n\n\n\n\n", "meta": {"hexsha": "6bc80729d7929bc65c073e8f1969d33bfab287ce", "size": 8461, "ext": "r", "lang": "R", "max_stars_repo_path": "vizualizacija/vizualizacija.r", "max_stars_repo_name": "pavlanovak/APPR-2021-22", "max_stars_repo_head_hexsha": "e71743784bb3c94d21ae3100bcef51474cb2271b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "vizualizacija/vizualizacija.r", "max_issues_repo_name": "pavlanovak/APPR-2021-22", "max_issues_repo_head_hexsha": "e71743784bb3c94d21ae3100bcef51474cb2271b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-02-03T11:13:10.000Z", "max_issues_repo_issues_event_max_datetime": "2022-02-04T22:29:08.000Z", "max_forks_repo_path": "vizualizacija/vizualizacija.r", "max_forks_repo_name": "pavlanovak/APPR-2021-22", "max_forks_repo_head_hexsha": "e71743784bb3c94d21ae3100bcef51474cb2271b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 66.6220472441, "max_line_length": 442, "alphanum_fraction": 0.6184848127, "num_tokens": 2768, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5851011542032312, "lm_q2_score": 0.6406358411176238, "lm_q1q2_score": 0.37483677006187954}} {"text": "#Tutorial and Tips for Numerai\n\n#***\n#The stock market is the hardest data science problem in the world.\n#If it seems easy, you're doing it wrong.\n#We don't know how to solve this problem. But here is what we know.\n#We need your help. You take it from here.\n#***\nlibrary(Metrics)\nlibrary(gbm)\nlibrary(randomForest)\n\n# for automatic download of data and upload of submissions have a look at the package Rnumerai\n# for the latest development release use devtools::install_github(\"Omni-Analytics-Group/Rnumerai\") or pak::pkg_install(\"Omni-Analytics-Group/Rnumerai\")\n# for the CRAN version use install.packages(\"Rnumerai\")\n\nprint(\"THIS SCRIPT DOWNSAMPLES DATA AND WILL LIKELY UNDERPERFORM THE example_predictions.csv\")\n\n#the training data is used to train your model how to predict the targets\ntraining_data<-read.csv(\"numerai_training_data.csv\", header=T)\n#the tournament data is the data that Numerai uses to evaluate your model\ntournament<-read.csv(\"numerai_tournament_data.csv\", header=T)\n#the tournament data contains validation data, test data and live data\n#validation is a hold out set out of sample and further in time (higher eras) than the training data\nvalidation<-tournament[tournament$data_type==\"validation\",]\n\nbenchmark<-0.002\nconsistency<-function(data_with_probs, target_name){\n unique_eras<-unique(data_with_probs$era)\n era_correlation<-vector()\n i<-1\n while(i<=length(unique_eras)){\n this_data<-data_with_probs[data_with_probs$era==unique_eras[i],]\n era_correlation[i]<-cor(this_data[,names(this_data)==target_name], this_data$prediction, method=\"spearman\")\n i<-i+1\n }\n consistency<-sum(era_correlation>benchmark)/length(era_correlation)\n consistency\n}\n\n#the training data is large so we reduce it by 10x in order to speed up this script\n#NB reducing the training data like this is not recommended for a production ready model\nnrow(training_data)\nset.seed(10)\n#remove the following line to not downsample. Note: it will take much longer to run\nsample_rows<-sample(1:nrow(training_data), ceiling(nrow(training_data)/10))\ntrain<-training_data[sample_rows,]\n\n#we remove the id, era, and data_type columns for now\ntrain<-train[,-c(1:3)]\nnrow(train)\n\n#there are a large number of features\nncol(train)\n#features are a number of feature groups of different sizes (intelligence, charisma, strength, dexterity, constitution, wisdom)\n#Numerai does not disclose what the features or feature groups mean; they are abstract and obfuscated\n#however, features within feature groups tend to be related in some way\n#models which have large feature importance in one group tend to do badly for long stretches of time (eras).\nhead(names(train),20)\n\n#the target variable has 5 ordinal outcomes (0,0.25,0.5,0.75,1)\n#we train a model on the features to predict this target\nsummary(train$target)\n\n#on this dataset, feature importance analysis is very important\n#we build a random forest to understand which features tend to improve the model out of bag\n#because stocks within eras are not independent, we use small bag sizes (sampsize=10%) so the out of bag estimate is meaningful\n#we use a small subset of features for each tree to build a more feature balanced forest (mtry=10%)\nset.seed(10)\nforest<-randomForest(target~., data=train, ntree=50, mtry=ceiling(0.1*ncol(train)-1), sampsize=ceiling(0.1*nrow(train)), importance=T, maxnodes=5)\n#a good model might drop the bad features according to the forest before training a final model\n#if a feature group or feature is too good, it might also be a good idea to drop to improve the feature balance and improve consistency of the model\nimp<-importance(forest)\nimp<-imp[order(imp[,1], decreasing = FALSE),]\nhead(imp)\n\n#based on the forest we can generate predictions on the validation set\n#the validation set contains eras further in time than the training set\n#the validation set is not \"representative of the live data\"; no one knows how the live data will behave\n#usually train performance < validation performance < live performance because live data is many eras into the future from the training data\npredictions<-predict(forest, validation)\nhead(predictions)\n#Numerai measures performance based on Rank Correlation between your predictions and the true targets\ncor(validation$target, predictions, method=\"spearman\")\nval<-validation\nval$prediction<-predictions\n#consistency is the fraction of months where the model achieves better correlation with the targets than the benchmark\nconsistency(val, \"target\")\n\n#we try a gbm model; we also choose a low bag fraction of 10% as a strategy to deal with within-era non-independence (which is a property of this data)\n#(if you take a sample from one era and a different sample from the same era that sample is not really out of sample because the observations occured in the same era)\n#having small bags also improves the out of bag estimate for the optimal number of trees\nset.seed(10)\nmodel<-gbm(target~., data=train, n.trees=50, shrinkage=0.01, interaction.depth=5, train.fraction=1, bag.fraction=0.1, verbose=T)\n#looking at the relative importance of the features we can see the model relies more on some features than others\nhead(summary(model))\nbest.iter <- gbm.perf(model, method=\"OOB\")\nbest.iter\n\n#we check performance of the gbm model on the out of sample validation data\npredictions<-predict.gbm(model, validation, n.trees=best.iter, type=\"response\")\nhead(predictions)\ncor(validation$target, predictions, method=\"spearman\")\nval<-validation\nval$prediction<-predictions\nconsistency(val, \"target\")\n\n#the gbm model and random forest model have the same consistency (number of eras where correlation > benchmark) even though correlation are different\n#improving consistency can be more important than improving standard machine learning metrics like RMSE\n#good models might train in such a way as to minimize the error across eras (improve consistency) not just reduce the error on each training example\n\n#so far we have ignored eras for training\n#eras are in order of time; for example, era4 is before era5\n#the reason to use eras is that cross validation on rows will tend to overfit (rows within eras are not independent)\n#so it's much better to cross validate within eras for example: take a subset of eras, build a model and test on the out of sample subset of eras\n#this will give a better estimate of how well your model will generalize\n#the validation set is not special; it is just an out of sample set of eras greater than the training set\n#some users might choose to train on the validation set as well\n\n#to give you a sense of how to use eras we train a model on the first half of the eras and test it on the second half\n#we take another 10x smaller sample of data to speed up the script\nordered_eras<-unique(training_data$era)\ntrain<-training_data[sample_rows,]\nfirst_half<-train[train$era%in%ordered_eras[1:ceiling(length(ordered_eras)/2)],]\nsecond_half<-train[!(train$id%in%first_half$id),]\n\n#we remove id, era, data_type column and train a gbm model on the first half of the data\nset.seed(10)\nmodel<-gbm(target~., data=first_half[,-c(1:3)], n.trees=100, shrinkage=0.01, interaction.depth=5, train.fraction=1, bag.fraction=0.1, verbose=T)\nbest.iter <- gbm.perf(model, method=\"OOB\")\nbest.iter\n\npredictions<-predict.gbm(model, second_half, n.trees=best.iter, type=\"response\")\n#our correlation score is good; what we appeared to learn generalizes well on the second half of the eras\n0.5+cor(second_half$target, predictions, method=\"spearman\")\nsec<-second_half\nsec$prediction<-predictions\n#consistency is the fraction of months where the model achieves better correlation with the targets than the benchmark\nconsistency(sec, \"target\")\n\n#but now we try build a model on the second half of the eras and predict on the first half\nset.seed(10)\nmodel<-gbm(target~., data=second_half[,-c(1:3)], n.trees=100, shrinkage=0.01, interaction.depth=5, train.fraction=1, bag.fraction=0.1, verbose=T)\nbest.iter <- gbm.perf(model, method=\"OOB\")\nbest.iter\n\npredictions<-predict.gbm(model, first_half, n.trees=best.iter, type=\"response\")\n#our correlation score is surprisingly low and surprisingly different from when we trained on the first half\n#this means our model is not very consistent, and it's possible that we will see unexpectedly low performance on the test set or live set\n#it also shows that our validation performance is likely to greatly overestimate our performance--this era-wise cross validation is more valuable\n#a model whose performance when training on the first half is the same as training on the second half would likely be more consistent\n#and would likely perform better on the tournament data and the live data\ncor(first_half$target, predictions, method=\"spearman\")\nfir<-first_half\nfir$prediction<-predictions\n#consistency is the fraction of months where the model achieves better correlation with the targets than the benchmark\nconsistency(fir, \"target\")\n\n#Numerai only pays models with correlations that beat the benchmark on the live portion of the tournament data\n#to submit predictions from your model to Numerai, predict on the entire tournament data\n#we choose use our original forest model for our final submission\ntournament$prediction<-predict(forest, tournament)\n\n#create your submission\nsubmission<-subset(tournament, select=c(id, prediction))\nhead(submission)\n\n#save your submission and now upload it to https://numer.ai\nwrite.csv(submission, file=\"submission.csv\", row.names=F)\n", "meta": {"hexsha": "c6dddf0e7da770b34cae3715937b53af034333e1", "size": 9424, "ext": "r", "lang": "R", "max_stars_repo_path": "src/round_254/numerai_dataset_254/example_model.r", "max_stars_repo_name": "gregoryverghese/numerai", "max_stars_repo_head_hexsha": "a15b9c71634fbaaf9eaf1eeceb34ed1b25b6584a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-08-30T18:53:01.000Z", "max_stars_repo_stars_event_max_datetime": "2021-08-30T18:53:01.000Z", "max_issues_repo_path": "example_model.r", "max_issues_repo_name": "JosephLazarus/Numerai", "max_issues_repo_head_hexsha": "f0d0c950068a4bf9b60dc6d512d856d69a34597a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "example_model.r", "max_forks_repo_name": "JosephLazarus/Numerai", "max_forks_repo_head_hexsha": "f0d0c950068a4bf9b60dc6d512d856d69a34597a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 55.4352941176, "max_line_length": 166, "alphanum_fraction": 0.7876697793, "num_tokens": 2259, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7401743620390162, "lm_q2_score": 0.5039061705290805, "lm_q1q2_score": 0.3729784282988859}} {"text": "\r\n# This function is intended to simulate random drift of 4 alleles in a population, given starting and ending\r\n# frequencies for each allele, by resampling population of given allele frequency.\r\n# Revision of a script by Melissa Hardstone (FourAlleleDrift.r), reviewed and minor edits JCF 2018.\r\n# The MH copy of FourAlleleDrift.r script HAS AN ERROR- in the reporting of results for A2 and can give incorrect results.\r\n# What I changed:\r\n #\r\n # Results were previously only kept for current simulation, I routed them to a larger matrix that stores \r\n # results for all sims during function. If raw simulation data is desired, default \"raw_data=FALSE\" can \r\n # be changed to true and all data will be returned. (Good for making sure everything is working as intended, \r\n # and plotting if desired.)\r\n # Also quieted down the function a bit, there were unnecessary print commands everywhere.\r\n # Added comments for clarity\r\n \r\n\r\n# last edit: 2019-1-8 JCF\r\n\r\n# R sessionInfo of last edit.\r\n# > sessionInfo()\r\n# R version 3.5.1 (2018-07-02)\r\n# Platform: x86_64-w64-mingw32/x64 (64-bit)\r\n# Running under: Windows >= 8 x64 (build 9200)\r\n# \r\n# Matrix products: default\r\n# \r\n# locale:\r\n# [1] LC_COLLATE=English_United States.1252 LC_CTYPE=English_United States.1252 LC_MONETARY=English_United States.1252\r\n# [4] LC_NUMERIC=C LC_TIME=English_United States.1252 \r\n# \r\n# attached base packages:\r\n# [1] stats graphics grDevices utils datasets methods base \r\n# \r\n# loaded via a namespace (and not attached):\r\n# [1] compiler_3.5.1 tools_3.5.1 \r\n\r\n\r\n\r\n#\r\n# Input:\r\n#\r\n# SIMS is # simulations desired\r\n# gens is # generations between starting & ending allele frequencies\r\n# size_of_pop is # of diploid individuals in the population\r\n# A1-A4 are starting allele frequencies \r\n# A1-A4 are starting allele frequencies\r\n\r\n#\r\n# Output:\r\n#\r\n# Vector of 4 p-values (1 for each allele), calculated as the number of simulations where the allele frequency change is as extreme as the\r\n# observed allele frequency change. Null hypothesis here is that allele frequency change could be due to drift.\r\n# raw_data is set to FALSE as default, but if set to TRUE function will return a matrix \r\n\r\n\r\nFourAlleleDrift<-function(SIMS, gens, size_of_pop, A1, A2, A3, A4, end_A1, end_A2, end_A3, end_A4, raw_data=FALSE)\r\n{\r\n \r\n # Set up 4 matrices to track allele frequency over gens (dimensions #gens X #sims)\r\n # Fill first row with the starting allele frequency\r\n\tresultA1<-matrix(NA, nrow=gens, ncol=SIMS) # Declare results matrix\r\n\tresultA1[1,]=A1 # Fill first row with the starting allele frequency\r\n\tresultA2<-matrix(NA, nrow=gens, ncol=SIMS)\r\n\tresultA2[1,]=A2\r\n\tresultA3<-matrix(NA, nrow=gens, ncol=SIMS)\r\n\tresultA3[1,]=A3\r\n resultA4<-matrix(NA, nrow=gens, ncol=SIMS)\r\n resultA4[1,]=A4\r\n\r\n \r\n # Now will loop through SIMS (j) & generations (i)\r\n # \r\n\tfor (j in 1:SIMS) # For each of j simulations\r\n\t{\r\n\r\n\t \r\n gen<-gens # no. of generations\r\n\t\tpop_size<-size_of_pop # size_of_pop\r\n\t\ti=1 # Initialize for generation\r\n\r\n\t\t# starting with the inputed allele frequencies\r\n\t\tA1_allele<-A1 # A1 start freq\r\n\t\tA2_allele<-A2 # A2 start freq\r\n\t\tA3_allele<-A3 # A3 start freq\r\n\t\tA4_allele<-A4 # A4 start freq\r\n\r\n\t\t# Create a population with the starting allele frequencies (*2 for diploid)\r\n\t\tpop_alleles<-c( rep('A1',2*pop_size*A1_allele), rep('A2',2*pop_size*A2_allele),\r\n\t\t rep('A3',2*pop_size*A3_allele), rep('A4',2*pop_size*A4_allele) )\r\n\r\n\t\t# take a sample with replacement from the whole population to make next generation (panmictic, random mating)\r\n\t\tpop_alleles<-sample( pop_alleles, 2*pop_size, replace=TRUE )\r\n\r\n\t\t# Add the simulated allele frequency to results matrices: find # of entries in pop_alleles for each allele & divide by 2*pop_size\r\n\t\tresultA1[i+1,j]<-( length(pop_alleles[pop_alleles=='A1']) )/(2*pop_size) # freq of A1 allele, add to results matrix\r\n\t\tresultA2[i+1,j]<-( length(pop_alleles[pop_alleles=='A2']) )/(2*pop_size) # freq of A2 allele\r\n\t\tresultA3[i+1,j]<-( length(pop_alleles[pop_alleles=='A3']) )/(2*pop_size) # freq of A3 allele\r\n\t\tresultA4[i+1,j]<-( length(pop_alleles[pop_alleles=='A4']) )/(2*pop_size) # freq of A4 allele\r\n\t\r\n\t\t\r\n\t\t\r\n\t\t\r\n # each loop, allele freq ending from previous loop used as the start allele freq\r\n\t\tfor(i in 2:gen-1)\r\n\t\t{\r\n\t\t A1_allele<-resultA1[(i+1)-1,j] # uses A1 freq from last generation\r\n\t\t\tA2_allele<-resultA2[(i+1)-1,j] # uses new A2 freq\r\n\t\t\tA3_allele<-resultA3[(i+1)-1,j] # uses new A3 freq\r\n\t\t\tA4_allele<-resultA4[(i+1)-1,j] # uses new A4 freq\r\n\r\n # Simulate population with new allele frequencies\r\n pop_alleles<-c(rep('A1',2*pop_size*A1_allele),rep('A2',2*pop_size*A2_allele),rep('A3',2*pop_size*A3_allele),rep('A4',2*pop_size*A4_allele));\r\n\r\n\t\t\t# take a sample from the whole population to make next generation\r\n pop_alleles<-sample(pop_alleles,2*pop_size,replace=TRUE)\r\n resultA1[i+1,j]<-(length(pop_alleles[pop_alleles=='A1']))/(2*pop_size) # freq of A1 allele, add to results matrix\r\n resultA2[i+1,j]<-(length(pop_alleles[pop_alleles=='A2']))/(2*pop_size) # freq of A2 allele\r\n resultA3[i+1,j]<-(length(pop_alleles[pop_alleles=='A3']))/(2*pop_size) # freq of A3 allele\r\n resultA4[i+1,j]<-(length(pop_alleles[pop_alleles=='A4']))/(2*pop_size) # freq of A4 allele\r\n\r\n\t }\r\n\r\n\t} \r\n \r\n # Now have full matrix of results for each allele.\r\n # Now calculate p-values from simulation results.\r\n\r\n # count times A1 allele freq at generation of interest is equal to or more extreme than obs freq\r\n # need to designate which direction of the extreme values is wanted\r\n if(end_A1 < A1)\r\n {\r\n\t\t A1_p<-length( which( resultA1[gen,] <= end_A1 ) )/SIMS;\r\n\t\t #cat(\"probability of getting end A1 freq or smaller is\", A1_p, '\\n');\r\n\t }else{\r\n\t A1_p<-length( which( resultA1[gen,] >= end_A1 ) )/SIMS;\r\n\t\t #cat(\"probability of getting end A1 freq or larger is\", A1_p, '\\n');\r\n\t }\r\n\r\n \t# Count times A2 allele freq at generation of interest is equal to or more extreme than obs freq\r\n\t# Need to designate which direction of the extreme values is wanted\r\n if(end_A2 < A2)\r\n {\r\n A2_p<-length( which( resultA2[gen,] <= end_A2 ) )/SIMS;\r\n # cat(\"probability of getting end A2 freq or smaller is\", A2_p, '\\n');\r\n }else{\r\n A2_p<-length( which( resultA2[gen,] >= end_A2 ) )/SIMS;\r\n # cat(\"probability of getting end A2 freq or larger is\", A2_p, '\\n');\r\n }\r\n\r\n\t# count times A3 allele freq at generation of interest is equal to or more extreme than obs freq\r\n\t# need to designate which direction of the extreme values is wanted\r\n if(end_A3 < A3)\r\n {\r\n A3_p<-length( which( resultA3[gen,] <= end_A3 ) )/SIMS;\r\n #cat(\"probability of getting end A3 freq or smaller is\", A3_p, '\\n');\r\n }else{\r\n A3_p<-length( which( resultA3[gen,] >= end_A3 ) )/SIMS;\r\n #cat(\"probability of getting end A3 freq or larger is\", A3_p, '\\n');\r\n }\r\n\t\r\n\t# count times A4 allele freq at generation of interest is equal to or more extreme than obs freq\r\n\t# need to designate which direction of the extreme values is wanted\r\n if(end_A4 < A4)\r\n {\r\n A4_p<-length( which( resultA4[gen,] <= end_A4 ) )/SIMS;\r\n #cat(\"probability of getting end A4 freq or smaller is\", A4_p, '\\n');\r\n }else{\r\n A4_p<-length( which( resultA4[gen,] >= end_A4 ) )/SIMS;\r\n #cat(\"probability of getting end A4 freq or larger is\", A4_p, '\\n');\r\n }\r\n \r\n \r\n # Function by default returns a vector of 4 p-values, 1 for each allele. Null hypothesis here is that allele frequency change could be due to drift.\r\n # If raw_data==TRUE, will also return a matrix of simulation results (intended for plotting). \r\n \r\n # Create vector of p-values\r\n p.vals=c(A1_p,A2_p,A3_p,A4_p)\r\n \r\n \r\n if( raw_data==TRUE ){\r\n print( list(\"A1_results\"=resultA1, \"A2_results\"=resultA2, \"A3_results\"=resultA3, \"A4_results\"=resultA4, p.vals) )\r\n } else { print(p.vals) }\r\n \r\n \r\n \r\n}\r\n\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "ee2e76c3492e3c2e39b9d9a70bcde508d9e09b04", "size": 8597, "ext": "r", "lang": "R", "max_stars_repo_path": "FourAlleleDrift_JCF.r", "max_stars_repo_name": "JamieCFreeman/Scott_et-al-2020_Genetic_drift_sims", "max_stars_repo_head_hexsha": "2dc55665b73849240ecf633dab127a72c4519c4b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "FourAlleleDrift_JCF.r", "max_issues_repo_name": "JamieCFreeman/Scott_et-al-2020_Genetic_drift_sims", "max_issues_repo_head_hexsha": "2dc55665b73849240ecf633dab127a72c4519c4b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "FourAlleleDrift_JCF.r", "max_forks_repo_name": "JamieCFreeman/Scott_et-al-2020_Genetic_drift_sims", "max_forks_repo_head_hexsha": "2dc55665b73849240ecf633dab127a72c4519c4b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 45.0104712042, "max_line_length": 151, "alphanum_fraction": 0.6291729673, "num_tokens": 2437, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6442250928250375, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.37203700524285854}} {"text": "## ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n## Demographic component functions\n##\n## x - size this autumn\n## y - size next autumn\n## S - sex\n## A - age\n## G - genotype\n## Nt - standardised population density\n## ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nmk.flist <- function(sets) {\n mydims <- sapply(sets,length)\n mylist <- vector(\"list\", prod(mydims))\n dim(mylist) <- mydims\n dimnames(mylist) <- sets\n return(mylist)\n}\n\n## ~~~~~~~~~ SURVIVAL ~~~~~~~~~\n\np.surv.list <- mk.flist(list(S=c(\"F\",\"M\"), A=c(0,+1)))\n\np.surv.list[[\"F\", \"0\"]] <- function(x, Nt, mPar) {\n nu <- mPar[\"s.a0.F.(Intercept)\"]+mPar[\"s.a0.F.capWgt\"]*x+\n mPar[\"s.a0.F.Nt\"]*Nt+mPar[\"s.a0.F.obsY\"]*mPar[\"obsY\"]\n return(invlogit(nu))\n}\np.surv.list[[\"F\", \"1\"]] <- function(x, G, A, Nt, mPar, gSwitch) {\n prefix <- \"s.a1.F\"\n if (prefix %in% names(gSwitch) & !gSwitch[prefix]) { G = 0 }\n nu <- mPar[\"s.a1.F.(Intercept)\"]+mPar[\"s.a1.F.capWgt\"]*x+\n mPar[\"s.a1.F.APS071add\"]*G+\n mPar[\"s.a1.F.poly(ageY, 2, raw = TRUE)1\"]*A+mPar[\"s.a1.F.poly(ageY, 2, raw = TRUE)2\"]*A^2+\n mPar[\"s.a1.F.Nt\"]*Nt+mPar[\"s.a1.F.Nt:APS071add\"]*G*Nt+mPar[\"s.a1.F.obsY\"]*mPar[\"obsY\"]\n return(invlogit(nu))\n}\np.surv.list[[\"M\", \"0\"]] <- function(x, G, Nt, mPar, gSwitch) {\n prefix <- \"s.a0.M\"\n if (prefix %in% names(gSwitch) & !gSwitch[prefix]) { G = 0 }\n nu <- mPar[\"s.a0.M.(Intercept)\"]+mPar[\"s.a0.M.capWgt\"]*x+\n mPar[\"s.a0.M.Nt\"]*Nt+mPar[\"s.a0.M.capWgt:Nt\"]*x*Nt+mPar[\"s.a0.M.obsY\"]*mPar[\"obsY\"]+\n mPar[\"s.a0.M.APS071add\"]*G\n return(invlogit(nu))\n}\np.surv.list[[\"M\", \"1\"]] <- function(x, G, A, Nt, mPar, gSwitch) {\n prefix <- \"s.a1.M\"\n if (prefix %in% names(gSwitch) & !gSwitch[prefix]) { G = 0 }\n nu <- mPar[\"s.a1.M.(Intercept)\"]+mPar[\"s.a1.M.capWgt\"]*x+\n mPar[\"s.a1.M.APS071add\"]*G+mPar[\"s.a1.M.ageY\"]*A+\n mPar[\"s.a1.M.Nt\"]*Nt+mPar[\"s.a1.M.obsY:APS071add\"]*G*mPar[\"obsY\"]+\n mPar[\"s.a1.M.obsY\"]*mPar[\"obsY\"]\n return(invlogit(nu))\n}\n\np.surv <- function(x, G, S, A, Nt, mPar, gSwitch=numeric(0))\n{\n ## expect S and A to have length=1\n if (length(S) != 1 | length(A) != 1)\n stop(\"survival function not vectorised for S(ex) and (A)ge\")\n ## assign the required function\n if (S==\"F\") {\n if (A == 0) {\n f <- p.surv.list[[\"F\", \"0\"]]\n } else if (A >= 1) {\n f <- p.surv.list[[\"F\", \"1\"]]\n } else stop(\"invalid (A)ge\")\n } else if (S==\"M\") {\n if (A == 0) {\n f <- p.surv.list[[\"M\", \"0\"]]\n } else if (A >= 1) {\n f <- p.surv.list[[\"M\", \"1\"]]\n } else stop(\"invalid (A)ge\")\n } else stop(\"invalid (S)ex\")\n ## get the required arguments as a list of atomic 'names'\n fargs <- names(formals(f))\n fargs <- sapply(fargs, as.name)\n ## call the function and return\n return(do.call(\"f\", fargs))\n}\n\n## ~~~~~~~~~ GROWTH ~~~~~~~~~\n\nd.grow.list <- mk.flist(list(S=c(\"F\",\"M\"), A=c(0,+1)))\n\nd.grow.list[[\"F\",\"0\"]] <- function(y, x, Nt, mPar) {\n mu <- mPar[\"g.a0.F.(Intercept)\"]+mPar[\"g.a0.F.capWgt\"]*x+mPar[\"g.a0.F.Nt\"]*Nt\n sg <- mPar[\"g.a0.F.sigma\"]\n return(dnorm(y,mu,sg))\n}\nd.grow.list[[\"F\",\"1\"]] <- function(y, x, G, A, Nt, mPar) {\n mu <- mPar[\"g.a1.F.(Intercept)\"] + mPar[\"g.a1.F.capWgt\"]*x + mPar[\"g.a1.F.poly(ageY, 2, raw = TRUE)1\"]*A +\n mPar[\"g.a1.F.Nt\"]*Nt + mPar[\"g.a1.F.ageY:Nt\"]*Nt*A + mPar[\"g.a1.F.poly(ageY, 2, raw = TRUE)2\"]*A^2\n sg <- mPar[\"g.a1.F.sigma\"]\n return(dnorm(y,mu,sg))\n}\nd.grow.list[[\"M\",\"0\"]] <- function(y, x, Nt, mPar) {\n mu <- mPar[\"g.a0.M.(Intercept)\"]+mPar[\"g.a0.M.capWgt\"]*x+mPar[\"g.a0.M.Nt\"]*Nt+mPar[\"g.a0.M.obsY\"]*mPar[\"obsY\"]\n sg <- mPar[\"g.a0.M.sigma\"]\n return(dnorm(y,mu,sg))\n}\nd.grow.list[[\"M\",\"1\"]] <- function(y, x, G, A, Nt, mPar) {\n mu <- mPar[\"g.a1.M.(Intercept)\"] + mPar[\"g.a1.M.capWgt\"]*x\n sg <- mPar[\"g.a1.M.sigma\"]\n return(dnorm(y,mu,sg))\n}\n\nd.grow <- function(y, x, G, S, A, Nt, mPar)\n{\n ## expect S and A to have length=1\n if (length(S) != 1 | length(A) != 1)\n stop(\"growth function not vectorised for S(ex) and (A)ge\")\n ## assign the required function\n if (S==\"F\") {\n if (A == 0) {\n f <- d.grow.list[[\"F\", \"0\"]]\n } else if (A >= 1) {\n f <- d.grow.list[[\"F\", \"1\"]]\n } else stop(\"invalid (A)ge\")\n } else if (S==\"M\") {\n if (A == 0) {\n f <- d.grow.list[[\"M\", \"0\"]]\n } else if (A >= 1) {\n f <- d.grow.list[[\"M\", \"1\"]]\n } else stop(\"invalid (A)ge\")\n } else stop(\"invalid (S)ex\")\n ## get the required arguments as a list of atomic 'names'\n fargs <- names(formals(f))\n fargs <- sapply(fargs, as.name)\n ## call the function and return\n return(do.call(\"f\", fargs))\n}\n\n## ~~~~~~~~~ FEMALE PROBABILITY OF REPRODUCTION ~~~~~~~~~\n\np.repr.list <- mk.flist(list(A=c(0,+1)))\n\np.repr.list[[\"0\"]] <- function(x, Nt, mPar) {\n nu <- mPar[\"r.a0.F.(Intercept)\"]+mPar[\"r.a0.F.capWgt\"]*x+\n mPar[\"r.a0.F.Nt\"]*Nt+mPar[\"r.a0.F.obsY\"]*mPar[\"obsY\"]+\n mPar[\"r.a0.F.capWgt:obsY\"]*x*mPar[\"obsY\"]\n return(invlogit(nu))\n}\np.repr.list[[\"1\"]] <- function(A, Nt, mPar) {\n nu <- mPar[\"r.a1.F.(Intercept)\"]+\n mPar[\"r.a1.F.poly(ageY, 2, raw = TRUE)1\"]*A+mPar[\"r.a1.F.poly(ageY, 2, raw = TRUE)2\"]*A^2+\n mPar[\"r.a1.F.obsY\"]*mPar[\"obsY\"]+mPar[\"r.a1.F.ageY:obsY\"]*A*mPar[\"obsY\"]\n return(invlogit(nu))\n}\n\np.repr <- function(x, G, A, Nt, mPar)\n{\n ## expect S and A to have length=1\n if (length(A) != 1)\n stop(\"female P(reproduction) function not vectorised for (A)ge\")\n ## assign the required function\n if (A == 0) {\n f <- p.repr.list[[\"0\"]]\n } else if (A >= 1) {\n f <- p.repr.list[[\"1\"]]\n } else stop(\"invalid (A)ge\")\n ## get the required arguments as a list of atomic 'names'\n fargs <- names(formals(f))\n fargs <- sapply(fargs, as.name)\n ## call the function and return\n return(do.call(\"f\", fargs))\n}\n\n## ~~~~~~~~~ FEMALE PROBABILITY OF TWINNING ~~~~~~~~~\n\np.twin.list <- mk.flist(list(A=c(0,+1)))\n\np.twin.list[[\"0\"]] <- function(x, Nt, mPar) {\n return(0)\n}\np.twin.list[[\"1\"]] <- function(x, A, Nt, mPar) {\n nu <- mPar[\"t.a1.F.(Intercept)\"]+mPar[\"t.a1.F.capWgt\"]*x+\n mPar[\"t.a1.F.poly(ageY, 2, raw = TRUE)1\"]*A+mPar[\"t.a1.F.poly(ageY, 2, raw = TRUE)2\"]*A^2+\n mPar[\"t.a1.F.Nt\"]*Nt+mPar[\"t.a1.F.obsY\"]*mPar[\"obsY\"]\n return(invlogit(nu))\n}\n\np.twin <- function(x, G, A, Nt, mPar)\n{\n ## expect S and A to have length=1\n if (length(A) != 1)\n stop(\"female P(twinning) function not vectorised for (A)ge\")\n ## assign the required function\n if (A == 0) {\n f <- p.twin.list[[\"0\"]]\n } else if (A >= 1) {\n f <- p.twin.list[[\"1\"]]\n } else stop(\"invalid (A)ge\")\n ## get the required arguments as a list of atomic 'names'\n fargs <- names(formals(f))\n fargs <- sapply(fargs, as.name)\n ## call the function and return\n return(do.call(\"f\", fargs))\n}\n\n## ~~~~~~~~~ OFFSPRING SPRING SURVIVAL FUNCTION ~~~~~~~~~\n\np.offsurv.list <- mk.flist(list(A=c(0,+1), S.off=c(\"F\",\"M\"), T.off=c(\"0\",\"1\")))\n\np.offsurv.list[[\"0\",\"F\",\"0\"]] <- function(x, Nt, mPar) {\n nu <- mPar[\"s.off.a0.(Intercept)\"]+mPar[\"s.off.a0.capWgtMum\"]*x+\n mPar[\"s.off.a0.Ntm1\"]*Nt+mPar[\"s.off.a0.obsY\"]*mPar[\"obsY\"]\n return(invlogit(nu))\n}\np.offsurv.list[[\"0\",\"M\",\"0\"]] <- function(x, Nt, mPar) {\n nu <- mPar[\"s.off.a0.(Intercept)\"]+mPar[\"s.off.a0.capWgtMum\"]*x+\n mPar[\"s.off.a0.Ntm1\"]*Nt+mPar[\"s.off.a0.obsY\"]*mPar[\"obsY\"]+mPar[\"s.off.a0.sexM\"]\n return(invlogit(nu))\n}\np.offsurv.list[[\"1\",\"F\",\"0\"]] <- function(x, A, Nt, mPar, isTwn) {\n nu <- mPar[\"s.off.a1.(Intercept)\"]+mPar[\"s.off.a1.capWgtMum\"]*x+\n mPar[\"s.off.a1.Ntm1\"]*Nt+mPar[\"s.off.a1.obsY\"]*mPar[\"obsY\"]\n return(invlogit(nu))\n}\np.offsurv.list[[\"1\",\"M\",\"0\"]] <- function(x, A, Nt, mPar, isTwn) {\n nu <- mPar[\"s.off.a1.(Intercept)\"]+mPar[\"s.off.a1.capWgtMum\"]*x+\n mPar[\"s.off.a1.Ntm1\"]*Nt+mPar[\"s.off.a1.obsY\"]*mPar[\"obsY\"]+mPar[\"s.off.a1.sexM\"]\n return(invlogit(nu))\n}\np.offsurv.list[[\"1\",\"F\",\"1\"]] <- function(x, A, Nt, mPar, isTwn) {\n nu <- mPar[\"s.off.a1.(Intercept)\"]+mPar[\"s.off.a1.capWgtMum\"]*x+\n mPar[\"s.off.a1.Ntm1\"]*Nt+mPar[\"s.off.a1.obsY\"]*mPar[\"obsY\"]+mPar[\"s.off.a1.isTwnMat\"]\n return(invlogit(nu))\n}\np.offsurv.list[[\"1\",\"M\",\"1\"]] <- function(x, A, Nt, mPar, isTwn) {\n nu <- mPar[\"s.off.a1.(Intercept)\"]+mPar[\"s.off.a1.capWgtMum\"]*x+\n mPar[\"s.off.a1.Ntm1\"]*Nt+mPar[\"s.off.a1.obsY\"]*mPar[\"obsY\"]+\n mPar[\"s.off.a1.sexM\"]+mPar[\"s.off.a1.isTwnMat\"]\n return(invlogit(nu))\n}\n\np.offsurv <- function(x, G, A, Nt, mPar, S.off, T.off)\n{\n ## expect S and A to have length=1\n if (length(A) != 1)\n stop(\"offspring survival function not vectorised for (A)ge\")\n ## assign the required function\n if (A == 0) {\n if (S.off == \"F\") {\n if (T.off == 0) {\n f <- p.offsurv.list[[\"0\",\"F\",\"0\"]]\n } else if (T.off == 1) {\n return(0) # age 0 females cannot twin\n } else stop(\"invalid offspring (T)win status\")\n } else if (S.off == \"M\") {\n if (T.off == 0) {\n f <- p.offsurv.list[[\"0\",\"M\",\"0\"]]\n } else if (T.off == 1) {\n return(0) # age 0 females cannot twin\n } else stop(\"invalid offspring (T)win status\")\n } else stop(\"invalid offspring (S)ex\")\n } else if (A >= 1) {\n if (S.off == \"F\") {\n if (T.off == 0) {\n f <- p.offsurv.list[[\"1\",\"F\",\"0\"]]\n } else if (T.off == 1) {\n f <- p.offsurv.list[[\"1\",\"F\",\"1\"]]\n } else stop(\"invalid offspring (T)win status\")\n } else if (S.off == \"M\") {\n if (T.off == 0) {\n f <- p.offsurv.list[[\"1\",\"M\",\"0\"]]\n } else if (T.off == 1) {\n f <- p.offsurv.list[[\"1\",\"M\",\"1\"]]\n } else stop(\"invalid offspring (T)win status\")\n } else stop(\"invalid offspring (S)ex\")\n } else stop(\"invalid (A)ge\")\n ## get the required arguments as a list of atomic 'names'\n fargs <- names(formals(f))\n fargs <- sapply(fargs, as.name)\n ## call the function and return\n return(do.call(\"f\", fargs))\n}\n\n## ~~~~~~~~~ OFFSPRING SIZE DISTRIBUTION ~~~~~~~~~\n\nd.offsize.list <- mk.flist(list(S.off=c(\"F\",\"M\"), T.off=c(\"0\",\"1\")))\n\nd.offsize.list[[\"F\",\"0\"]] <- function(y, x, A, Nt, mPar) {\n mu <- mPar[\"sz.off.(Intercept)\"]+mPar[\"sz.off.capWgtMum\"]*x+\n mPar[\"sz.off.ageMum\"]*A+\n mPar[\"sz.off.Ntm1\"]*Nt+\n mPar[\"sz.off.obsY\"]*mPar[\"obsY\"]+\n mPar[\"sz.off.ageMum:obsY\"]*A*mPar[\"obsY\"]\n sg <- mPar[\"sz.off.sigma\"]\n return(dnorm(y,mu,sg))\n}\nd.offsize.list[[\"M\",\"0\"]] <- function(y, x, A, Nt, mPar) {\n mu <- mPar[\"sz.off.(Intercept)\"]+mPar[\"sz.off.capWgtMum\"]*x+\n mPar[\"sz.off.ageMum\"]*A+\n mPar[\"sz.off.Ntm1\"]*Nt+mPar[\"sz.off.sexM\"]+\n mPar[\"sz.off.obsY\"]*mPar[\"obsY\"]+\n mPar[\"sz.off.ageMum:obsY\"]*A*mPar[\"obsY\"]\n\n sg <- mPar[\"sz.off.sigma\"]\n return(dnorm(y,mu,sg))\n}\nd.offsize.list[[\"F\",\"1\"]] <- function(y, x, A, Nt, mPar) {\n mu <- mPar[\"sz.off.(Intercept)\"]+mPar[\"sz.off.capWgtMum\"]*x+\n mPar[\"sz.off.ageMum\"]*A+\n mPar[\"sz.off.Ntm1\"]*Nt+mPar[\"sz.off.isTwnMat\"]+\n mPar[\"sz.off.obsY\"]*mPar[\"obsY\"]+\n mPar[\"sz.off.ageMum:obsY\"]*A*mPar[\"obsY\"]\n sg <- mPar[\"sz.off.sigma\"]\n return(dnorm(y,mu,sg))\n}\nd.offsize.list[[\"M\",\"1\"]] <- function(y, x, A, Nt, mPar) {\n mu <- mPar[\"sz.off.(Intercept)\"]+mPar[\"sz.off.capWgtMum\"]*x+\n mPar[\"sz.off.ageMum\"]*A+\n mPar[\"sz.off.Ntm1\"]*Nt+mPar[\"sz.off.sexM\"]+mPar[\"sz.off.isTwnMat\"]+\n mPar[\"sz.off.obsY\"]*mPar[\"obsY\"]+\n mPar[\"sz.off.ageMum:obsY\"]*A*mPar[\"obsY\"]\n sg <- mPar[\"sz.off.sigma\"]\n return(dnorm(y,mu,sg))\n}\n\nd.offsize <- function(y, x, G, A, Nt, mPar, S.off, T.off)\n{\n ## expect S and A to have length=1\n if (length(S.off) != 1 | length(T.off) != 1)\n stop(\"offspring size function not vectorised for offspring S(ex), female (A)ge and (T)win status\")\n ## assign the required function\n if (all(A >= 0)) {\n if (S.off == \"F\") {\n if (T.off == 0) {\n f <- d.offsize.list[[\"F\",\"0\"]]\n } else if (T.off == 1) {\n f <- d.offsize.list[[\"F\",\"1\"]]\n } else stop(\"invalid offspring (T)win status\")\n } else if (S.off == \"M\") {\n if (T.off == 0) {\n f <- d.offsize.list[[\"M\",\"0\"]]\n } else if (T.off == 1) {\n f <- d.offsize.list[[\"M\",\"1\"]]\n } else stop(\"invalid offspring (T)win status\")\n } else stop(\"invalid offspring (S)ex\")\n } else stop(\"invalid (A)ge\")\n ## get the required arguments as a list of atomic 'names'\n fargs <- names(formals(f))\n fargs <- sapply(fargs, as.name)\n ## call the function and return\n return(do.call(\"f\", fargs))\n}\n\n## ~~~~~~~~~ MALE MATING SUCCESS ~~~~~~~~~\n\nn.mrepro.list <- mk.flist(list(A=c(\"0\",\"1\")))\n\nn.mrepro.list[[\"0\"]] <- function(x, G, Nt, mPar, gSwitch) {\n prefix <- \"n.off.a0.M\"\n if (prefix %in% names(gSwitch) & !gSwitch[prefix]) { G = 0 }\n nu <- mPar[\"n.off.a0.M.(Intercept)\"] + mPar[\"n.off.a0.M.capWgt\"]*x +\n mPar[\"n.off.a0.M.APS071add\"]*G + mPar[\"n.off.a0.M.Nt\"]*Nt + mPar[\"n.off.a0.M.obsY\"]*mPar[\"obsY\"]\n return(exp(nu))\n}\nn.mrepro.list[[\"1\"]] <- function(x, G, Nt, mPar, gSwitch) {\n prefix <- \"n.off.a1.M\"\n if (prefix %in% names(gSwitch) & !gSwitch[prefix]) { G = 0 }\n nu <- mPar[\"n.off.a1.M.(Intercept)\"] + mPar[\"n.off.a1.M.capWgt\"]*x +\n mPar[\"n.off.a1.M.APS071add\"]*G + mPar[\"n.off.a1.M.APS071add:Nt\"]*G*Nt +\n mPar[\"n.off.a1.M.Nt\"]*Nt + mPar[\"n.off.a1.M.obsY\"]*mPar[\"obsY\"]\n return(exp(nu))\n}\n\nn.mrepro <- function(x, G, A, Nt, mPar, gSwitch=numeric(0))\n{\n ## expect S and A to have length=1\n if (length(A) != 1)\n stop(\"male reproduction function not vectorised for (A)ge\")\n ## assign the required function\n if (A == 0) {\n f <- n.mrepro.list[[\"0\"]]\n } else if (A >= 1) {\n f <- n.mrepro.list[[\"1\"]]\n } else stop(\"invalid (A)ge\")\n ## get the required arguments as a list of atomic 'names'\n fargs <- names(formals(f))\n fargs <- sapply(fargs, as.name)\n ## call the function and return\n return(do.call(\"f\", fargs))\n}\n", "meta": {"hexsha": "c09db1dbe490054023df03a6c0ecc3337240ee7e", "size": 14629, "ext": "r", "lang": "R", "max_stars_repo_path": "code_r/imported/demog_fun.r", "max_stars_repo_name": "tdjames1/soay_ibm", "max_stars_repo_head_hexsha": "4b0688549db2ebac7bda344ef7d1b6b432932015", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code_r/imported/demog_fun.r", "max_issues_repo_name": "tdjames1/soay_ibm", "max_issues_repo_head_hexsha": "4b0688549db2ebac7bda344ef7d1b6b432932015", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code_r/imported/demog_fun.r", "max_forks_repo_name": "tdjames1/soay_ibm", "max_forks_repo_head_hexsha": "4b0688549db2ebac7bda344ef7d1b6b432932015", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.8989637306, "max_line_length": 114, "alphanum_fraction": 0.508168706, "num_tokens": 5352, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7549149868676283, "lm_q2_score": 0.4921881357207955, "lm_q1q2_score": 0.37156020001406675}} {"text": "#' ## START MODULE 2.4\n#' Objective: Edit extent, projection, dimension, resolution of raster layers or shapefiles\n#' \n#' tested on R versions 3.1.X, 3.2.X\n#' \n#' Load packages and set working directory\n#+ load packages\n library(rgdal) # fxns: readOGR, writeOGR\n library(raster) # fxns: crop, mask\n# set path\n path.root <- \"~/Documents/Intro-Spatial-R/\"\n path.mod <- paste(path.root, \"module2\", sep = \"\")\n setwd(path.mod)\n#'\n#' ### Crop a polygon file to another polygon\n#' Import shapefile to be altered\n#' \n#+ import shapefile \n# CP study area; the \"mask\" for cropping\n cp.region <- readOGR(dsn = \"data\", layer = \"COP_boundpoly_aea\")\n class(cp.region) # examine class\n\n# North American states/provinces to be altered\n states <- readOGR(dsn = \"data\", layer = \"na_states_aea\")\n class(states) # examine class\n#'\n#' Subset states (UT, AZ, CO, NM) in Colorado Plateau region \n#' - NOTE: str() to determine shapefile characteristics\n#' here, states$CODE returns all state-based codes\n#' - NOTE: rgdal can be squirrelly, requiring NAs to be excluded, it crashes if NA present\n#'\n#+ subset states\n head(states@data) # examine shapepoly data\n states$CODE # state codes\n cp.states <- states[states$CODE == \"UT\" | states$CODE == \"CO\" | \n states$CODE == \"NM\" | states$CODE == \"AZ\", ]\n \n# cp.states <- states[states$CODE == \"UT\" & !is.na(states$CODE) | \n# states$CODE == \"CO\" & !is.na(states$CODE) | \n# states$CODE == \"NM\" & !is.na(states$CODE) | \n# \t states$CODE == \"AZ\" & !is.na(states$CODE), ]\n cp.states@data # examine subsetted states\n#'\n#+ giggle plots\n plot(states)# all of North America\n plot(cp.states, add = T, col = \"blue\")# the subsetted states\n plot(cp.region, add = T, col = \"red\")# the study region, taking long time\n#'\n#' Crop states to the CP region\n#' \n#+ crop states \n cp.statesCROP <- crop(cp.states,cp.region)\n plot(cp.states) # giggle plot\n## output shapefile if desired; examine in ArcGIS if desired\n # writeOGR(cp.statesCROP, dsn = \"./outdata\", layer = \"cp.statesCROP\", \n # morphToESRI = T, driver = \"ESRI Shapefile\")\n#'\n#' ### Polygon crop of raster\n#' This is a 2-step process that is easy to construct as function if desired.\n#' \n#+ import raster\n tave <- raster(\"data/tave_yr_av.img\")\n tave # examine raster\n summary(cp.region) # examine crop polygon (from above)\n#' \n#' Note the different projections; must convert 1 to match other (see Module 2.2)\n#' \n#+ transform to match projections\n cp.regionWGS <- spTransform(cp.region, CRS = CRS(projection(tave)))\n cp.regionWGS # now same projection as tave\n \n## giggle plots; goal is crop of tave to match red in plot\n plot(tave)\n plot(cp.regionWGS, add = T, col = \"red\")\n#' \n#' Step #1; `mask()` function w/CP polygon as the mask applied to tave\n#' \n#+ mask tave\n taveCROP.1 <- mask(tave, cp.regionWGS)\n \n## giggle plots; LOL here .....\n plot(taveCROP.1)# NOTE extent is extent of tave\n plot(extent(taveCROP.1), add = T)\n#' \n#' Step #2; `crop()` function to subset the masked tave to the extent of the CP region\n#' \n#+ crop tave to CP region\n taveCROP.2 <- crop(taveCROP.1, cp.regionWGS)\n \n## giggle plots ...\n plot(taveCROP.2)\n plot(cp.regionWGS, add = T)\n \n## outfile cropped raster if desired\n #writeRaster(taveCROP.2, filename = \"outdata/cp.taveCROP2.img\", format = \"HFA\")\n#'\n#' ### Crop raster using another raster\n#' Assume raster of region to serve as crop; here cp.rast (see Module 2.2)\n#'\n#+ crop raster by raster \n ext.rast <- raster(resolution = 0.008333333, extent(cp.regionWGS))\n cp.rast <- rasterize(cp.regionWGS, field = \"Id\", ext.rast)\n cp.rast # examine\n \n## raster to be cropped\n## same projection/resolution as cp.rast? if not see Module 2.3\n tave # examine\n \n## some giggle plots; crop goal is red\n plot(tave)\n plot(cp.rast, add = T, col = \"red\")\n \n## crop tave raster w/cp.rast raster\n taveCROP.3 <- crop(tave, cp.rast)\n \n## write out file of cropped raster if desired\n #writeRaster(taveCROP.3, filename = \"outdata/cp.taveCROP3.img\", format = \"HFA\")\n \n## giggle plots; NOTE that crop is the cp.rast extent, not just CP region\n plot(taveCROP.3)\n plot(cp.rast, add = T, col = \"red\")\n \n## giggle plots\n par(mfrow = c(1, 2))\n plot(taveCROP.3)\n plot(cp.regionWGS, add = T, border = \"black\")\n\n## outfile cropped raster if desired\n #writeRaster(taveCROP.3, filename = \"outdata/cp.taveCROP3.img\", format = \"HFA\")\n#'\n#' Crop a polygon to a raster\n#'\n#+ load shapefile \n soil <- readOGR(dsn = \"data\", layer = \"soils\") # be patient here ... ~3 min runtime\n soil # examine polygon\n cp.rast # examine raster; both have same projection? if not see Module 2.2/2.3\n \n## crop polygon w/extent of raster\n soilCROP.1 <- crop(soil,extent(cp.rast))\n## giggle plots\n par(mfrow = c(1, 2))\n plot(soil)\n plot(cp.regionWGS, add = T, col = \"red\")\n plot(soilCROP.1)\n plot(cp.rast, add = T, col = \"red\")\n#'\n#' ## END MODULE 2.4\n#' \n#' Create R markdown file from R script \n#+\n knitr::spin(\"Rscripts/M2.4-alterextent_shapefileraster.r\", knit = F, format = \"Rmd\")\n", "meta": {"hexsha": "6f779ec210cc6c453ead96824cffd9b8ac048c5a", "size": 5190, "ext": "r", "lang": "R", "max_stars_repo_path": "module2/Rscripts/M2.4-alterextent_shapefileraster.r", "max_stars_repo_name": "f-tonini/Intro-Spatial-R", "max_stars_repo_head_hexsha": "6bbd65c7fad7d64573964a8981f9bd5cded66f98", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 3, "max_stars_repo_stars_event_min_datetime": "2017-01-23T12:51:19.000Z", "max_stars_repo_stars_event_max_datetime": "2018-10-02T18:02:28.000Z", "max_issues_repo_path": "module2/Rscripts/M2.4-alterextent_shapefileraster.r", "max_issues_repo_name": "f-tonini/Intro-Spatial-R", "max_issues_repo_head_hexsha": "6bbd65c7fad7d64573964a8981f9bd5cded66f98", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "module2/Rscripts/M2.4-alterextent_shapefileraster.r", "max_forks_repo_name": "f-tonini/Intro-Spatial-R", "max_forks_repo_head_hexsha": "6bbd65c7fad7d64573964a8981f9bd5cded66f98", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": 4, "max_forks_repo_forks_event_min_datetime": "2016-10-05T16:12:12.000Z", "max_forks_repo_forks_event_max_datetime": "2018-10-02T18:02:32.000Z", "avg_line_length": 34.1447368421, "max_line_length": 91, "alphanum_fraction": 0.6425818882, "num_tokens": 1591, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6224593452091672, "lm_q2_score": 0.5964331462646254, "lm_q1q2_score": 0.3712553856849222}} {"text": "#' Bumblebee: Quantify Disease Transmission Within and Between Population Groups\n#' \n#' @description\n#' Bumblebee uses counts of directed transmission pairs identified between samples\n#' from population groups of interest to estimate the flow of transmissions within \n#' and between those population groups accounting for sampling heterogeneity.\n#' \n#' Population groups might include: communities, geographical regions, age-gender \n#' groupings or arms of a randomized-clinical trial.\n#' \n#' Counts of observed directed transmission pairs can be obtained from deep-sequence \n#' phylogenetic data (via phyloscanner) or known epidemiological contacts. Note: \n#' Deep-sequence data is also commonly referred to as high-throughput or\n#' next-generation sequence data. See references to learn more about phyloscanner.\n#' \n#' @section The \\code{estimate_transmission_flows()} function:\n#' To estimate transmission flows, that is, the relative probability of transmission \n#' within and between population groups accounting for variable sampling the among\n#' the population groups the function: \\code{estimate_transmission_flows_and_ci()}\n#' computes the conditional probability, \\code{theta_hat} that a pair of pathogen\n#' sequences is from a specific population group pairing given that the pair is\n#' linked.\n#' \n#' For two population groups of interest \\eqn{(u,v)} \\code{theta_hat} is denoted by \n#' \n#' \\deqn{\\hat{\\theta_{ij}} = Pr(pair from groups (i,j) | pair is linked), where i = u,v and j = u,v .}\n#' \n#' To learn more and try some examples, see documentation of the \n#' \\code{estimate_transmission_flows()} function and the bumblebee package\n#' website \\url{https://magosil86.github.io/bumblebee/}.\n#' \n#' @seealso See the following functions for details on estimating transmission flows\n#' and corresponding confidence intervals: \\code{estimate_transmission_flows_and_ci}, \n#' \\code{estimate_theta_hat} and \\code{estimate_multinom_ci}.\n#' \n#' @section Cite the package:\n#' Please cite the package using the following reference:\n#' Lerato E. Magosi, Marc Lipsitch (2021). Bumblebee: Quantify Disease\n#' Transmission Within and Between Population Groups. R package version\n#' 0.1.0 \\url{https://magosil86.github.io/bumblebee/}\n#' \n#' @author \n#' Lerato E. Magosi \\email{lmagosi@hsph.harvard.edu} or \n#' \\email{magosil86@gmail.com}\n#' \n#' @references\n#' \\enumerate{\n#'\n#' \\item Magosi LE, et al., Deep-sequence phylogenetics to quantify patterns of \n#' HIV transmission in the context of a universal testing and treatment\n#' trial – BCPP/ Ya Tsie trial. To submit for publication, 2021.\n#'\n#' \\item Carnegie, N.B., et al., Linkage of viral sequences among HIV-infected\n#' \t\t village residents in Botswana: estimation of linkage rates in the \n#' \t\t presence of missing data. PLoS Computational Biology, 2014. 10(1): \n#' \t\t p. e1003430.\n#' \n#' \\item Goodman, L. A. On Simultaneous Confidence Intervals for Multinomial Proportions \n#' \t\t Technometrics, 1965. 7, 247-254.\n#' \n#' \\item Glaz, J., Sison, C.P. Simultaneous confidence intervals for multinomial proportions. \n#' \t\t Journal of Statistical Planning and Inference, 1999. 82:251-262.\n#' \n#' \\item May, W.L., Johnson, W.D. Constructing two-sided simultaneous confidence intervals for \n#' \t\t multinomial proportions for small counts in a large number of cells. \n#' \t\t Journal of Statistical Software, 2000. 5(6).\n#' \t\t Paper and code available at https://www.jstatsoft.org/v05/i06.\n#' \n#' \\item Ratmann, O., et al., Inferring HIV-1 transmission networks and sources of \n#' \t\t epidemic spread in Africa with deep-sequence phylogenetic analysis. \n#' \t\t Nature Communications, 2019. 10(1): p. 1411.\n#' \n#' \\item Sison, C.P and Glaz, J. Simultaneous confidence intervals and sample size determination\n#' \t\t for multinomial proportions. Journal of the American Statistical Association, \n#' \t\t 1995. 90:366-369.\n#' \n#' \\item Wymant, C., et al., PHYLOSCANNER: Inferring Transmission from Within- and\n#' \t\t Between-Host Pathogen Genetic Diversity. Molecular Biology and Evolution,\n#' \t\t 2017. 35(3): p. 719-733.\n#' }\n#' \n#' @docType package\n#' @name bumblebee-package\n#' @aliases bumblebee\n#' \n#' @keywords internal\n#' @importFrom dplyr %>%\n\"_PACKAGE\"\n", "meta": {"hexsha": "2adb8b80be23c0aeb6a1abe5437c2cf5e2b98d14", "size": 4243, "ext": "r", "lang": "R", "max_stars_repo_path": "R/bumblebee.r", "max_stars_repo_name": "magosil86/bumblebee", "max_stars_repo_head_hexsha": "82e50927f1f3f3fd10c0fc53dd45b60babc2e0c7", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/bumblebee.r", "max_issues_repo_name": "magosil86/bumblebee", "max_issues_repo_head_hexsha": "82e50927f1f3f3fd10c0fc53dd45b60babc2e0c7", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2021-04-29T03:19:50.000Z", "max_issues_repo_issues_event_max_datetime": "2021-04-29T12:38:24.000Z", "max_forks_repo_path": "R/bumblebee.r", "max_forks_repo_name": "magosil86/bumblebee", "max_forks_repo_head_hexsha": "82e50927f1f3f3fd10c0fc53dd45b60babc2e0c7", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 47.6741573034, "max_line_length": 102, "alphanum_fraction": 0.7329719538, "num_tokens": 1079, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494550081926, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.36971524648927734}} {"text": "thresh<-function(x,lam){\n\t# s=solve(A)%*%x\n# \tif(lam==0) return(s)\n# \tmax(1-lam/crossprod(x,s)^(1/2),0)*s\n\tif(lam==0) return(x)\n\tmax(1-lam/sum(x^2)^(1/2) , 0)*x\n}\n\nadmmSel<-function(dat,lam,m1,m2,rho=1,cores=1,elist=NULL){\n\tn=dim(dat)[1]\n\tprint(\"Calculating Statistics:\")\n\td=dim(dat)[2]\n\tif(is.null(elist)) elist= get.edgelist(graph.full(d))\n\tg=graph.edgelist(elist,directed=F)\n\tK = Kvec2(dat,m1,m2,elist)\n\tG = Gamma.ret2(dat,m1,m2,cores=dim(dat)[2],ge=elist)\n\tdd=dim(G[[1]]$v)[1]\n\t#dd=dim(G[[1]])[1]\n\n\tGinv=mclapply(1:d,function(x) G[[x]]$v %*% ((1/((1/n)*G[[x]]$d^2+rho)) * t(G[[x]]$v)),mc.cores=d)\n\t#Ginv=mclapply(1:d,function(x) solve(G[[x]]+rho*diag(dd)),mc.cores=cores)\n\tprint(\"Done.\")\n\tznode = matrix(rnorm(d*m1)*1e-10,d,m1)\n\tzedge = array(rnorm(m2*m2*dim(elist)[1])*1e-10,dim=c(m2,m2,dim(elist)[1]))\n\ttol=Inf\n\tx=xold=y=zz=lapply(1:d,function(x)rep(0,dim(G[[x]]$v)[1]))\n\tadmmout=list()\n\tlam=rev(sort(lam))\n\tif(d>=100) cores = detectCores()\n\tfor(lamind in 1:length(lam)){\n\t\tprint(paste(\"Run \",lamind,\" Begun\"))\n\t\tif(lamind>1){\n\t\t\tx=admmout[[lamind-1]]$x\n\t\t\ty=admmout[[lamind-1]]$y\n\t\t\tzz=admmout[[lamind-1]]$zz\n\t\t}\n\t\ttol=Inf\n\t\titer=0\n\t\twhile(tol>1e-3 & iter<500){\n\t\titer=iter+1\n\t\t# x step\n\t\txold=x\n\t\tzedge_old=zedge\n\t\tznode_old=znode\n\t\t#print(lapply(y,function(x)length(x)))\n\t\tx=mclapply(1:d,function(i){\n\t\t#\tprint(dim(Ginv[[i]]))\n\t\t#\tprint(length(K[[i]]))\n\t\t#\tprint(length(y[[i]]))\n\t\t\tGinv[[i]]%*%(-K[[i]] - y[[i]] + rho*zz[[i]]) \n\t\t},mc.cores=cores)\n\t\t#z-y step\n\t\tfor(i in 1:d){\n\t\t\tii=sum(neighbors(g,i)i , m1 + (j-2)*m2+1 ,(j-1)*m2+1 )\n\t\t\t\t\t#c2 = ifelse(j=100) cores = detectCores()\n\tfor(lamind in 1:length(lam)){\n\t\tprint(paste(\"Run \",lamind,\" Begun\"))\n\t\tif(lamind>1){\n\t\t\tx=admmout[[lamind-1]]$x\n\t\t\ty=admmout[[lamind-1]]$y\n\t\t\tzz=admmout[[lamind-1]]$zz\n\t\t}\n\t\ttol=Inf\n\t\titer=0\n\t\twhile(tol>1e-3 & iter<500){\n\t\titer=iter+1\n\t\t# x step\n\t\txold=x\n\t\tzedge_old=zedge\n\t\tznode_old=znode\n\t\t#print(lapply(y,function(x)length(x)))\n\t\tx=mclapply(1:d,function(i){\n\t\t#\tprint(dim(Ginv[[i]]))\n\t\t#\tprint(length(K[[i]]))\n\t\t#\tprint(length(y[[i]]))\n\t\t\tGinv[[i]]%*%(-K[[i]] - y[[i]] + rho*zz[[i]]) \n\t\t},mc.cores=cores)\n\t\t#z-y step\n\t\tfor(i in 1:d){\n\t\t\tii=sum(neighbors(g,i)i , m1 + (j-2)*m2+1 ,(j-1)*m2+1 )\n\t\t\t\t\t#c2 = ifelse(j1e-3){\n# \t\tfor(i in 1:d){\n# \t\t\tfor(j in i:d){\n# \t\t\t\tA = (gn[[i]][[j]]+gn[[j]][[i]])\n# \t\t\t\tif(i!=j){\n# \t\t\t\t\tee= which(elist[,1]==i & elist[,2]==j)\n# \t\t\t\t\tind11 = which( (elist[,1]==j | elist[,2]==j) & elist[,1]!=i)\n# \t\t\t\t\tind12 = which( (elist[,1]==i | elist[,2]==i) & elist[,2]!=j)\n# \t\t\t\t\txx=crossprod(gr[[i]][[ee]] , out.node[i,])+\n# \t\t\t\t\t gr[[j]][[ee]] %*% out.node[j,] +\n# \t\t\t\t\t c(kve[,,ee])\n# \t\t\t\t}else{\n# \t\t\t\t\tind11 = which( (elist[,1]==j | elist[,2]==j) )\n# \t\t\t\t\tind12 = which( (elist[,1]==i | elist[,2]==i) )\n# \t\t\t\t\txx = kvn[i,]\t\t\t\t\t\n# \t\t\t\t}\n# \t\t\t\t#print(paste(i,\" \" ,j))\n# \t\t\t\t#print(elist[ind11,])\n# \t\t\t\t#print(elist[ind12,])\n# \t\t\t\txx=xx+Reduce(\"+\",lapply(1:length(ind11), function(x){\n# \t\t\t\t\t if(elist[ind11[x],1]==j){\n# \t\t\t\t\t \tgr[[i]][[ind11[x]]] %*% c(out.edge[,,ind12[x]]) \n# \t\t\t\t\t }else{\n# \t\t\t\t\t \tt(gr[[i]][[ind11[x]]]) %*% c(out.edge[,,ind12[x]]) \n# \t\t\t\t\t }\n# \t\t\t\t\t }))\n# \t\t\t\txx=xx+Reduce(\"+\",lapply(1:length(ind11), function(x){\n# \t\t\t\t if(elist[ind12[x],1]==i){\n# \t\t\t\t\t gr[[j]][[ind12[x]]] %*% c(out.edge[,,ind11[x]]) \n# \t\t\t\t}else{\n# \t\t\t\t\tt(gr[[j]][[ind12[x]]]) %*% c(out.edge[,,ind11[x]]) \n# \t\t\t\t}\n# \t\t\t\t \n# \t\t\t\t }))\n# \t\t\t\tif(i==j){\n# \t\t\t\t\tout.node[i,]=thresh(-xx,A,lam)\n# \t\t\t\t}else{\n# \t\t\t\t\tout.edge[,,ee] = matrix( thresh(-xx,A,lam) , m2,m2)\n# \t\t\t\t}\n# \t\t\t}\n# \t\t}\n# \t\t#print(out.edge)\n# \t\t#print(out.node)\n# \t\t#break\n# \t\ttol = mean(abs(out.edge-out.edge.old))\n# \t\ttol= tol + mean(abs(out.node.old-out.node))\n# \t\tprint(tol)\n# \t\tout.node.old = out.node\n# \t\tout.edge.old=out.edge\n# \t}\n# \treturn(list(edge=out.edge,node=out.node))\n# }", "meta": {"hexsha": "4083e34cd4c65c4e3c3f30c491be556e79e37d3b", "size": 8234, "ext": "r", "lang": "R", "max_stars_repo_path": "admm.r", "max_stars_repo_name": "geb5101h/quasr", "max_stars_repo_head_hexsha": "f0b6aa5bb8bc3784977807c04017af5587ec0c87", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "admm.r", "max_issues_repo_name": "geb5101h/quasr", "max_issues_repo_head_hexsha": "f0b6aa5bb8bc3784977807c04017af5587ec0c87", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "admm.r", "max_forks_repo_name": "geb5101h/quasr", "max_forks_repo_head_hexsha": "f0b6aa5bb8bc3784977807c04017af5587ec0c87", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 30.0510948905, "max_line_length": 109, "alphanum_fraction": 0.5246538742, "num_tokens": 3572, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.8080672227971211, "lm_q2_score": 0.45713671682749474, "lm_q1q2_score": 0.3693971972053876}} {"text": "# Solution by Ismail Prada & Andreas Säuberli\n\n# Lena Jäger\n# Eyetracking: From experiment design to statistical and machine learning-based data analysis\n# Assignment 4: Frequentist statistical analysis of a psycholinguistic eye-tracking-while-reading experiment\n\n# Data set:\n# For a detailed description of the data set used in this assignment, please refer to: \n# Jäger, Mertzen, Van Dyke, & Vasishth: 'Interference patterns for subject-verb \n# agreement and reflexives revisited: A large-sample study', \n# Journal of Memory and Language, 2020\n\n# Experimental design: \n# 2x2x2 fully crossed factorial desing:\n# Factor I: Dependency type: {subject-verb agreement; reflexive-antecedent binding}\n# Factor II: Grammaticality: {grammatical; ungrammatical}\n# Factor III: Similarity-based interference: {interference; no-intererence}\n\n# Condition labels: \n# a Agreement; grammatical; interference\n# b. Agreement; grammatical; no interference\n# c. Agreement; ungrammatical; no interference\n# d. Agreement; ungrammatical; interference\n# e. Reflexive; grammatical; interference\n# f. Reflexive; grammatical; no interference\n# g. Reflexive; ungrammatical; no interference\n# h. Reflexive; ungrammatical; interference\n\n# Column names:\n# subj: subject id\n# item: item id\n# cond: condition id\n# acc: comprehension question response accuracy\n# roi: region of interest \n# FPRT: first-pass reading times in ms\n# TFT: total fixation times in ms\n# FPR: first-pass regression (binary)\n\nlibrary(coda)\nlibrary(plyr)\nlibrary(ggplot2)\nlibrary(xtable)\nlibrary(dplyr)\nrequire(tidyr)\nlibrary(tidyverse)\nextrafont::loadfonts()\nlibrary(reshape2)\nrequire(lme4)\n\n\n### RESEARCH QUESTIONS:\n# 1. Are fixation times different in subject-verb agreement versus reflexive-antecedent dependencies?\n# --> main effect of dependency type\n# 2. Are fixation times different in ungrammatical versus grammatical conditions?\n# --> main effect of grammaticality\n# 3. Are fixation times affected by interference?\n# --> main effect of interference\n# 4. Does the grammaticality effect differ between the two dependency types?\n# --> interaction between grammaticality and dependency type\n# 5. Does the interference effect differ between grammatical and ungrammatical conditions?\n# --> interaction between interference and grammaticality\n# 6. Does the interference effect differ between dependency types?\n# --> interaction between interference and dependency type\n# 7. Does the (possible) difference in the sensitivity to the interference manipulation of \n# grammatical versus ungrammatical conditions differ between subject-verb agreement and reflexive-antecedent dependencies?\n# --> 3-way interaction between interference, grammaticality and dependency type\n\n\n# Critical region: were/was/himself/themselves (= roi 12)\n# Dependent variable: total fixation times\n\n\n#### Load and format the data\nd <- read.table(file='dataJMVV.txt', sep = '\\t')\n\n#### Inspect the data and answer the following questions: \n# How many conditions are there? How many instances of each condition?\n# 8 conditions (+filler), counts:\n# a b c d e f filler g h \n# 22659 22659 22659 22596 22680 22638 482412 22680 22617\n# How many subjects and items are there?\n# 181 subjects\n# 176 items\n# NOTE: This could also be answered by converting these columns to factors first and then use str()\n# How many times did each subject see each item? Hint: use xtabs() )\n# 21 times\n# What was the average response accuracy for each of the conditions? Hint: use tapply()\n# a b c d e f \n# -0.05560704 -0.05838740 -0.05004634 -0.06133829 -0.07129630 -0.05751391 \n# filler g h \n# -0.04718788 -0.05185185 -0.05292479\n########################################################\nhead(d, 3)\nd$cond <- factor(d$cond)\nsummary(d$cond)\nlength(unique(d$subj))\nlength(unique(d$item))\nxtabs(~subj+item, d)\ntapply(d$acc, d$cond, mean)\n########################################################\n\n\n### Convert the subj, item and cond columns to factors\n########################################################\nd$subj <- factor(d$subj)\nd$item <- factor(d$item)\nd$cond <- factor(d$cond)\nstr(d)\n########################################################\n\n# Exlcude filler trials and remove all rows from other than the critical region (roi 12)\n########################################################\nd_crit <- d[d$cond != \"filler\" & d$roi == 12, ]\n########################################################\n\n# Note: when removing all rows with a certain level of a factor, this level still exists, it simply has 0 instances:\nsummary(d$cond) # before removing the fillers\nsummary(d_crit$cond) # after removing the fillers\n# We can fix this by simply conveting cond to a factor again: \n########################################################\nd_crit$cond <- factor(d_crit$cond)\n########################################################\n\n\n#### Define contrasts \n# Create hypothesis matrix from the given research questions\n# main effects of dependency and grammaticality and their interaction (applied in Model 1 and 2)\nX_H <- matrix(c( 1/8, 1/8, 1/8, 1/8, 1/8, 1/8, 1/8, 1/8, # Intercept\n 1/4, 1/4, 1/4, 1/4, -1/4, -1/4, -1/4, -1/4, # Main effect dependency type\n -1/4, -1/4, 1/4, 1/4, -1/4, -1/4, 1/4, 1/4, # Main effect grammaticality\n 1/4, -1/4, -1/4, 1/4, 1/4, -1/4, -1/4, 1/4, # Main effect of interference\n -1/4, -1/4, 1/4, 1/4, 1/4, 1/4, -1/4, -1/4, # Grammaticality x Dependency\n -1/4, 1/4, -1/4, 1/4, -1/4, 1/4, -1/4, 1/4, # Interference x Grammaticality\n 1/4, -1/4, -1/4, 1/4, -1/4, 1/4, 1/4, -1/4, # Interference x Dependency type\n -1/4, 1/4, -1/4, 1/4, 1/4, -1/4, 1/4, -1/4 # Interference x Grammaticality x Dependency\n), byrow=TRUE, nrow = 8)\n\n# Compute the inverse of X_H\n########################################################\nlibrary(MASS) # need this for ginv()\nX_C <- ginv(X_H)\n########################################################\n\n# For better readibility add column and row names: \nrownames(X_C) <- c('a','b','c','d','e','f','g','h')\ncolnames(X_C) <- c('Intercept','Dep','Gram','Int','Gram_x_Dep','Int_x_Gram','Int_x_Dep','Int_x_Gram_x_Dep')\n\n# Remove intercept column\n########################################################\nX_C_bar <- X_C[,2:ncol(X_C)]\n########################################################\n\n# Apply the contrasts to the cond column\n########################################################\ncontrasts(d_crit$cond) <- X_C_bar\n########################################################\n\n\n#--------------------------------------------------------\n#--------------------------------------------------------\n# OR: \n# Alternative: code contrasts as numerical columns in the dataframe and use these as predictors in the model\n\n# NOTE: Why did they use d and not d_crit here?\nd_crit$Dep <- ifelse(d_crit$cond %in% c('a', 'b', 'c', 'd'), .5, -.5) # main effect of dependency type: agr=0.5, refl=-0.5\nd_crit$Gram <- ifelse(d_crit$cond %in% c('a', 'b', 'e', 'f'), -.5, .5) # main effect of grammaticality: gram=-.5, ungram=.5\n# ... add the other contrasts\n########################################################\nd_crit$Int <- ifelse(d_crit$cond %in% c('a', 'd', 'e', 'h'), .5, -.5)\nd_crit$Gram_x_Dep <- ifelse(d_crit$cond %in% c('c', 'd', 'e', 'f'), .5, -.5)\nd_crit$Int_x_Gram <- ifelse(d_crit$cond %in% c('b', 'd', 'f', 'h'), .5, -.5)\nd_crit$Int_x_Dep <- ifelse(d_crit$cond %in% c('a', 'd', 'f', 'g'), .5, -.5)\nd_crit$Int_x_Gram_x_Dep <- ifelse(d_crit$cond %in% c('b', 'd', 'e', 'g'), .5, -.5)\n########################################################\n\n#--------------------------------------------------------\n#--------------------------------------------------------\n\n# Remove trials in which the dependent variable (TFT) is zero (i.e., trials in which the critical region was never fixated)\n########################################################\nd_crit_tft <- d_crit[d_crit$TFT != 0, ]\n########################################################\n# How many trials (=rows) in % are removed by selecting only the ones with TFT larger than 0? \n# 0.07765415 => 7.77% of all trials were removed\n########################################################\n1 - nrow(d_crit_tft) / nrow(d_crit)\n########################################################\n\n# Fit a linear mixed model with log transformed total fixation times as dependent variable and the above defined contrasts as predictor variables (independent variables)\nlibrary(lme4)\n########################################################\n# With contrasts coded as columns:\nm <- lmer(log(TFT)~\n Dep+\n Gram+\n Int+\n Gram_x_Dep+\n Int_x_Gram+\n Int_x_Dep+\n Int_x_Gram_x_Dep+\n (1|subj)+\n (1|item),\n data=d_crit_tft)\n########################################################\n# With contrasts coded using contrasts():\nm <- lmer(log(TFT)~cond+(1|subj)+(1|item), data=d_crit_tft)\nsummary(m)\n\n# Interpret the model output verbally.\n########################################################\n# t values for Dep and Gram are large enough to be significant,\n# i.e. dependency type and grammaticality have a significant\n# effect on logarithmic total fixation time.\n# The estimated betas for these contrasts are positive, which means:\n# - Subject-verb agreement has larger TFT than reflexive-antecedent binding\n# - Ungrammatical items have larger TFT than grammatical ones\n# The other contrasts do not show significant effects.\n########################################################\n\n# We have modeled log(TFT). However, for the conceptual interpretation, it is often easier to express the effect sizes on the ms-scale rather than the log-ms scale\n# Compute the effect sizes of the predictors to the ms-scale. H\n\n# Effect of dependency type on the ms scale \n########################################################\n# NOTE: Not sure if this is really what they mean...\n\n# A change from \"reflexive\" to \"agreement\" dependency type increases log(TFT) by 0.2775904\n# This corresponds to multiplying TFT by e^0.2775904 = 1.319945\nms_effects <- exp(fixef(m))\nms_effects[\"condDep\"]\n\n# For example, the average TFT for the \"reflexive\" dependency type is 553.5267 ms:\naverage_reflexive_tft <-\n d_crit_tft %>%\n filter(cond %in% c(\"e\", \"f\", \"g\", \"h\")) %>%\n summarize(mean(TFT))\n\n# Applying a factor of 1.319945 would mean an expected increase by 177.0983 ms\n# when changing the dependency type to \"agreement\":\nms_increase <- average_reflexive_tft * ms_effects[\"condDep\"] - average_reflexive_tft\n########################################################\n", "meta": {"hexsha": "a1c76adb128ea13930df827adce61feceb0ad839", "size": 10834, "ext": "r", "lang": "R", "max_stars_repo_path": "linear_modeling/Assignment_4_Frequentist_Data_Analysis.r", "max_stars_repo_name": "raykyn/eyetracking", "max_stars_repo_head_hexsha": "8757e101c8de292b025939e27eab8aabd0749363", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "linear_modeling/Assignment_4_Frequentist_Data_Analysis.r", "max_issues_repo_name": "raykyn/eyetracking", "max_issues_repo_head_hexsha": "8757e101c8de292b025939e27eab8aabd0749363", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "linear_modeling/Assignment_4_Frequentist_Data_Analysis.r", "max_forks_repo_name": "raykyn/eyetracking", "max_forks_repo_head_hexsha": "8757e101c8de292b025939e27eab8aabd0749363", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 44.7685950413, "max_line_length": 169, "alphanum_fraction": 0.5792874285, "num_tokens": 2788, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5964331462646255, "lm_q2_score": 0.6187804337438501, "lm_q1q2_score": 0.36906116094483415}} {"text": "#!/usr/local/bin/Rscript --vanilla\n\n###############################################################################\n# METAREP : High-Performance Comparative Metagenomics Framework (http://www.jcvi.org/metarep)\n# Copyright(c) J. Craig Venter Institute (http://www.jcvi.org)\n#\n# Licensed under The MIT License\n# Redistributions of files must retain the above copyright notice.\n#\n# link http://www.jcvi.org/metarep METAREP Project\n# package metarep\n# version METAREP v 1.3.2\n# author Johannes Goll\n# lastmodified 2010-07-09\n# license http://www.opensource.org/licenses/mit-license.php The MIT License\n###############################################################################\n\nlibrary(edgeR);\nlibrary(methods);\n\n## get command line arguments\nargs \t\t\t\t\t= commandArgs(TRUE)\n\ninfile \t\t\t\t\t= args[1];\noutfile \t\t\t\t= args[2];\npropround \t\t\t\t= as.numeric(args[3]);\npvalround \t\t\t\t= as.numeric(args[4]);\nstartIndexPopulationB\t= as.numeric(args[5]);\npopulationNameA\t\t\t= args[6];\npopulationNameB\t\t\t= args[7];\n\n## get edgeR DGE List object\ntargets = read.delim(infile,stringsAsFactors=F);\ndgeList = readDGE(targets);\nfeatures = rownames(dgeList$counts); \nm = as.matrix(dgeList$counts);\n\n## get number of datasets\nncols = as.numeric(length(m[1,]));\nnrows = as.numeric(length(m[,1]));\n\n## get counts for each population\nposA = seq(1,(startIndexPopulationB-1));\n\nposB = seq(startIndexPopulationB,ncols);\ncntA = apply(m[,posA],1,sum);\ncntB = apply(m[,posB],1,sum);\n\n## estimate common dispersion\ncommonDispersion = estimateCommonDisp(dgeList);\n\n## execute exact negative binomial test\nedgeResults = exactTest(commonDispersion,pair=c(populationNameA,populationNameB));\nedgeResultTable = edgeResults$table;\n\n## top ten results for smear plot\n#topTenEdgeResults = topTags(edgeResults);\n#pdf(outfile||\".pdf\");\n\n## init metarep result matrix\ncolumns = c(\"id\",\"count1\",\"count2\",\"logConc\",\"logFC\",\"disp\",\"p_value\",\"b_value\",\"q_value\");\nmetarepResults = data.frame(matrix(rep(NA,9*nrows),ncol=9),stringsAsFactors=F);\t\t\ncolnames(metarepResults) = columns;\n\n## set metarep result values\nmetarepResults[,1] = features;\nmetarepResults[,2] = cntA;\nmetarepResults[,3] = cntB;\nmetarepResults[,4] = round(edgeResultTable$logConc,4);\nmetarepResults[,5] = round(edgeResultTable$logFC,4);\nmetarepResults[,6] = round(commonDispersion$common.dispersion,4);\nmetarepResults[,7] = round(edgeResultTable$p.value,pvalround);\nmetarepResults[,8] = round(p.adjust(edgeResultTable$p.value, method = \"fdr\"),pvalround);\nmetarepResults[,9] = round(p.adjust(edgeResultTable$p.value, method = \"bonferroni\"),pvalround);\n\n## write results to tab delimites output file\nwrite.table(metarepResults,file=outfile,row.names=F,sep =\"\\t\",eol=\"\\n\",append=F,quote=F);\n\n## exit\nq(status=0)", "meta": {"hexsha": "d85a7a31ae70c367471dcd71a5adf10b47a07f5c", "size": 2728, "ext": "r", "lang": "R", "max_stars_repo_path": "scripts/r/edge_r_test.r", "max_stars_repo_name": "allenlab/PhyloMetarep", "max_stars_repo_head_hexsha": "e586d1a0208d6d5c14701ec6cbc915206dc4aaf1", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scripts/r/edge_r_test.r", "max_issues_repo_name": "allenlab/PhyloMetarep", "max_issues_repo_head_hexsha": "e586d1a0208d6d5c14701ec6cbc915206dc4aaf1", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/r/edge_r_test.r", "max_forks_repo_name": "allenlab/PhyloMetarep", "max_forks_repo_head_hexsha": "e586d1a0208d6d5c14701ec6cbc915206dc4aaf1", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 34.1, "max_line_length": 95, "alphanum_fraction": 0.6946480938, "num_tokens": 751, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239957834733, "lm_q2_score": 0.5156199157230156, "lm_q1q2_score": 0.36888686041209756}} {"text": "stem <- c(\"甲\", \"乙\", \"丙\", \"丁\", \"戊\", \"己\", \"庚\", \"辛\", \"壬\", \"癸\")\nbranch <- c(\"子\", \"丑\", \"寅\", \"卯\", \"辰\", \"巳\", \"午\", \"未\", \"申\", \"酉\", \"戌\", \"亥\")\nstembranch <- function(year) {\n return(paste0(stem[(year-3)%%10], branch[(year-3)%%12]))\n}\n", "meta": {"hexsha": "82757aa57b8d2b67d41efe453a0c5ee421737745", "size": 224, "ext": "r", "lang": "R", "max_stars_repo_path": "stembranch.r", "max_stars_repo_name": "liu-sun/stembranch", "max_stars_repo_head_hexsha": "daa5b32c2a532dbfc796103133fa1657bdc790bf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "stembranch.r", "max_issues_repo_name": "liu-sun/stembranch", "max_issues_repo_head_hexsha": "daa5b32c2a532dbfc796103133fa1657bdc790bf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "stembranch.r", "max_forks_repo_name": "liu-sun/stembranch", "max_forks_repo_head_hexsha": "daa5b32c2a532dbfc796103133fa1657bdc790bf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.3333333333, "max_line_length": 71, "alphanum_fraction": 0.4107142857, "num_tokens": 124, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6513548646660542, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.3686789263911349}} {"text": "########################### BayesKin ###########################\n## Bayesian estimates of rigid body kinematics\n## Andy Pohl\n## UofC - Faculty of Kinesiology\n\n## Written by: Andy Pohl\n## UofC - Faculty of Kinesiology\n## June-Dec 2020\n## Revision 1: April 2021\n################################################################\n\n##################### generate_results.r ###################\n## processes_results table for a batch of simulations\n#############################################################\n\n\n# preliminaries \nrm(list = ls()) # clear workspace\n\nlibrary('dplyr')\nlibrary('latex2exp')\nlibrary('xtable')\nlibrary('coda')\nWORKING_DIR = \"\" # Replace with the location of the BayesKin/src directory on the local PC.\nsetwd(WORKING_DIR)\nRESULTS_DIR = paste0(WORKING_DIR, \"/src/\") # location of results directory\n\nsetwd(RESULTS_DIR)\n# Load results file\n\nFILENAME = \"\" # Filename of .rda result file produced by process_results.r\nresults = readRDS(FILENAME)\nresults = data.frame(results, stringsAsFactors = F)\nresults$model = factor(results$model, levels = c('LS', \"Bayes_p1\", \"Bayes_p2\", \"Bayes_p3\", \"Bayes_p4\", \"Bayes_p5\"))\nresults$parameter = factor(results$parameter, levels = c('r1', \"r2\", \"theta1\", \"theta2\", \"theta3\", \"sigma\"))\n# Convert r/sigma to mm\nresults[results$parameter %in% c('r1', 'r2', 'sigma'),c('est', 'quantile.1', 'quantile.2', 'quantile.3', 'quantile.4', 'quantile.5')] = results[results$parameter %in% c('r1', 'r2', 'sigma'),c('est', 'quantile.1', 'quantile.2', 'quantile.3', 'quantile.4', 'quantile.5')]*1000\n\n# Set constants\nPOSES = c(\"SingleLink\", \"DoubleLink\", \"TripleLink\")\nMODELS = c(\"LS\", \"Bayes_p1\", \"Bayes_p2\", \"Bayes_p3\", \"Bayes_p4\", \"Bayes_p5\")\nPARMS = c(\"r1\", \"r2\", \"theta1\", \"theta2\", \"theta3\", \"sigma\")\nPARMLABS = list(r1=TeX(\"$r_1 \\\\, (mm)$\"), r2=TeX(\"$r_2 \\\\, (mm)$\"), theta1=TeX(\"$\\\\theta_1 \\\\, (^o)$\"), \n theta2=TeX(\"$\\\\theta_2 \\\\, (^o)$\"), theta3=TeX(\"$\\\\theta_3\\\\, (^o) \"), sigma=TeX(\"$\\\\sigma \\\\, (mm)$\"))\nMODELLABS = c(\"LS\", \"Bayes P1\", \"Bayes P2\", \"Bayes P3\", \"Bayes P4\", \"Bayes P5\")\n\nTRUEVALS = list(r1 = 0.07*1000, r2 = 0.03*1000, \n theta1 = -55, theta2 = -110, theta3 = -10, sigma = 1.5/1000 *1000)\n\n################################################################################\n## FILTERING Poor MCMC convergence\n################################################################################\n# identify poor MCMC convergence\nbad_seeds = results %>% group_by(pose) %>% filter(rhat>1.1) %>% select(pose, model, seed) %>% distinct()\nbad_seeds %>% summarise(n_distinct(seed))\n\nresults = results[!((results$seed %in% bad_seeds$seed[bad_seeds$pose == 'SingleLink']) & (results$pose == 'SingleLink')),]\nresults = results[!((results$seed %in% bad_seeds$seed[bad_seeds$pose == 'DoubleLink']) & (results$pose == 'DoubleLink')),]\nresults = results[!((results$seed %in% bad_seeds$seed[bad_seeds$pose == 'TripleLink']) & (results$pose == 'TripleLink')),]\n\n# filter to only 1000 iterations per pose\nresults_temps = results[results$pose =='SingleLink',]\ntemp_seeds = unique(results_temps$seed)\nresults_temps = results_temps[results_temps$seed %in% temp_seeds[1:1000],]\n\nresults_tempd = results[results$pose =='DoubleLink',]\ntemp_seeds = unique(results_tempd$seed)\nresults_tempd = results_tempd[results_tempd$seed %in% temp_seeds[1:1000],]\n\nresults_tempt = results[results$pose =='TripleLink',]\ntemp_seeds = unique(results_tempt$seed)\nresults_tempt = results_tempt[results_tempt$seed %in% temp_seeds[1:1000],]\n\nresults = rbind(results_temps, results_tempd, results_tempt)\n\nresults %>% group_by(pose) %>% summarise(n_distinct(seed))\n\n################################################################################\n## MCMC convergence summary\n################################################################################\n\nMCMC_summary = results %>% filter(model != \"LS\") %>% \n group_by(pose, model, parameter) %>% \n summarise( mean_neff = mean(rhat), sd_neff = sd(rhat))\n\nxtable(MCMC_summary)\n\n\n################################################################################\n## Table 1: Bias, variance, mse and RMSE\n################################################################################\n\ntab1 = results %>% group_by(pose, model, parameter) %>% summarize(bias = mean(est), var = sd(est)^2)\n\nparms = c(\"r1\", \"r2\", \"theta1\", \"theta2\", \"theta3\", \"sigma\")\nfor(i in 1:length(parms)){\n tab1$bias[tab1$parameter == parms[i]] = tab1$bias[tab1$parameter == parms[i]] - TRUEVALS[[parms[i]]]\n}\ntab1$bias[tab1$parameter %in% c('r1', 'r2', 'sigma')] = tab1$bias[tab1$parameter %in% c('r1', 'r2', 'sigma')] \ntab1$mse = tab1$bias^2 + tab1$var\ntab1$rmse = sqrt(tab1$mse)\n\n\nprint(xtable(tab1[,c('pose', 'model', 'parameter', 'rmse')], digits = 3), include.rowname=F)\n\n################################################################################\n## FIGURE 1 strip charts\n################################################################################\ndeltadeg = 2\ndeltar = .02 *1000\naxislimits = list(r1 = TRUEVALS[[1]] + c(-deltar, deltar),\n r2 = TRUEVALS[[2]] + c(-deltar, deltar),\n theta1 = TRUEVALS[[3]] + c(-deltadeg, deltadeg),\n theta2 = TRUEVALS[[4]] + c(-deltadeg, deltadeg),\n theta3 = TRUEVALS[[5]] + c(-deltadeg, deltadeg),\n sigma = c(0, 0.01))\naxislimits$sigma = axislimits$sigma*1000\n\ncolors = list(grey = rgb(97/255, 97/255,97/255, 0.2),\n orange = rgb(241/255, 136/255,5/255, 1),\n blue = rgb(18/255, 78/255,120/255, 0.2),\n red = rgb(162/255, 0/255,33/255, 0.2),\n green = rgb(76/255, 159/255, 112/255, 0.2),\n purple = rgb(217/255, 187/255, 249/255, 0.2),\n pink = rgb(217/255, 3/255, 104/255, 0.2))\n\npoint_cols = list(colors$pink, colors$blue, colors$green, colors$purple)\n\n# Adjust the following to choose what is plotted in the nparmsx4 grid of plots.\nMODELS = c(\"LS\", \"Bayes_p1\", \"Bayes_p2\", \"Bayes_p3\")\nMODELLABS = c(\"LS\", \"Bayes P1\", \"Bayes P2\", \"Bayes P3\")\n################################################################################\n## Single Link\n################################################################################\nsl_results = results %>% filter(pose == 'SingleLink')\npar(mfcol = c(4,4), mar = c(3, 1, 1,1), mgp = c(2,0.5,0), cex.lab = 1.2, cex.main = 1.2)\nfor(i in 1:length(MODELS)){\n m_results = sl_results %>% filter(model == MODELS[i])\n ps = unique(m_results$parameter)\n for(j in 1:length(ps)){\n est = m_results %>% filter(parameter == ps[j]) %>% select(est)\n if(j ==1){\n plot(x = est[,1], y = runif(length(est[,1]), 0, 0.1), \n xlim = get(as.character(ps[j]),axislimits), ylim = c(-0.03,0.25), \n pch = 16, col = point_cols[[i]],\n xlab = get(as.character(ps[j]),PARMLABS),\n ylab =NA, yaxt='n', bty = 'n',\n main = MODELLABS[i])\n }else{\n plot(x = est[,1], y = runif(length(est[,1]), 0, 0.1), \n xlim = get(as.character(ps[j]),axislimits), ylim = c(-0.03,0.25), \n pch = 16, col = point_cols[[i]],\n xlab = get(as.character(ps[j]),PARMLABS), bty = 'n',\n ylab =NA, yaxt='n')\n }\n \n segments(x0=TRUEVALS[[ps[j]]], y0=-0.02, x1=TRUEVALS[[ps[j]]], y1=0.12, col = colors$orange, lwd=1.5)\n }\n}\n\n################################################################################\n## Double Link\n################################################################################\nsl_results = results %>% filter(pose == 'DoubleLink')\npar(mfcol = c(5,4), mar = c(3, 1, 1,1), mgp = c(2,0.5,0), cex.lab = 1.2, cex.main = 1.2)\nfor(i in 1:length(MODELS)){\n m_results = sl_results %>% filter(model == MODELS[i])\n ps = unique(m_results$parameter)\n for(j in 1:length(ps)){\n est = m_results %>% filter(parameter == ps[j]) %>% select(est)\n if(j ==1){\n plot(x = est[,1], y = runif(length(est[,1]), 0, 0.1), \n xlim = get(as.character(ps[j]),axislimits), ylim = c(-0.03,0.25), \n pch = 16, col = point_cols[[i]],\n xlab = get(as.character(ps[j]),PARMLABS), ylab =NA, yaxt='n', bty = 'n',\n main = MODELLABS[i])\n }else{\n plot(x = est[,1], y = runif(length(est[,1]), 0, 0.1), \n xlim = get(as.character(ps[j]),axislimits),ylim = c(-0.03,0.25), \n pch = 16, col = point_cols[[i]],\n xlab = get(as.character(ps[j]),PARMLABS), ylab =NA, yaxt='n', bty = 'n')\n }\n \n segments(x0=TRUEVALS[[ps[j]]], y0=-0.02, x1=TRUEVALS[[ps[j]]], y1=0.12, col = colors$orange, lwd=1.5)\n }\n}\n\n################################################################################\n## Triple Link\n################################################################################\nsl_results = results %>% filter(pose == 'TripleLink')\npar(mfcol = c(6,4), mar = c(3, 1, 1,1), mgp = c(2,0.5,0), cex.lab = 1.2, cex.main = 1.2)\nfor(i in 1:length(MODELS)){\n m_results = sl_results %>% filter(model == MODELS[i])\n ps = unique(m_results$parameter)\n for(j in 1:length(ps)){\n est = m_results %>% filter(parameter == ps[j]) %>% select(est)\n if(j ==1){\n plot(x = est[,1], y = runif(length(est[,1]), 0, 0.1), \n xlim = get(as.character(ps[j]),axislimits), ylim = c(-0.03,0.25), \n pch = 16, col = point_cols[[i]],\n xlab = get(as.character(ps[j]),PARMLABS), ylab =NA, yaxt='n', bty = 'n',\n main = MODELLABS[i])\n }else{\n plot(x = est[,1], y = runif(length(est[,1]), 0, 0.1),\n xlim = get(as.character(ps[j]),axislimits), ylim = c(-0.03,0.25), \n pch = 16, col = point_cols[[i]],\n xlab = get(as.character(ps[j]),PARMLABS), ylab =NA, yaxt='n', bty = 'n')\n }\n segments(x0=TRUEVALS[[ps[j]]], y0=-0.02, x1=TRUEVALS[[ps[j]]], y1=0.12, col = colors$orange, lwd=1.5)\n }\n}\n\n\n################################################################################\n## Table 2: EQULIIVANCE\n################################################################################\n\n## Prior 1\np1 = results %>% filter(model =='Bayes_p1' )\nBayes_perf = data.frame(seed = numeric(), pose = character(), model = character(), parameter = character(), \n equilivance_ls = numeric(), equilivance_true = numeric(),outperformed = numeric())\nfor(i in 1:length(POSES)){\n temp = p1 %>% filter(pose == POSES[i])\n ps = unique(temp$parameter)\n for(j in 1:length(ps)){\n print(sprintf(\"Computing Pose %s, parameter: %s\", POSES[i], ps[j]))\n temp1 = temp %>% filter(parameter == ps[j])\n seeds = unique(temp1$seed)\n for(k in 1:length(seeds)){\n tmpseed = seeds[k]\n print(sprintf(\" seed: %s\", as.character(tmpseed)))\n \n ls_est = results %>% filter(seed == tmpseed, parameter == ps[j], pose == POSES[i], model == 'LS') %>% select(est)\n bayes_est = results %>% filter(seed == tmpseed, parameter == ps[j], pose == POSES[i], model == 'Bayes_p1') %>% select(est)\n \n # Equilivance of Bayes and LS\n if((temp$est[k] - (2* temp1$ts_se[k]) < ls_est) &(temp1$est[k] + (2* temp1$ts_se[k]) > ls_est)){\n tmpcvgls = 1\n } else{\n tmpcvgls =0\n }\n \n # equilivance of Bayes and True Val\n if((temp$est[k] - (2* temp1$ts_se[k]) < TRUEVALS[[ps[j]]]) &(temp1$est[k] + (2* temp1$ts_se[k]) > TRUEVALS[[ps[j]]])){\n tmpcvgtrue = 1\n } else{\n tmpcvgtrue =0\n }\n \n \n tmpimprv = as.numeric((abs(bayes_est - TRUEVALS[[ps[j]]])) < (abs(ls_est - TRUEVALS[[ps[j]]])))\n \n toappend = data.frame(seed = tmpseed, pose = POSES[i], model = \"Bayes_p1\", parameter = ps[j], \n equilivance_ls = tmpcvgls, equilivance_true = tmpcvgtrue, outperformed = tmpimprv)\n Bayes_perf = rbind(Bayes_perf, toappend)\n \n }\n \n }\n}\n\nBayes_perf_p1 = Bayes_perf %>% group_by(pose, model, parameter) %>% summarize(equilivance_ls = mean(equilivance_ls), equilivance_true = mean(equilivance_true),\n perf = mean(outperformed))\n\n## Prior 2\np2 = results %>% filter(model =='Bayes_p2' )\nBayes_perf = data.frame(seed = numeric(), pose = character(), model = character(), parameter = character(), \n equilivance_ls = numeric(), equilivance_true = numeric(),outperformed = numeric())\nfor(i in 1:length(POSES)){\n temp = p2 %>% filter(pose == POSES[i])\n ps = unique(temp$parameter)\n for(j in 1:length(ps)){\n print(sprintf(\"Computing Pose %s, parameter: %s\", POSES[i], ps[j]))\n temp1 = temp %>% filter(parameter == ps[j])\n seeds = unique(temp1$seed)\n for(k in 1:length(seeds)){\n tmpseed = seeds[k]\n print(sprintf(\" seed: %s\", as.character(tmpseed)))\n \n ls_est = results %>% filter(seed == tmpseed, parameter == ps[j], pose == POSES[i], model == 'LS') %>% select(est)\n bayes_est = results %>% filter(seed == tmpseed, parameter == ps[j], pose == POSES[i], model == 'Bayes_p2') %>% select(est)\n \n # Equilivance of Bayes and LS\n if((temp$est[k] - (2* temp1$ts_se[k]) < ls_est) &(temp1$est[k] + (2* temp1$ts_se[k]) > ls_est)){\n tmpcvgls = 1\n } else{\n tmpcvgls =0\n }\n \n # equilivance of Bayes and True Val\n if((temp$est[k] - (2* temp1$ts_se[k]) < TRUEVALS[[ps[j]]]) &(temp1$est[k] + (2* temp1$ts_se[k]) > TRUEVALS[[ps[j]]])){\n tmpcvgtrue = 1\n } else{\n tmpcvgtrue =0\n }\n \n \n tmpimprv = as.numeric((abs(bayes_est - TRUEVALS[[ps[j]]])) < (abs(ls_est - TRUEVALS[[ps[j]]])))\n \n toappend = data.frame(seed = tmpseed, pose = POSES[i], model = \"Bayes_p2\", parameter = ps[j], \n equilivance_ls = tmpcvgls, equilivance_true = tmpcvgtrue, outperformed = tmpimprv)\n Bayes_perf = rbind(Bayes_perf, toappend)\n \n }\n \n }\n}\n\nBayes_perf_p2 = Bayes_perf %>% group_by(pose, model, parameter) %>% summarize(equilivance_ls = mean(equilivance_ls), equilivance_true = mean(equilivance_true),\n perf = mean(outperformed))\n\n## Prior 3\np3 = results %>% filter(model =='Bayes_p3' )\nBayes_perf = data.frame(seed = numeric(), pose = character(), model = character(), parameter = character(), \n equilivance_ls = numeric(), equilivance_true = numeric(),outperformed = numeric())\nfor(i in 1:length(POSES)){\n temp = p3 %>% filter(pose == POSES[i])\n ps = unique(temp$parameter)\n for(j in 1:length(ps)){\n print(sprintf(\"Computing Pose %s, parameter: %s\", POSES[i], ps[j]))\n temp1 = temp %>% filter(parameter == ps[j])\n seeds = unique(temp1$seed)\n for(k in 1:length(seeds)){\n tmpseed = seeds[k]\n print(sprintf(\" seed: %s\", as.character(tmpseed)))\n \n ls_est = results %>% filter(seed == tmpseed, parameter == ps[j], pose == POSES[i], model == 'LS') %>% select(est)\n bayes_est = results %>% filter(seed == tmpseed, parameter == ps[j], pose == POSES[i], model == 'Bayes_p3') %>% select(est)\n \n # Equilivance of Bayes and LS\n if((temp$est[k] - (2* temp1$ts_se[k]) < ls_est) &(temp1$est[k] + (2* temp1$ts_se[k]) > ls_est)){\n tmpcvgls = 1\n } else{\n tmpcvgls =0\n }\n \n # equilivance of Bayes and True Val\n if((temp$est[k] - (2* temp1$ts_se[k]) < TRUEVALS[[ps[j]]]) &(temp1$est[k] + (2* temp1$ts_se[k]) > TRUEVALS[[ps[j]]])){\n tmpcvgtrue = 1\n } else{\n tmpcvgtrue =0\n }\n \n \n tmpimprv = as.numeric((abs(bayes_est - TRUEVALS[[ps[j]]])) < (abs(ls_est - TRUEVALS[[ps[j]]])))\n \n toappend = data.frame(seed = tmpseed, pose = POSES[i], model = \"Bayes_p3\", parameter = ps[j], \n equilivance_ls = tmpcvgls, equilivance_true = tmpcvgtrue, outperformed = tmpimprv)\n Bayes_perf = rbind(Bayes_perf, toappend)\n \n }\n \n }\n}\n\nBayes_perf_p3 = Bayes_perf %>% group_by(pose, model, parameter) %>% summarize(equilivance_ls = mean(equilivance_ls), equilivance_true = mean(equilivance_true),\n perf = mean(outperformed))\n\n## Prior 4\np4 = results %>% filter(model =='Bayes_p4' )\nBayes_perf = data.frame(seed = numeric(), pose = character(), model = character(), parameter = character(), \n equilivance_ls = numeric(), equilivance_true = numeric(),outperformed = numeric())\nfor(i in 1:length(POSES)){\n temp = p4 %>% filter(pose == POSES[i])\n ps = unique(temp$parameter)\n for(j in 1:length(ps)){\n print(sprintf(\"Computing Pose %s, parameter: %s\", POSES[i], ps[j]))\n temp1 = temp %>% filter(parameter == ps[j])\n seeds = unique(temp1$seed)\n for(k in 1:length(seeds)){\n tmpseed = seeds[k]\n print(sprintf(\" seed: %s\", as.character(tmpseed)))\n \n ls_est = results %>% filter(seed == tmpseed, parameter == ps[j], pose == POSES[i], model == 'LS') %>% select(est)\n bayes_est = results %>% filter(seed == tmpseed, parameter == ps[j], pose == POSES[i], model == 'Bayes_p4') %>% select(est)\n \n # Equilivance of Bayes and LS\n if((temp$est[k] - (2* temp1$ts_se[k]) < ls_est) &(temp1$est[k] + (2* temp1$ts_se[k]) > ls_est)){\n tmpcvgls = 1\n } else{\n tmpcvgls =0\n }\n \n # equilivance of Bayes and True Val\n if((temp$est[k] - (2* temp1$ts_se[k]) < TRUEVALS[[ps[j]]]) &(temp1$est[k] + (2* temp1$ts_se[k]) > TRUEVALS[[ps[j]]])){\n tmpcvgtrue = 1\n } else{\n tmpcvgtrue =0\n }\n \n \n tmpimprv = as.numeric((abs(bayes_est - TRUEVALS[[ps[j]]])) < (abs(ls_est - TRUEVALS[[ps[j]]])))\n \n toappend = data.frame(seed = tmpseed, pose = POSES[i], model = \"Bayes_p4\", parameter = ps[j], \n equilivance_ls = tmpcvgls, equilivance_true = tmpcvgtrue, outperformed = tmpimprv)\n Bayes_perf = rbind(Bayes_perf, toappend)\n \n }\n \n }\n}\n\nBayes_perf_p4 = Bayes_perf %>% group_by(pose, model, parameter) %>% summarize(equilivance_ls = mean(equilivance_ls), equilivance_true = mean(equilivance_true),\n perf = mean(outperformed))\n\n## Prior 5\np5 = results %>% filter(model =='Bayes_p5' )\nBayes_perf = data.frame(seed = numeric(), pose = character(), model = character(), parameter = character(), \n equilivance_ls = numeric(), equilivance_true = numeric(),outperformed = numeric())\nfor(i in 1:length(POSES)){\n temp = p5 %>% filter(pose == POSES[i])\n ps = unique(temp$parameter)\n for(j in 1:length(ps)){\n print(sprintf(\"Computing Pose %s, parameter: %s\", POSES[i], ps[j]))\n temp1 = temp %>% filter(parameter == ps[j])\n seeds = unique(temp1$seed)\n for(k in 1:length(seeds)){\n tmpseed = seeds[k]\n print(sprintf(\" seed: %s\", as.character(tmpseed)))\n \n ls_est = results %>% filter(seed == tmpseed, parameter == ps[j], pose == POSES[i], model == 'LS') %>% select(est)\n bayes_est = results %>% filter(seed == tmpseed, parameter == ps[j], pose == POSES[i], model == 'Bayes_p5') %>% select(est)\n \n # Equilivance of Bayes and LS\n if((temp$est[k] - (2* temp1$ts_se[k]) < ls_est) &(temp1$est[k] + (2* temp1$ts_se[k]) > ls_est)){\n tmpcvgls = 1\n } else{\n tmpcvgls =0\n }\n \n # equilivance of Bayes and True Val\n if((temp$est[k] - (2* temp1$ts_se[k]) < TRUEVALS[[ps[j]]]) &(temp1$est[k] + (2* temp1$ts_se[k]) > TRUEVALS[[ps[j]]])){\n tmpcvgtrue = 1\n } else{\n tmpcvgtrue =0\n }\n \n \n tmpimprv = as.numeric((abs(bayes_est - TRUEVALS[[ps[j]]])) < (abs(ls_est - TRUEVALS[[ps[j]]])))\n \n toappend = data.frame(seed = tmpseed, pose = POSES[i], model = \"Bayes_p5\", parameter = ps[j], \n equilivance_ls = tmpcvgls, equilivance_true = tmpcvgtrue, outperformed = tmpimprv)\n Bayes_perf = rbind(Bayes_perf, toappend)\n \n }\n \n }\n}\n\nBayes_perf_p5 = Bayes_perf %>% group_by(pose, model, parameter) %>% summarize(equilivance_ls = mean(equilivance_ls), equilivance_true = mean(equilivance_true),\n perf = mean(outperformed))\nBayes_perf = rbind(Bayes_perf_p1, Bayes_perf_p2, Bayes_perf_p3, Bayes_perf_p4, Bayes_perf_p5)\n\nBayes_perf\n\n\n################################################################################\n## Computational time.\n################################################################################\ncomp_time = results %>% select(pose, seed, model, run_time) %>% group_by(pose, model) \ncomp_time = unique(comp_time)\ncomp_time = comp_time %>% summarise(run_time_mean = mean(run_time), run_time_sd = sd(run_time))\n\n# temp = Bayes_perf %>% group_by(pose, model, parameter) %>% summarise(equilivance = mean(coverage), perf = mean(outperformed))\nxtable(comp_time, digits = 2)\n\n\n#####################################################################################\n## Plot likelihoods\n#####################################################################################\nsource('./library.r')\n\nset.seed(4)\n\n## 1) Specify parameters\nn.links = 3 # Number of links.\nseg.length = c(0.45, 0.35, 0.25) # Length of segment specified in m. NB: Pataky pg 2.\nr_true = c(0.07, 0.03) # Origin location in m.\ntheta_true = c(-55, -110, -10) # Rotation angle in deg. NB: specified to avoid 0/360 issue\n# and mirroring solutions.\nsigma_true = 1.5/1000 # Measurement noise in m. NB Noise specified as 1.5mm\n# midpoint of range explored by Pataky et al.\ntrue_vals = c(r_true = r_true, theta_true = theta_true, sigma_true = sigma_true)\n\n\n# Generate posture\nlinks = list(gen_link(seg.length = seg.length[1],\n plate.center = 0.7*seg.length[1]),\n gen_link(seg.length = seg.length[2],\n plate.center = 0.5*seg.length[2]),\n gen_link(seg.length = seg.length[3],\n plate.center = 0.5*seg.length[3]))\nposture = gen_posture(links, r = r_true, theta = theta_true)\ny = gen_obs(posture, sigma_true)\n\nLS_result = LS_soln(y, links, \n inits = true_vals,\n init_type = 'random' )\ninits = c(0.0446749866008758, 0.012961977859959, -40.1004006620497, 88.534386176616, 142.351554371417)\n# lik for r\nrs = seq(-1, 1, by = 0.01)\ncosts = matrix(NA, nrow = length(rs), ncol = length(rs))\nfor(i in 1:length(rs)){\n for(j in 1:length(rs)){\n costs[i,j] = cost(params = c(rs[i], rs[j], true_vals[3:5]), y =y, links = links)\n }\n}\n\nfilled.contour(x=rs, y = rs, z=costs, \n color = function(n) rev(hcl.colors(n, \"Spectral\")),\n main = 'Cost for R', xlab = 'r1', ylab = 'r2', nlevels = 30,\n plot.axes={points(true_vals[1], true_vals[2], pch = 3, col = 'green')\n points(LS_result$r.hat[1], LS_result$r.hat[2], pch = 3, col = 'blue')\n points(inits[1], inits[2], pch = 3, col = 'black')\n axis(1, seq(-1, 1, by = 0.1))\n axis(2, seq(-1, 1, by = 0.1))})\n\n# lik for theta 1 vs 2\nthetas = seq(-360, 360, by = 1)\ncosts = matrix(NA, nrow = length(thetas), ncol = length(thetas))\nfor(i in 1:length(thetas)){\n for(j in 1:length(thetas)){\n costs[i,j] = cost(params = c(true_vals[1:2], thetas[i], thetas[j], true_vals[5]), y =y, links = links)\n }\n}\n\nfilled.contour(x=thetas, y = thetas, z=costs, \n color = function(n) rev(hcl.colors(n, \"Spectral\")),\n main = 'Cost for theta', xlab = 'theta1', ylab = 'theta2', nlevels = 30,\n plot.axes={points(true_vals[3], true_vals[4], pch = 3, col = 'green')\n points(LS_result$theta.hat[1], LS_result$theta.hat[2], pch = 3, col = 'blue')\n points(inits[3], inits[4], pch = 3, col = 'black')\n axis(1, seq(-360, 360, by = 45))\n axis(2, seq(-360, 360, by = 45))})\n\n\n# lik for theta 2 vs 3\nthetasi = seq(-135, 135, length.out = 500)\nthetasj = seq(-45, 270, length.out = 500)\n\ncosts = matrix(NA, nrow = length(thetasi), ncol = length(thetasj))\nfor(i in 1:length(thetasi)){\n for(j in 1:length(thetasj)){\n costs[i,j] = cost(params = c(true_vals[1:3], thetasi[i], thetasj[j]), y=y, links = links)\n }\n}\n\nfilled.contour(x=thetasi, y = thetasj, z=costs, \n color = function(n) rev(hcl.colors(n, \"Spectral\")),\n main = \"LS Cost\", xlab = TeX('$\\\\theta_2$'), ylab = TeX('$\\\\theta_3$'), nlevels = 30,\n plot.axes={points(true_vals[4], true_vals[5], pch = 19, col = rgb(241/255, 136/255,5/255, 1))\n points(LS_result$theta.hat[2], LS_result$theta.hat[3], pch = 19, col = rgb(217/255, 3/255, 104/255, 1))\n points(inits[4], inits[5], pch = 19, col = 'black')\n axis(1, seq(-135, 135, by = 45))\n axis(2, seq(-45, 270, by = 45))})\n\n\n\n## lik for sigma\nsigmas = seq(1e-3, 1, length.out = 10000)\nlls = rep(NA, length(sigmas))\nfor(i in 1:length(sigmas)){\n lls[i] = loglikelihood(hat = c(true_vals[1:5], log(sigmas[i])), y=y, links = links)\n}\n\nplot(x = log(sigmas), y=lls, type = 'l', main = 'LL for sigma', xlab = 'log(sigma)')\nabline(v=log(true_vals[6]), col = 'red')\n\n\n\nplot_system(posture, y)\nposture_hat = gen_posture(links = links, r = LS_result$r.hat, theta = LS_result$theta.hat)\nplot_system(posture_hat, y, add=T)\n\n", "meta": {"hexsha": "8a2f0792aace54c6a23425c90b570434a5e39002", "size": 26668, "ext": "r", "lang": "R", "max_stars_repo_path": "src/analyse_results.r", "max_stars_repo_name": "AndyPohlNZ/BayesKin", "max_stars_repo_head_hexsha": "1eac3d30f09491d8b371a433e4621a53a2b5d2ef", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/analyse_results.r", "max_issues_repo_name": "AndyPohlNZ/BayesKin", "max_issues_repo_head_hexsha": "1eac3d30f09491d8b371a433e4621a53a2b5d2ef", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/analyse_results.r", "max_forks_repo_name": "AndyPohlNZ/BayesKin", "max_forks_repo_head_hexsha": "1eac3d30f09491d8b371a433e4621a53a2b5d2ef", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.2986111111, "max_line_length": 274, "alphanum_fraction": 0.5112869357, "num_tokens": 7700, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5506073655352404, "lm_q2_score": 0.6688802669716107, "lm_q1q2_score": 0.36829040165574684}} {"text": "model_updatephase <- function (cumulTT = 354.582294511779,\n leafNumber_t1 = 4.620511621863958,\n cumulTTFromZC_39 = 0.0,\n isMomentRegistredZC_39 = 0,\n gAI = 0.3255196285135,\n grainCumulTT = 0.0,\n dayLength = 12.7433275303389,\n vernaprog = 1.0532526829571554,\n minFinalNumber = 6.879410413987549,\n fixPhyll = 91.2,\n isVernalizable = 1,\n dse = 105.0,\n pFLLAnth = 2.22,\n dcd = 100.0,\n dgf = 450.0,\n degfm = 0.0,\n maxDL = 15.0,\n sLDL = 0.85,\n ignoreGrainMaturation = FALSE,\n pHEADANTH = 1.0,\n choosePhyllUse = 'Default',\n p = 120.0,\n phase_t1 = 1.0,\n cumulTTFromZC_91 = 0.0,\n phyllochron = 91.2,\n hasLastPrimordiumAppeared_t1 = 0,\n finalLeafNumber_t1 = 0.0){\n #'- Name: UpdatePhase -Version: 1.0, -Time step: 1\n #'- Description:\n #' * Title: UpdatePhase Model\n #' * Author: Pierre MARTRE\n #' * Reference: Modeling development phase in the \n #' Wheat Simulation Model SiriusQuality.\n #' See documentation at http://www1.clermont.inra.fr/siriusquality/?page_id=427\n #' * Institution: INRA Montpellier\n #' * Abstract: This strategy advances the phase and calculate the final leaf number\n #' \t\n #'- inputs:\n #' * name: cumulTT\n #' ** description : cumul thermal times at current date\n #' ** variablecategory : auxiliary\n #' ** datatype : DOUBLE\n #' ** min : -200\n #' ** max : 10000\n #' ** default : 354.582294511779\n #' ** unit : °C d\n #' ** inputtype : variable\n #' * name: leafNumber_t1\n #' ** description : Actual number of phytomers\n #' ** variablecategory : state\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 25\n #' ** default : 4.620511621863958\n #' ** unit : leaf\n #' ** inputtype : variable\n #' * name: cumulTTFromZC_39\n #' ** description : cumul of the thermal time ( DeltaTT) since the moment ZC_39\n #' ** variablecategory : auxiliary\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 10000\n #' ** default : 0\n #' ** unit : °C d-1\n #' ** inputtype : variable\n #' * name: isMomentRegistredZC_39\n #' ** description : true if ZC_39 is registered in the calendar\n #' ** variablecategory : state\n #' ** datatype : INT\n #' ** min : 0\n #' ** max : 1\n #' ** default : 0\n #' ** unit : \n #' ** inputtype : variable\n #' * name: gAI\n #' ** description : used to calculate Terminal spikelet\n #' ** variablecategory : auxiliary\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 10000\n #' ** default : 0.3255196285135\n #' ** unit : \n #' ** inputtype : variable\n #' * name: grainCumulTT\n #' ** description : cumulTT used for the grain developpment\n #' ** variablecategory : auxiliary\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 10000\n #' ** default : 0\n #' ** unit : °C d\n #' ** inputtype : variable\n #' * name: dayLength\n #' ** description : length of the day\n #' ** datatype : DOUBLE\n #' ** variablecategory : auxiliary\n #' ** min : 0\n #' ** max : 24\n #' ** unit : h\n #' ** default : 12.7433275303389\n #' ** inputtype : variable\n #' * name: vernaprog\n #' ** description : progression on a 0 to 1 scale of the vernalization\n #' ** variablecategory : state\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 10\n #' ** default : 1.0532526829571554\n #' ** unit : \n #' ** inputtype : variable\n #' * name: minFinalNumber\n #' ** description : minimum final leaf number\n #' ** variablecategory : state\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 25\n #' ** default : 6.879410413987549\n #' ** unit : leaf\n #' ** inputtype : variable\n #' * name: fixPhyll\n #' ** description : Phyllochron with sowing date fix\n #' ** variablecategory : auxiliary\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 10000\n #' ** default : 91.2\n #' ** unit : °C d\n #' ** inputtype : variable\n #' * name: isVernalizable\n #' ** description : true if the plant is vernalizable\n #' ** parametercategory : species\n #' ** datatype : INT\n #' ** min : 0\n #' ** max : 1\n #' ** unit : \n #' ** default : 1\n #' ** inputtype : parameter\n #' * name: dse\n #' ** description : Thermal time from sowing to emergence\n #' ** parametercategory : genotypic\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 1000\n #' ** default : 105\n #' ** unit : °C d\n #' ** inputtype : parameter\n #' * name: pFLLAnth\n #' ** description : Phyllochronic duration of the period between flag leaf ligule appearance and anthesis\n #' ** parametercategory : species\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 1000\n #' ** unit : \n #' ** default : 2.22\n #' ** inputtype : parameter\n #' * name: dcd\n #' ** description : Duration of the endosperm cell division phase\n #' ** parametercategory : species\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 10000\n #' ** default : 100\n #' ** unit : °C d\n #' ** inputtype : parameter\n #' * name: dgf\n #' ** description : Grain filling duration (from anthesis to physiological maturity)\n #' ** parametercategory : species\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 10000\n #' ** default : 450\n #' ** unit : °C d\n #' ** inputtype : parameter\n #' * name: degfm\n #' ** description : Grain maturation duration (from physiological maturity to harvest ripeness)\n #' ** parametercategory : species\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 50\n #' ** default : 0\n #' ** unit : °C d\n #' ** inputtype : parameter\n #' * name: maxDL\n #' ** description : Saturating photoperiod above which final leaf number is not influenced by daylength\n #' ** parametercategory : species\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 24\n #' ** default : 15\n #' ** unit : h\n #' ** inputtype : parameter\n #' * name: sLDL\n #' ** description : Daylength response of leaf production\n #' ** parametercategory : species\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 1\n #' ** default : 0.85\n #' ** unit : leaf h-1\n #' ** inputtype : parameter\n #' * name: ignoreGrainMaturation\n #' ** description : true to ignore grain maturation\n #' ** parametercategory : species\n #' ** datatype : BOOLEAN\n #' ** default : FALSE\n #' ** unit : \n #' ** inputtype : parameter\n #' * name: pHEADANTH\n #' ** description : Number of phyllochron between heading and anthesiss\n #' ** parametercategory : species\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 1000\n #' ** default : 1\n #' ** unit : \n #' ** inputtype : parameter\n #' * name: choosePhyllUse\n #' ** description : Switch to choose the type of phyllochron calculation to be used\n #' ** parametercategory : species\n #' ** datatype : STRING\n #' ** unit : \n #' ** default : Default\n #' ** inputtype : parameter\n #' * name: p\n #' ** description : Phyllochron (Varietal parameter)\n #' ** parametercategory : species\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 1000\n #' ** default : 120\n #' ** unit : °C d leaf-1\n #' ** inputtype : parameter\n #' * name: phase_t1\n #' ** description : the name of the phase\n #' ** variablecategory : state\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 7\n #' ** default : 1\n #' ** unit : \n #' ** inputtype : variable\n #' * name: cumulTTFromZC_91\n #' ** description : cumul of the thermal time (DeltaTT) since the moment ZC_91\n #' ** variablecategory : auxiliary\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 5000\n #' ** default : 0\n #' ** unit : °C d-1\n #' ** inputtype : variable\n #' * name: phyllochron\n #' ** description : Phyllochron\n #' ** variablecategory : state\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 1000\n #' ** default : 91.2\n #' ** unit : °C d leaf-1\n #' ** inputtype : variable\n #' * name: hasLastPrimordiumAppeared_t1\n #' ** description : if Last Primordium has Appeared\n #' ** variablecategory : state\n #' ** datatype : INT\n #' ** min : 0\n #' ** max : 1\n #' ** default : 0\n #' ** unit : \n #' ** inputtype : variable\n #' * name: finalLeafNumber_t1\n #' ** description : final leaf number\n #' ** variablecategory : state\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 25\n #' ** default : 0\n #' ** unit : leaf\n #' ** inputtype : variable\n #'- outputs:\n #' * name: finalLeafNumber\n #' ** description : final leaf number\n #' ** variablecategory : state\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 25\n #' ** unit : leaf\n #' * name: phase\n #' ** description : the name of the phase\n #' ** variablecategory : state\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 7\n #' ** unit : \n #' * name: hasLastPrimordiumAppeared\n #' ** description : if Last Primordium has Appeared\n #' ** variablecategory : state\n #' ** datatype : INT\n #' ** min : 0\n #' ** max : 1\n #' ** unit : \n hasLastPrimordiumAppeared <- hasLastPrimordiumAppeared_t1\n finalLeafNumber <- finalLeafNumber_t1\n phase <- phase_t1\n if (phase_t1 >= 0.0 && phase_t1 < 1.0)\n {\n if (cumulTT >= dse)\n {\n phase <- 1.0\n }\n else\n {\n phase <- phase_t1\n }\n }\n else if ( phase_t1 >= 1.0 && phase_t1 < 2.0)\n {\n if (isVernalizable == 1 && vernaprog >= 1.0 || isVernalizable == 0)\n {\n if (dayLength > maxDL)\n {\n finalLeafNumber <- minFinalNumber\n hasLastPrimordiumAppeared <- 1\n }\n else\n {\n appFLN <- minFinalNumber + (sLDL * (maxDL - dayLength))\n if (appFLN / 2.0 <= leafNumber_t1)\n {\n finalLeafNumber <- appFLN\n hasLastPrimordiumAppeared <- 1\n }\n else\n {\n phase <- phase_t1\n }\n }\n if (hasLastPrimordiumAppeared == 1)\n {\n phase <- 2.0\n }\n }\n else\n {\n phase <- phase_t1\n }\n }\n else if ( phase_t1 >= 2.0 && phase_t1 < 4.0)\n {\n if (isMomentRegistredZC_39 == 1)\n {\n if (phase_t1 < 3.0)\n {\n ttFromLastLeafToHeading <- 0.0\n if (choosePhyllUse == 'Default')\n {\n ttFromLastLeafToHeading <- (pFLLAnth - pHEADANTH) * fixPhyll\n }\n else if ( choosePhyllUse == 'PTQ')\n {\n ttFromLastLeafToHeading <- (pFLLAnth - pHEADANTH) * phyllochron\n }\n else if ( choosePhyllUse == 'Test')\n {\n ttFromLastLeafToHeading <- (pFLLAnth - pHEADANTH) * p\n }\n if (cumulTTFromZC_39 >= ttFromLastLeafToHeading)\n {\n phase <- 3.0\n }\n else\n {\n phase <- phase_t1\n }\n }\n else\n {\n phase <- phase_t1\n }\n ttFromLastLeafToAnthesis <- 0.0\n if (choosePhyllUse == 'Default')\n {\n ttFromLastLeafToAnthesis <- pFLLAnth * fixPhyll\n }\n else if ( choosePhyllUse == 'PTQ')\n {\n ttFromLastLeafToAnthesis <- pFLLAnth * phyllochron\n }\n else if ( choosePhyllUse == 'Test')\n {\n ttFromLastLeafToAnthesis <- pFLLAnth * p\n }\n if (cumulTTFromZC_39 >= ttFromLastLeafToAnthesis)\n {\n phase <- 4.0\n }\n }\n else\n {\n phase <- phase_t1\n }\n }\n else if ( phase_t1 == 4.0)\n {\n if (grainCumulTT >= dcd)\n {\n phase <- 4.5\n }\n else\n {\n phase <- phase_t1\n }\n }\n else if ( phase_t1 == 4.5)\n {\n if (grainCumulTT >= dgf || gAI <= 0.0)\n {\n phase <- 5.0\n }\n else\n {\n phase <- phase_t1\n }\n }\n else if ( phase_t1 >= 5.0 && phase_t1 < 6.0)\n {\n localDegfm <- degfm\n if (ignoreGrainMaturation)\n {\n localDegfm <- -1.0\n }\n if (cumulTTFromZC_91 >= localDegfm)\n {\n phase <- 6.0\n }\n else\n {\n phase <- phase_t1\n }\n }\n else if ( phase_t1 >= 6.0 && phase_t1 < 7.0)\n {\n phase <- phase_t1\n }\n return (list (\"finalLeafNumber\" = finalLeafNumber,\"phase\" = phase,\"hasLastPrimordiumAppeared\" = hasLastPrimordiumAppeared))\n}", "meta": {"hexsha": "5b0470b359b3ff229c82c98c0e8e59be607c26a2", "size": 19293, "ext": "r", "lang": "R", "max_stars_repo_path": "src/r/SQ_Wheat_Phenology/Updatephase.r", "max_stars_repo_name": "Crop2ML-Catalog/SQ_Wheat_Phenology", "max_stars_repo_head_hexsha": "8e9ec229e5f0754d0f4b9d79ac96a084d75dde67", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2020-06-21T18:58:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-29T21:32:28.000Z", "max_issues_repo_path": "src/r/SQ_Wheat_Phenology/Updatephase.r", "max_issues_repo_name": "Crop2ML-Catalog/SQ_Wheat_Phenology", "max_issues_repo_head_hexsha": "8e9ec229e5f0754d0f4b9d79ac96a084d75dde67", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 27, "max_issues_repo_issues_event_min_datetime": "2018-12-04T15:35:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-11T08:25:03.000Z", "max_forks_repo_path": "src/r/SQ_Wheat_Phenology/Updatephase.r", "max_forks_repo_name": "Crop2ML-Catalog/SQ_Wheat_Phenology", "max_forks_repo_head_hexsha": "8e9ec229e5f0754d0f4b9d79ac96a084d75dde67", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2019-04-20T02:25:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-04T07:52:35.000Z", "avg_line_length": 43.4527027027, "max_line_length": 134, "alphanum_fraction": 0.3359767791, "num_tokens": 4091, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7662936430859597, "lm_q2_score": 0.48047867804790706, "lm_q1q2_score": 0.36818775662645664}} {"text": "#' Create a bias-corrected distribution model\n#' \n#' This function implements an occupancy-detection model assuming that:\n#' \\itemize{\n#' \t\t\\item{Detection varies by state but not between counties in a state.\n#' \t\t\\item{False detections can occur when the species does not occupy a county but does not occur when it does.\n#'\t\t\\item{Occupancy is a function of the occupancy of neighboring counties.\n#' }\n#' @param shape SpatialPolygonsDataFrame\n#' @param effort Character, name of field in \\code{shape} indicating collection effort.\n#' @param detect Character, name of field in \\code{shape} indicating number of detections of focal species.\n#' @param stateProv Character, name of field with state/province.\n#' @param county Character, name of field with county.\n#' @param niter Positive integer, number of MCMC iterations (including burn-in). The default is 2000, but this is often too low for most cases (i.e., try numbers in the range 10000, 100000, etc.).\n#' @param nburnin Positive integer, number of burn-in samples (less than \\code{niter}). The default is 1000, but this is often too low for most cases (i.e., try numbers in the range 10000, 100000, etc.).\n#' @param nchains Positive integer, number of MCMC chains (default is 4).\n#' @param thin Positive integer, number of MCMC samples by which to thin the results (default is 1; i.e., no thinning). To reduce memory requirements, you can use \\code{thin} while increasing \\code{niter} and/or \\code{nburnin}.\n#' @param raf Logical, if \\code{TRUE} (default), dynamically change the value for niter using the Raftery-Lewis method for assessing number of iterations needed for convergence. The number used will the the number suggested rounded up to the nearest 1000. The total number of iterations (including burn-in) will be this number plus \\code{nburnin}.\n#' @param minIter Minimum number of iterations to require (not including burn-in).\n#' @param maxIter Maximum number of iterations to allow in output. The final number of recommended iterations will be \\code{min(maxIter, rl)} where \\code{rl} is the number recommend by the RL method, rounded up to the nearest 1000. If \\code{rl} is > \\code{maxIter} a warning will be issued.\n#' @param nsamples Number of samples desired (after burn-in and thinning). Only used if \\code{raf} is \\code{TRUE}. Used to reset the value of \\code{thin} after estimating the number of iterations using the Raftery-Lewis method.\n#' @param na.rm Logical, if \\code{TRUE} (default), then remove rows in \\code{shape} that have \\code{NA} in any input field. If this is \\code{FALSE} and \\code{NA}s occur in any fields then an error may occur.\n#' @param verbose Logical, if \\code{TRUE} (default) display progress.\n#' @param ... Arguments to pass to \\code{\\link[nimble]{configureMCMC}}, \\code{\\link[nimble]{runMCMC}}, and \\code{rafLewis}.\n#' @return A list object with three elements, one with the MCMC chains, a second with the object \\code{shape} with model output appended to the data portion of the object, and a third with model information. The new columns in \\code{shape} represent:\n#' \\itemize{\n#' \t\t\\item{\\code{psi}} Probability of occurrence\n#' \t\t\\item{\\code{psi95CI}} 95% credibility interval for probability of occurrence\n#' \t\t\\item{\\code{p}} Probability of detecting the focal species assuming it is present\n#' \t\t\\item{\\code{p95CI}} 95% credibility interval for probability of detection\n#' }\n#' @examples\n#' @export\n\ntrainBayesODM_pMaxVarByState_psiCar <- function(\n\tshape,\n\teffort,\n\tdetect,\n\tstateProv,\n\tcounty,\n\tniter = 2000,\n\tnburnin = 1000,\n\tnchains = 4,\n\tthin = 1,\n\traf = TRUE,\n\tminIter = 2000,\n\tmaxIter = 11000,\n\tnsamples = 1000,\n\tna.rm = TRUE,\n\tverbose = TRUE,\n\t...\n) {\n\n\t### prepare data\n\t################\n\n\t\t# remove missing\n\t\tif (na.rm) {\n\t\t\tok <- complete.cases(shape@data[ , c(effort, detect)])\n\t\t\tshape <- shape[ok, ]\n\t\t}\n\t\t\t\n\t\t### CAR setup for counties\n\t\t\n\t\tneighs <- spdep::poly2nb(shape, queen=TRUE)\n\t\tneighIndex <- which(!sapply(neighs, function(shape) { length(shape == 1) && (shape == 0) }))\n\t\tislandIndex <- which(sapply(neighs, function(shape) { length(shape == 1) && (shape == 0) }))\n\n\t\thasNeighs <- length(neighIndex) > 0\n\t\thasIslands <- length(islandIndex) > 0\n\t\t\n\t\tif (hasIslands) {\n\t\t\tshapeNoIslands <- shape[neighIndex, ]\n\t\t\tneighs <- spdep::poly2nb(shapeNoIslands, queen=TRUE)\n\t\t}\n\n\t\tnumNeighs <- length(neighIndex)\n\t\tnumIslands <- length(islandIndex)\n\t\t\n\t\tnumCounties <- nrow(shape)\n\t\tnumStates <- length(unique(shape@data[ , stateProv]))\n\t\t\n\t\t### input\n\t\tdata <- list()\n\t\tconstants <- list(\n\t\t\tnumStates = numStates\n\t\t)\n\t\t\n\t\tinits <- list(\n\t\t\tq = 0.01,\n\t\t\tqConstraint = rep(1, numStates),\n\t\t\tp_max = rep(0.6, numStates),\n\t\t\tp_min_star = rep(0.95, numStates)\n\t\t)\n\n\t\t# some counties have neighbors\n\t\tif (hasNeighs) {\n\t\t\t\n\t\t\t# remove islands\n\t\t\tneighsList <- spdep::nb2WB(neighs)\n\t\t\tcarAdjCounty <- neighsList$adj\n\t\t\tcarWeightCounty <- neighsList$weights\n\t\t\tcarNumCounty <- neighsList$num\n\n\t\t\tdata <- c(\n\t\t\t\tdata,\n\t\t\t\tlist(\n\t\t\t\t\ty_neigh = shape@data[neighIndex, detect],\n\t\t\t\t\tN_neigh = shape@data[neighIndex, effort],\n\t\t\t\t\tcarAdjCounty = carAdjCounty,\n\t\t\t\t\tcarWeightCounty = carWeightCounty,\n\t\t\t\t\tcarNumCounty = carNumCounty\n\t\t\t\t)\n\t\t\t)\n\n\t\t\tconstants <- c(\n\t\t\t\tconstants,\n\t\t\t\tlist(\n\t\t\t\t\tnumNeighs = numNeighs,\n\t\t\t\t\tstate_neigh = as.numeric(as.factor(shape@data[neighIndex, stateProv])),\n\n\t\t\t\t\tlengthAdjCounties = length(carAdjCounty)\n\t\t\t\t)\n\t\t\t)\n\n\t\t\tinits <- c(\n\t\t\t\tinits,\n\t\t\t\tlist(\n\t\t\t\t\tp_star_neigh = runif(numNeighs, inits$p_min_star * inits$p_max, inits$p_max),\n\t\t\t\t\n\t\t\t\t\tz_neigh = rep(1, numNeighs),\n\t\t\t\t\tpsi_neigh = runif(numNeighs, 0.4, 0.6),\n\t\t\t\t\t\n\t\t\t\t\tpsi_tau = 0.1,\n\t\t\t\t\tpsi_car = rnorm(numNeighs)\n\t\t\t\t)\n\t\t\t)\n\t\t\t\n\t\t}\n\t\t\n\t\t# some counties are islands\n\t\tif (hasIslands) {\n\t\t\n\t\t\tdata <- c(\n\t\t\t\tdata,\n\t\t\t\tlist(\n\t\t\t\t\ty_island = shape@data[islandIndex, detect],\n\t\t\t\t\tN_island = shape@data[islandIndex, effort]\n\t\t\t\t)\n\t\t\t)\n\n\t\t\tnumStates_island <- length(shape@data[islandIndex, stateProv])\n\t\t\t\n\t\t\tconstants <- c(\n\t\t\t\tconstants,\n\t\t\t\tlist(\n\t\t\t\t\tnumIslands = numIslands,\n\t\t\t\t\tstate_island = as.numeric(as.factor(shape@data[islandIndex, stateProv]))\n\t\t\t\t)\n\t\t\t)\n\t\t\t\n\t\t\tpsi_island <- runif(numIslands, 0.4, 0.6)\n\t\t\t\n\t\t\tinits <- c(\n\t\t\t\tinits,\n\t\t\t\tlist(\n\t\t\t\t\tp_star_island = runif(numIslands, 0.1, 0.5),\n\t\t\t\t\tz_island = rep(1, numIslands),\n\t\t\t\t\tpsi_island = psi_island,\n\t\t\t\t\tlogit_psi_island = logit(psi_island),\n\t\t\t\t\tpsi_islandMean = 0,\n\t\t\t\t\tpsi_islandTau = 1\n\t\t\t\t)\n\t\t\t)\n\t\t\t\n\t\t}\n\t\t\n\t\t### monitors\n\t\tmonitors <- names(inits)\n\t\tif (hasNeighs) monitors <- c(monitors, 'p_star_neigh')\n\t\tif (hasIslands) monitors <- c(monitors, 'p_star_island')\n\n\t### model setup\n\t###############\n\t\n\t\tcode <- if (hasNeighs & hasIslands) {\n\t\t\t.trainBayesODM_pMaxVarByState_psiCar_neighsIslands\n\t\t} else if (hasNeighs & !hasIslands) {\n\t\t\t.trainBayesODM_pMaxVarByState_psiCar_neighsOnly\n\t\t} else if (!hasNeighs & hasIslands) {\n\t\t\t.trainBayesODM_pMaxVarByState_psiCar_islandsOnly\n\t\t}\n\n\t\t### construct and compile model\n\t\t###############################\n\t\t\n\t\t\tmodel <- nimble::nimbleModel(code=code, constants=constants, data=data, inits=inits, check=TRUE)\n\t\t\tflush.console()\n\n\t\t\tconf <- nimble::configureMCMC(model, monitors = monitors, print = verbose, enableWAIC = TRUE)\n\t\t\t\n\t\t\t### modify samplers\n\t\t\tnode <- 'q'\n\t\t\tconf$removeSamplers(node)\n\t\t\tconf$addSampler(target=node, type='slice')\n\t\t\t\n\t\t\tif (hasNeighs) {\n\t\t\t\tnode <- 'psi_tau'\n\t\t\t\tconf$removeSamplers(node)\n\t\t\t\tconf$addSampler(target=node, type='slice')\n\t\t\t}\n\t\t\t\n\t\t\tif (hasIslands) {\n\t\t\t\tnode <- 'psi_islandTau'\n\t\t\t\tconf$removeSamplers(node)\n\t\t\t\tconf$addSampler(target=node, type='slice')\n\n\t\t\t\t# for (i in 1:numIslands) {\n\t\t\t\t\t# node <- paste0('logit_psi_island[', i, ']')\n\t\t\t\t\t# conf$removeSamplers(node)\n\t\t\t\t\t# conf$addSampler(target=node, type='slice')\n\t\t\t\t# }\n\t\t\t}\n\t\t\t\n\t\t\tfor (i in 1:numStates) {\n\n\t\t\t\tnode <- paste0('p_max[', i, ']')\n\t\t\t\tconf$removeSamplers(node)\n\t\t\t\tconf$addSampler(target=node, type='slice')\n\t\t\t\t\n\t\t\t\tnode <- paste0('p_min_star[', i, ']')\n\t\t\t\tconf$removeSamplers(node)\n\t\t\t\tconf$addSampler(target=node, type='slice')\n\t\t\t\t\n\t\t\t}\n\t\t\t\n\t\t\tconfBuild <- nimble::buildMCMC(conf)\n\t\t\tcompiled <- nimble::compileNimble(model, confBuild)\n\n\t### variables to ignore when assessing convergence\n\t##################################################\n\n\t\texact <- NULL\n\t\t# pattern <- c('qConstraint[[]', 'p_star_neigh[[]', 'p_star_island[[]', 'logit_psi_island[[]')\n\t\tpattern <- c('qConstraint[[]')\n\t\n\t### use Raftery-Lewis statistic to see how many iterations are needed\n\t#####################################################################\n\n\t\tif (raf) {\n\n\t\t\trl <- rafLewis(\n\t\t\t\tcomp=compiled$confBuild,\n\t\t\t\tinits = inits,\n\t\t\t\tniter = niter,\n\t\t\t\tnburnin = nburnin,\n\t\t\t\tnsamples = nsamples,\n\t\t\t\tthin = thin,\n\t\t\t\tminIter = minIter,\n\t\t\t\tmaxIter = maxIter,\n\t\t\t\tretry = TRUE,\n\t\t\t\texact = exact,\n\t\t\t\tpattern = pattern,\n\t\t\t\tpropInsufficient = minUnconverged,\n\t\t\t\tverbose = verbose\n\t\t\t)\n\n\t\t\trl$mcmc <- .removeVariablesFromMcmc(rl$mcmc, exact=exact, pattern=pattern)\n\n\t\t\trand <- round(1E6 * runif(1))\n\t\t\ttempFile <- paste0('./temp/temp', rand, '.rda')\n\t\t\tsave(rl, file=tempFile)\n\t\t\trm(rl)\n\t\t\tgc()\n\t\t\tload(tempFile)\n\t\t\tfile.remove(tempFile)\n\t\t\t\n\t\t}\n\t\t\n\t\tif (rl$sufficient) {\n\t\t\n\t\t\tniter <- rl$recIter\n\t\t\tthin <- rl$recThin\n\t\t\t\n\t\t\tif (coda::niter(rl$mcmc) < nsamples) {\n\t\t\t\tif (verbose) omnibus::say('Adding iterations to Raftery-Lewis MCMC chain...')\n\t\t\t\tadd <- (niter - burnin - coda::niter(rl$mcmc)) * thin\n\t\t\t\trl$mcmc <- addToMcmc(comp = comp, mcmc = rl$mcmc, inits = inits, add = add, thin = thin)\n\t\t\t}\n\t\t\t\n\t\t}\n\t\t\t\n\t### add MCMC chains\n\t###################\n\t\t\n\t\tif (nchains > 1 | !raf) {\n\n\t\t\tstartChain <- if (raf) { 2 } else { 1 }\n\t\t\tthisNumChains <- if (raf) { nchains - 1 } else { nchains }\n\t\t\n\t\t\tmcmc <- runMCMC(compiled$confBuild, niter = niter, nburnin = nburnin, thin = thin, nchains = thisNumChains, inits = inits, progressBar = verbose, samplesAsCodaMCMC = TRUE, summary = FALSE, WAIC = FALSE)\n\t\t\tflush.console()\n\n\t\t\tmcmc <- .removeVariablesFromMcmc(mcmc, exact=exact, pattern=pattern)\n\t\t\t\t\n\t\t}\n\t\t\n\t\t# combine all chains\n\t\tnrowRafMcmc <- coda::niter(rl$mcmc)\n\t\tnrowNewMcmc <- coda::niter(mcmc)\n\t\t\n\t\tif (nrowRafMcmc > nrowNewMcmc) {\n\t\t\trl$mcmc <- rl$mcmc[1:nrowNewMcmc, ]\n\t\t\trl$mcmc <- as.mcmc(rl$mcmc)\n\t\t}\n\t\t\n\t\tmcmc[[1 + coda::nchain(mcmc)]] <- rl$mcmc\n\t\tnames(mcmc)[coda::nchain(mcmc)] <- paste0('chain', coda::nchain(mcmc))\n\n\t\tsave(mcmc, file=tempFile)\n\t\trm(mcmc)\n\t\tgc()\n\t\tload(tempFile)\n\t\tdone <- file.remove(tempFile)\n\t\t\n\t### WAIC and LOO\n\t################\n\t\n\t\t# combine chains\n\t\tniter <- coda::niter(mcmc) * nchains\n\t\tcombined <- mcmc[[1]]\n\t\tif (nchains > 1) {\n\t\t\tfor (chain in 2:nchains) {\n\t\t\t\tcombined <- rbind(combined, mcmc[[chain]])\n\t\t\t}\n\t\t}\n\t\t\n\t\t# counties with neighborhoods (not islands)\n\t\tif (hasNeighs) {\n\t\t\n\t\t\tneigh_ll <- matrix(NA, nrow=niter, ncol=length(data$y_neigh))\n\n\t\t\t# detection and occupancy\n\t\t\tfor (iter in 1:niter) {\n\n\t\t\t\t# detection\n\t\t\t\tz_neigh <- combined[iter, grepl(colnames(combined), pattern='z_neigh[[]'), drop=TRUE]\n\t\t\t\tp_max <- combined[iter, grepl(colnames(combined), pattern='p_max[[]'), drop=TRUE]\n\t\t\t\tp_min_star <- combined[iter, grepl(colnames(combined), pattern='p_min_star[[]'), drop=TRUE]\n\n\t\t\t\tq <- combined[iter, 'q', drop=TRUE]\n\n\t\t\t\tp_max_ll <- dbeta(p_max, 1, 1, log=TRUE)\n\t\t\t\tp_min_star_ll <- dbeta(p_min_star, 10, 1, log=TRUE)\n\t\t\t\tq_ll <- dbeta(q, 1, 2, log=TRUE)\n\t\t\t\t\n\t\t\t\t# CAR component\n\t\t\t\tpsi_tau <- combined[iter, 'psi_tau', drop=TRUE]\n\t\t\t\tpsi_tau_ll <- dgamma(psi_tau, 0.001, 0.001, log=TRUE)\n\t\t\t\t\n\t\t\t\tpsi_car <- combined[iter, grepl(colnames(combined), pattern='psi_car[[]')]\n\t\t\t\tpsi_car_ll <- dcar_normal(psi_car, adj=data$carAdjCounty[1:constants$lengthAdjCounties], weights=data$carWeightCounty[1:constants$lengthAdjCounties], num=data$carNumCounty[1:constants$numNeighs], tau=psi_tau, c=3, zero_mean=0, log=TRUE)\n\n\t\t\t\tp_star_neigh <- combined[iter, grepl(colnames(combined), pattern='p_star_neigh[[]'), drop=TRUE]\n\t\t\t\tp_neigh <- z_neigh * p_star_neigh + (1 - z_neigh) * q\n\t\t\t\t\n\t\t\t\tneigh_ll[iter, ] <-\n\t\t\t\t\tdbinom(data$y_neigh, size=data$N_neigh, prob=p_neigh, log = TRUE) +\t# detection\n\t\t\t\t\tp_max_ll[constants$state_neigh] +\t\t\t\t\t\t\t\t\t# state effect\n\t\t\t\t\tq_ll +\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# false detection\n\t\t\t\t\tpsi_car_ll\t\t\t\t\t\t\t\t\t\t\t\t\t\t# occupancy ~ CAR\n\n\t\t\t} # next iteration\n\t\t\t\n\t\t} # has neighbors\n\n\t\t# island counties\n\t\tif (hasIslands) {\n\t\t\n\t\t\tisland_ll <- matrix(NA, nrow=niter, ncol=length(data$y_island))\n\n\t\t\t# detection and occupancy\n\t\t\tfor (iter in 1:niter) {\n\n\t\t\t\t# detection\n\t\t\t\tz_island <- combined[iter, grepl(colnames(combined), pattern='z_island[[]'), drop=TRUE]\n\t\t\t\tp_max <- combined[iter, grepl(colnames(combined), pattern='p_max[[]'), drop=TRUE]\n\t\t\t\tp_min_star <- combined[iter, grepl(colnames(combined), pattern='p_min_star[[]'), drop=TRUE]\n\n\t\t\t\tq <- combined[iter, 'q', drop=TRUE]\n\n\t\t\t\tp_max_ll <- dbeta(p_max, 1, 1, log=TRUE)\n\t\t\t\tp_min_star_ll <- dbeta(p_min_star, 10, 1, log=TRUE)\n\t\t\t\tq_ll <- dbeta(q, 1, 2, log=TRUE)\n\t\t\t\t\n\t\t\t\tp_star_island <- combined[iter, grepl(colnames(combined), pattern='p_star_island[[]'), drop=TRUE]\n\t\t\t\tp_island <- z_island * p_star_island + (1 - z_island) * q\n\n\t\t\t\tpsi_islandMean <- combined[iter, 'psi_islandMean', drop=TRUE]\n\t\t\t\tpsi_islandTau <- combined[iter, 'psi_islandTau', drop=TRUE]\n\t\t\t\t\n\t\t\t\tpsi_islandMean_ll ~ dnorm(psi_islandMean, 0, sd=1000)\n\t\t\t\tpsi_islandTau_ll ~ dgamma(psi_islandTau, 1, 0.001)\n\t\t\t\n\t\t\t\tisland_ll[iter, ] <-\n\t\t\t\t\tdbinom(data$y_island, size=data$N_island, prob=p_island, log = TRUE) +\n\t\t\t\t\tp_max_ll[constants$state_island] +\n\t\t\t\t\tp_min_star_ll[constants$state_island] +\n\t\t\t\t\tq_ll +\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t# false detection\n\t\t\t\t\tpsi_islandMean_ll +\t\t\t\t\t\t\t\t\t\t\t\t# psi for islands\n\t\t\t\t\tpsi_islandTau_ll\t\t\t\t\t\t\t\t\t\t\t\t# psi for islands\n\n\t\t\t} # next iteration\n\t\t\t\n\t\t} # if has islands\n\n\t\t# LL of neighbors and islands, one row per iteration, one column per county\n\t\tll <- if (hasNeighs & !hasIslands) {\n\t\t\tneigh_ll\n\t\t} else if (!hasNeighs & hasIslands) {\n\t\t\tisland_ll\n\t\t} else {\n\t\t\tcbind(neigh_ll, island_ll)\n\t\t}\n\t\n\t\twaic <- loo::waic(ll)\n\t\tloo <- loo::loo(ll, cores=4)\n\t\t\n\t### process model output\n\t########################\n\n\t\tmcmc <- .removeVariablesFromMcmc(mcmc, exact=exact, pattern=c('z_neigh[[]', 'z_island[[]'))\n\n\t\tmcmcModel <- .processBayesODM(shape=shape, mcmc=mcmc, effort=effort, detect=detect, neighIndex=neighIndex, islandIndex=islandIndex, pByState=TRUE, stateProv=stateProv)\n\n\t\tmeta <- list(\n\t\t\tniter=niter,\n\t\t\tnburnin=nburnin,\n\t\t\tnchains=nchains,\n\t\t\tthin=thin,\n\t\t\teffort=effort,\n\t\t\tdetect=detect,\n\t\t\tstateProv=stateProv,\n\t\t\tcounty=county,\n\t\t\thasIslands=hasIslands,\n\t\t\tna.rm=na.rm,\n\t\t\t...\n\t\t)\n\t\t\n\t\tmcmcModel <- c(mcmcModel, list(code=code), meta=list(meta), waic=list(waic), loo=list(loo))\n\t\tmcmcModel\n\n}\n\n.trainBayesODM_pMaxVarByState_psiCar_neighsIslands <- nimble::nimbleCode({\n\t\t\t\n\t### likelihood for counties with neighborhoods\n\tfor (g in 1:numNeighs) {\n\n\t\t# detection\n\t\ty_neigh[g] ~ dbin(p_neigh[g], N_neigh[g])\n\t\tp_neigh[g] <- z_neigh[g] * p_star_neigh[g] + (1 - z_neigh[g]) * q\n\t\tp_star_neigh[g] ~ dunif(p_min[state_neigh[g]], p_max[state_neigh[g]])\n\n\t\t# occupancy\n\t\tz_neigh[g] ~ dbern(psi_neigh[g])\n\t\tlogit(psi_neigh[g]) <- psi_car[g]\n\t\n\t}\n\n\t# county occupancy CAR\n\tpsi_tau ~ dgamma(0.001, 0.001)\n\tpsi_car[1:numNeighs] ~ dcar_normal(adj=carAdjCounty[1:lengthAdjCounties], weights=carWeightCounty[1:lengthAdjCounties], num=carNumCounty[1:numNeighs], tau=psi_tau, c=3, zero_mean=0)\t\n\n\t### likelihood for island counties\n\tfor (h in 1:numIslands) {\n\n\t\t# detection\n\t\ty_island[h] ~ dbin(p_island[h], N_island[h])\n\t\tp_island[h] <- z_island[h] * p_star_island[h] + (1 - z_island[h]) * q\n\t\tp_star_island[h] ~ dunif(p_min[state_island[h]], p_max[state_island[h]])\n\n\t\t# occupancy\n\t\tz_island[h] ~ dbern(psi_island[h])\n\t\tlogit(psi_island[h]) ~ dnorm(psi_islandMean, sd=psi_islandTau)\n\n\t}\n\n\tpsi_islandMean ~ dnorm(0, tau=0.001)\n\tpsi_islandTau ~ dgamma(1, 0.001)\n\n\t\n\t# false detection\n\tq ~ dbeta(1, 2)\n\t\n\t# detection\n\tfor (j in 1:numStates) {\n\t\tp_max[j] ~ dbeta(1, 1)\n\t\tp_min[j] <- p_min_star[j] * p_max[j]\n\t\tp_min_star[j] ~ dbeta(10, 1)\n\t\tqConstraint[j] ~ dconstraint(p_min[j] > q)\n\t}\n\t\t\n})\n\n.trainBayesODM_pMaxVarByState_psiCar_neighsOnly <- nimble::nimbleCode({\n\t\t\t\n\t### likelihood for counties with neighborhoods\n\tfor (g in 1:numNeighs) {\n\n\t\t# detection\n\t\ty_neigh[g] ~ dbin(p_neigh[g], N_neigh[g])\n\t\tp_neigh[g] <- z_neigh[g] * p_star_neigh[g] + (1 - z_neigh[g]) * q\n\t\tp_star_neigh[g] ~ dunif(p_min[state_neigh[g]], p_max[state_neigh[g]])\n\n\t\t# occupancy\n\t\tz_neigh[g] ~ dbern(psi_neigh[g])\n\t\tlogit(psi_neigh[g]) <- psi_car[g]\n\t\n\t}\n\n\t# county occupancy CAR\n\tpsi_tau ~ dgamma(0.001, 0.001)\n\tpsi_car[1:numNeighs] ~ dcar_normal(adj=carAdjCounty[1:lengthAdjCounties], weights=carWeightCounty[1:lengthAdjCounties], num=carNumCounty[1:numNeighs], tau=psi_tau, c=3, zero_mean=0)\t\n\n\t# false detection\n\tq ~ dbeta(1, 2)\n\t\n\t# detection\n\tfor (j in 1:numStates) {\n\t\tp_max[j] ~ dbeta(1, 1)\n\t\tp_min[j] <- p_min_star[j] * p_max[j]\n\t\tp_min_star[j] ~ dbeta(10, 1)\n\t\tqConstraint[j] ~ dconstraint(p_min[j] > q)\n\t}\n\t\t\n})\n", "meta": {"hexsha": "3384606699f73786060cbeba4ef0cc44d037a326", "size": 16868, "ext": "r", "lang": "R", "max_stars_repo_path": "code/trainBayesODM_pMaxVarByState_psiCar.r", "max_stars_repo_name": "adamlilith/tropicosMassModeling", "max_stars_repo_head_hexsha": "4772fcb431283224b90544ecdbdb5ee4513b8d86", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code/trainBayesODM_pMaxVarByState_psiCar.r", "max_issues_repo_name": "adamlilith/tropicosMassModeling", "max_issues_repo_head_hexsha": "4772fcb431283224b90544ecdbdb5ee4513b8d86", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": 4, "max_issues_repo_issues_event_min_datetime": "2020-07-10T23:53:19.000Z", "max_issues_repo_issues_event_max_datetime": "2020-07-10T23:54:10.000Z", "max_forks_repo_path": "code/trainBayesODM_pMaxVarByState_psiCar.r", "max_forks_repo_name": "adamlilith/tropicosMassModeling", "max_forks_repo_head_hexsha": "4772fcb431283224b90544ecdbdb5ee4513b8d86", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.3531598513, "max_line_length": 347, "alphanum_fraction": 0.6557979606, "num_tokens": 5477, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6442250928250375, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.36711337725387905}} {"text": "#' Compute absolute distances between intervals.\n#'\n#' Computes the absolute distance between the midpoint of each `x` interval and\n#' the midpoints of each closest `y` interval.\n#'\n#' @details Absolute distances are scaled by the inter-reference gap for the\n#' chromosome as follows. For `Q` query points and `R` reference\n#' points on a chromosome, scale the distance for each query point `i` to\n#' the closest reference point by the inter-reference gap for each chromosome.\n#' If an `x` interval has no matching `y` chromosome,\n#' `.absdist` is `NA`.\n#'\n#' \\deqn{d_i(x,y) = min_k(|q_i - r_k|)\\frac{R}{Length\\ of\\ chromosome}}\n#'\n#' Both absolute and scaled distances are reported as `.absdist` and\n#' `.absdist_scaled`.\n#'\n#' @param x [tbl_interval()]\n#' @param y [tbl_interval()]\n#' @param genome [tbl_genome()]\n#'\n#' @return\n#' [tbl_interval()] with `.absdist` and `.absdist_scaled` columns.\n#'\n#' @template stats\n#'\n#' @family interval statistics\n#'\n#' @seealso\n#' \\url{http://journals.plos.org/ploscompbiol/article?id=10.1371/journal.pcbi.1002529}\n#'\n#' @examples\n#' genome <- read_genome(valr_example('hg19.chrom.sizes.gz'))\n#'\n#' x <- bed_random(genome, seed = 1010486)\n#' y <- bed_random(genome, seed = 9203911)\n#'\n#' bed_absdist(x, y, genome)\n#'\n#' @export\nbed_absdist <- function(x, y, genome) {\n if (!is.tbl_interval(x)) x <- as.tbl_interval(x)\n if (!is.tbl_interval(y)) y <- as.tbl_interval(y)\n if (!is.tbl_genome(genome)) genome <- as.tbl_genome(genome)\n\n # establish grouping with shared groups (and chrom)\n groups_xy <- shared_groups(x, y)\n groups_xy <- unique(as.character(c(\"chrom\", groups_xy)))\n groups_vars <- rlang::syms(groups_xy)\n\n # type convert grouping factors to characters if necessary and ungroup\n x <- convert_factors(x, groups_xy)\n y <- convert_factors(y, groups_xy)\n\n x <- group_by(x, !!! groups_vars)\n y <- group_by(y, !!! groups_vars)\n\n if (utils::packageVersion(\"dplyr\") < \"0.7.99.9000\"){\n x_cpp <- update_groups(x)\n y_cpp <- update_groups(y)\n grp_indexes <- shared_group_indexes(x_cpp, y_cpp)\n res <- dist_impl(x_cpp, y_cpp,\n grp_indexes$x,\n grp_indexes$y,\n distcalc = \"absdist\")\n } else {\n grp_indexes <- shared_group_indexes(x, y)\n res <- dist_impl(x, y,\n grp_indexes$x, grp_indexes$y,\n distcalc = \"absdist\")\n }\n\n # convert groups_xy to character vector\n if (!is.null(groups_xy)) {\n groups_xy <- as.character(groups_xy)\n }\n\n # calculate reference sizes\n genome <- filter(genome, genome$chrom %in% res$chrom)\n genome <- inner_join(genome, get_labels(y), by = c(\"chrom\"))\n\n ref_points <- summarize(y, .ref_points = n())\n genome <- inner_join(genome, ref_points, by = c(\"chrom\", groups_xy))\n\n genome <- mutate(genome, .ref_gap = .ref_points / size)\n genome <- select(genome, -size, -.ref_points)\n\n # calculate scaled reference sizes\n res <- full_join(res, genome, by = c(\"chrom\", groups_xy))\n res <- mutate(res, .absdist_scaled = .absdist * .ref_gap)\n res <- select(res, -.ref_gap)\n\n # report back original x intervals not found\n x_missing <- anti_join(x, res, by = c(\"chrom\", groups_xy))\n x_missing <- ungroup(x_missing)\n x_missing <- mutate(x_missing, .absdist = NA, .absdist_scaled = NA)\n res <- bind_rows(res, x_missing)\n\n res <- bed_sort(res)\n\n res\n}\n", "meta": {"hexsha": "ab519f20f611e2c022c86dd890ca22ebd1cdb4e5", "size": 3365, "ext": "r", "lang": "R", "max_stars_repo_path": "R/bed_absdist.r", "max_stars_repo_name": "kriemo/valr", "max_stars_repo_head_hexsha": "6355681e84b1aece2fc3800da4c15ed29c8f754c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/bed_absdist.r", "max_issues_repo_name": "kriemo/valr", "max_issues_repo_head_hexsha": "6355681e84b1aece2fc3800da4c15ed29c8f754c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/bed_absdist.r", "max_forks_repo_name": "kriemo/valr", "max_forks_repo_head_hexsha": "6355681e84b1aece2fc3800da4c15ed29c8f754c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 32.6699029126, "max_line_length": 86, "alphanum_fraction": 0.6579494799, "num_tokens": 928, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102636778401, "lm_q2_score": 0.5774953651858117, "lm_q1q2_score": 0.36579149153507556}} {"text": "#!/usr/local/bin/env Rscript --vanilla\nargs <- commandArgs(TRUE)\nif (is.null(args[1])) {\n stop(\"No expression matrix provided!\")\n}\n\nif (is.null(args[2])) {\n stop(\"No signature matrix provided!\")\n}\n\n# CIBERSORT R script v1.04 (last updated 10-24-2016)\n# Note: Signature matrix construction is not currently available; use java version for full functionality.\n# Author: Aaron M. Newman, Stanford University (amnewman@stanford.edu)\n# Requirements:\n# R v3.0 or later. (dependencies below might not work properly with earlier versions)\n# install.packages('e1071')\n# install.pacakges('parallel')\n# install.packages('preprocessCore')\n# if preprocessCore is not available in the repositories you have selected, run the following:\n# source(\"http://bioconductor.org/biocLite.R\")\n# biocLite(\"preprocessCore\")\n# Windows users using the R GUI may need to Run as Administrator to install or update packages.\n# This script uses 3 parallel processes. Since Windows does not support forking, this script will run\n# single-threaded in Windows.\n#\n# Usage:\n# Navigate to directory containing R script\n#\n# In R:\n# source('CIBERSORT.R')\n# results <- CIBERSORT('sig_matrix_file.txt','mixture_file.txt', perm, QN, absolute, abs_method)\n#\n# Options:\n# i) perm = No. permutations; set to >=100 to calculate p-values (default = 0)\n# ii) QN = Quantile normalization of input mixture (default = TRUE)\n# iii) absolute = Run CIBERSORT in absolute mode (default = FALSE)\n# - note that cell subsets will be scaled by their absolute levels and will not be\n# represented as fractions (to derive the default output, normalize absolute\n# levels such that they sum to 1 for each mixture sample)\n# - the sum of all cell subsets in each mixture sample will be added to the ouput\n# ('Absolute score'). If LM22 is used, this score will capture total immune content.\n# iv) abs_method = if absolute is set to TRUE, choose method: 'no.sumto1' or 'sig.score'\n# - sig.score = for each mixture sample, define S as the median expression\n# level of all genes in the signature matrix divided by the median expression\n# level of all genes in the mixture. Multiple cell subset fractions by S.\n# - no.sumto1 = remove sum to 1 constraint\n#\n# Input: signature matrix and mixture file, formatted as specified at http://cibersort.stanford.edu/tutorial.php\n# Output: matrix object containing all results and tabular data written to disk 'CIBERSORT-Results.txt'\n# License: http://cibersort.stanford.edu/CIBERSORT_License.txt\n\n\n#dependencies\nlibrary(e1071)\nlibrary(parallel)\nlibrary(preprocessCore)\n\n#Core algorithm\nCoreAlg <- function(X, y, absolute, abs_method){\n\n #try different values of nu\n svn_itor <- 3\n\n res <- function(i){\n if(i==1){nus <- 0.25}\n if(i==2){nus <- 0.5}\n if(i==3){nus <- 0.75}\n model<-svm(X,y,type=\"nu-regression\",kernel=\"linear\",nu=nus,scale=F)\n model\n }\n\n if(Sys.info()['sysname'] == 'Windows') out <- mclapply(1:svn_itor, res, mc.cores=1) else\n out <- mclapply(1:svn_itor, res, mc.cores=svn_itor)\n\n nusvm <- rep(0,svn_itor)\n corrv <- rep(0,svn_itor)\n\n #do cibersort\n t <- 1\n while(t <= svn_itor) {\n weights = t(out[[t]]$coefs) %*% out[[t]]$SV\n weights[which(weights<0)]<-0\n w<-weights/sum(weights)\n u <- sweep(X,MARGIN=2,w,'*')\n k <- apply(u, 1, sum)\n nusvm[t] <- sqrt((mean((k - y)^2)))\n corrv[t] <- cor(k, y)\n t <- t + 1\n }\n\n #pick best model\n rmses <- nusvm\n mn <- which.min(rmses)\n model <- out[[mn]]\n\n #get and normalize coefficients\n q <- t(model$coefs) %*% model$SV\n q[which(q<0)]<-0\n if(!absolute || abs_method == 'sig.score') w <- (q/sum(q)) #relative space (returns fractions)\n if(absolute && abs_method == 'no.sumto1') w <- q #absolute space (returns scores)\n\n mix_rmse <- rmses[mn]\n mix_r <- corrv[mn]\n\n newList <- list(\"w\" = w, \"mix_rmse\" = mix_rmse, \"mix_r\" = mix_r)\n\n}\n\n#do permutations\ndoPerm <- function(perm, X, Y, absolute, abs_method){\n itor <- 1\n Ylist <- as.list(data.matrix(Y))\n dist <- matrix()\n\n while(itor <= perm){\n #print(itor)\n\n #random mixture\n yr <- as.numeric(Ylist[sample(length(Ylist),dim(X)[1])])\n\n #standardize mixture\n yr <- (yr - mean(yr)) / sd(yr)\n\n #run CIBERSORT core algorithm\n result <- CoreAlg(X, yr, absolute, abs_method)\n\n mix_r <- result$mix_r\n\n #store correlation\n if(itor == 1) {dist <- mix_r}\n else {dist <- rbind(dist, mix_r)}\n\n itor <- itor + 1\n }\n newList <- list(\"dist\" = dist)\n}\n\n#main function\nCIBERSORT <- function(sig_matrix, mixture_file, perm=0, QN=FALSE, absolute=FALSE, abs_method='sig.score'){\n\n if(absolute && abs_method != 'no.sumto1' && abs_method != 'sig.score') stop(\"abs_method must be set to either 'sig.score' or 'no.sumto1'\")\n\n #read in data\n #X <- read.table(sig_matrix,header=T,sep=\"\\t\",row.names=1,check.names=F)\n X <- read.csv(sig_matrix, sep = \"\\t\", row.names = 1,check.names=F)\n #Y <- read.table(mixture_file, header=T, sep=\"\\t\",check.names=F)\n Y <- read.csv(mixture_file, sep = \"\\t\",check.names=F)\n #to prevent crashing on duplicated gene symbols, add unique numbers to identical names\n dups <- dim(Y)[1] - length(unique(Y[,1]))\n if(dups > 0) {\n warning(paste(dups,\" duplicated gene symbol(s) found in mixture file!\",sep=\"\"))\n rownames(Y) <- make.names(Y[,1], unique=TRUE)\n }else {rownames(Y) <- Y[,1]}\n Y <- Y[,-1]\n\n X <- data.matrix(X)\n Y <- data.matrix(Y)\n\n #order\n X <- X[order(rownames(X)),]\n Y <- Y[order(rownames(Y)),]\n\n P <- perm #number of permutations\n\n #anti-log if max < 50 in mixture file\n if (max(Y, na.rm = TRUE) < 50) {\n Y <- 2^Y\n Y[is.na(Y)] <- 0.0\n }\n\n #quantile normalization of mixture file\n if(QN == TRUE){\n tmpc <- colnames(Y)\n tmpr <- rownames(Y)\n Y <- normalize.quantiles(Y)\n colnames(Y) <- tmpc\n rownames(Y) <- tmpr\n }\n\n #store original mixtures\n Yorig <- Y\n Ymedian <- max(median(Yorig),1)\n\n #intersect genes\n Xgns <- row.names(X)\n Ygns <- row.names(Y)\n YintX <- Ygns %in% Xgns\n Y <- Y[YintX,]\n XintY <- Xgns %in% row.names(Y)\n X <- X[XintY,]\n\n #standardize sig matrix\n X <- (X - mean(X)) / sd(as.vector(X))\n\n #empirical null distribution of correlation coefficients\n if(P > 0) {nulldist <- sort(doPerm(P, X, Y, absolute, abs_method)$dist)}\n\n header <- c('Mixture',colnames(X),\"P-value\",\"Correlation\",\"RMSE\")\n if(absolute) header <- c(header, paste('Absolute score (',abs_method,')',sep=\"\"))\n\n output <- matrix()\n itor <- 1\n mixtures <- dim(Y)[2]\n pval <- 9999\n\n #iterate through mixtures\n while(itor <= mixtures){\n\n\n y <- Y[,itor]\n\n #standardize mixture\n y <- (y - mean(y)) / sd(y)\n\n #run SVR core algorithm\n result <- CoreAlg(X, y, absolute, abs_method)\n\n #get results\n w <- result$w\n mix_r <- result$mix_r\n mix_rmse <- result$mix_rmse\n\n if(absolute && abs_method == 'sig.score') {\n w <- w * median(Y[,itor]) / Ymedian\n }\n\n #calculate p-value\n if(P > 0) {pval <- 1 - (which.min(abs(nulldist - mix_r)) / length(nulldist))}\n\n #print output\n out <- c(colnames(Y)[itor],w,pval,mix_r,mix_rmse)\n if(absolute) out <- c(out, sum(w))\n if(itor == 1) {output <- out}\n else {output <- rbind(output, out)}\n\n itor <- itor + 1\n\n }\n\n #save results\n #write.table(rbind(header,output), file=\"CIBERSORT-Results.txt\", sep=\"\\t\", row.names=F, col.names=F, quote=F)\n\n #return matrix object containing all results\n obj <- rbind(header,output)\n obj <- obj[,-1]\n obj <- obj[-1,]\n obj <- matrix(as.numeric(unlist(obj)),nrow=nrow(obj))\n rownames(obj) <- colnames(Y)\n if(!absolute){colnames(obj) <- c(colnames(X),\"P-value\",\"Correlation\",\"RMSE\")}\n else{colnames(obj) <- c(colnames(X),\"P-value\",\"Correlation\",\"RMSE\",paste('Absolute score (',abs_method,')',sep=\"\"))}\n obj[, 1:(dim(X)[2])]\n}\n\ntryCatch(\n expr = {\n cs <- CIBERSORT(args[2], args[1])\n write.table(t(cs), file=\"deconvoluted.tsv\", quote = FALSE, col.names = NA, sep = \"\\t\")\n },\n error = function(e){\n # (Optional)\n # Do this if an error is caught...\n print(e)\n X <- read.csv(args[2], sep = \"\\t\", row.names = 1)\n Y <- read.csv(args[1], sep = \"\\t\")\n cs <- matrix(0, nrow = length(colnames(Y)) - 1, ncol = length(colnames(X)), dimnames = list(colnames(Y)[2:length(colnames(Y))], colnames(X)))\n write.table(t(cs), file=\"deconvoluted.tsv\", quote = FALSE, col.names = NA, sep = \"\\t\")\n }\n)\n", "meta": {"hexsha": "a3b51435e1319f662d9dff8ef44837b6b09e978c", "size": 8541, "ext": "r", "lang": "R", "max_stars_repo_path": "tumorDeconvAlgs/cibersort/cibersort.r", "max_stars_repo_name": "PNNL-CompBio/proteomicsTumorDeconv", "max_stars_repo_head_hexsha": "a88c3ee729a0dab267ebd5d802a486ebacbf0c0c", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2021-07-18T17:37:26.000Z", "max_stars_repo_stars_event_max_datetime": "2022-02-15T05:20:31.000Z", "max_issues_repo_path": "tumorDeconvAlgs/cibersort/cibersort.r", "max_issues_repo_name": "sgosline/proteomicsTumorDeconv", "max_issues_repo_head_hexsha": "a88c3ee729a0dab267ebd5d802a486ebacbf0c0c", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 58, "max_issues_repo_issues_event_min_datetime": "2020-10-14T20:37:05.000Z", "max_issues_repo_issues_event_max_datetime": "2021-05-11T15:36:22.000Z", "max_forks_repo_path": "tumorDeconvAlgs/cibersort/cibersort.r", "max_forks_repo_name": "sgosline/proteomicsTumorDeconv", "max_forks_repo_head_hexsha": "a88c3ee729a0dab267ebd5d802a486ebacbf0c0c", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 3, "max_forks_repo_forks_event_min_datetime": "2021-05-18T01:21:39.000Z", "max_forks_repo_forks_event_max_datetime": "2021-09-24T15:44:27.000Z", "avg_line_length": 31.750929368, "max_line_length": 147, "alphanum_fraction": 0.6263903524, "num_tokens": 2591, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6926419831347361, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.36524156249333783}} {"text": "library(dplyr)\nlibrary(CHNOSZ)\nlibrary(stringr)\n\n\n### helper functions\n\n# trims away leading and trailing spaces and condenses multiple spaces between words\ntrimspace <- function(str){\n gsub(\"(?<=[\\\\s])\\\\s*|^\\\\s+|\\\\s+$\", \"\", str, perl=TRUE)\n}\n\n# isolate a substring by trimming off the portions before and after it\nisolate_block <- function(str, begin_str, end_str){\n return(sub(end_str, \"\", sub(begin_str, \"\", str)))\n}\n\n### main functions\n\nmine_3o <- function(this_file,\n this_pressure,\n rxn_table,\n get_aq_dist=T,\n get_mass_contribution=T,\n get_mineral_sat=T,\n get_redox=T,\n get_charge_balance=T,\n get_ion_activity_ratios=T,\n get_fugacity=T,\n get_basis_totals=T,\n get_solid_solutions=T,\n get_affinity_energy=T,\n negative_energy_supplies=F,\n not_limiting=c(\"H+\", \"OH-\", \"H2O\"),\n mass_contribution_other=T,\n verbose=1){\n \n # set directory to rxn_3o folder where .3o files are kept\n setwd(\"rxn_3o\")\n \n # read .3o file as a string\n fileName <- this_file\n extractme <- readChar(fileName, file.info(fileName)$size) # readChar requires filesize, which is obtained from file.info()$size\n\n # get sample name\n this_name <- trimspace(isolate_block(extractme, begin_str=\"^.*\\\\|Sample:\\\\s+\", end_str=\"\\\\|\\\\n\\\\|.*$\"))\n\n if(verbose > 1){\n writeLines(paste0(\"Processing EQ3 output for \", this_name))\n }\n\n # check if file experienced errors. If so, skip processing the file:\n if (grepl(\"Normal exit\", extractme) == FALSE | grepl(\"\\\\* Error\", extractme)){\n if(verbose > 0){\n writeLines(paste0(\"\\nSample \", this_name, \" experienced errors during speciation:\"))\n\n output_error <- str_extract_all(extractme, regex(\"\\\\* Error.*?\\n(\\n|$)\", dotall=T))\n \n output_error <- lapply(output_error, function(x) gsub(\"\\n\", \" \", x))\n output_error <- lapply(output_error, str_squish)\n \n for(i in 1:length(output_error)){\n writeLines(output_error[[i]])\n }\n \n }\n\n setwd(\"../\")\n return(list())\n }\n\n sample_3o <- list()\n\n sample_3o[[\"filename\"]] <- this_file\n sample_3o[[\"name\"]] <- this_name\n \n ### Begin mining temperature, pressure, water properties\n \n # mine params\n sample_3o[[\"temperature\"]] <- isolate_block(str=extractme, begin_str=\"^.*Temperature=\\\\s+\", end_str=\"\\\\s+.*$\")\n sample_3o[[\"pressure\"]] <- this_pressure #isolate_block(str=extractme, begin_str=\"^.*Pressure=\\\\s+\", end_str=\"\\\\s+.*$\")\n sample_3o[[\"logact_H2O\"]] <- isolate_block(str=extractme, begin_str=\"^.*Log activity of water=\\\\s+\", end_str=\"\\\\s+.*$\")\n sample_3o[[\"H2O_density\"]] <- isolate_block(str=extractme, begin_str=\"^.*Solution density =\\\\s+\", end_str=\"\\\\s+.*$\")\n sample_3o[[\"H2O_molality\"]] <- 55.348/as.numeric(sample_3o[[\"H2O_density\"]])\n sample_3o[[\"H2O_log_molality\"]] <- log10(sample_3o[[\"H2O_molality\"]])\n\n ### Begin extracting 'Distribution of Aqueous Solute Species' ###\n if (get_aq_dist){\n # string to isolate the aqueous species distribution section:\n front_trim <- \"^.*\\n\\n\\n\\n --- Distribution of Aqueous Solute Species ---\\n\\n Species Molality Log Molality Log Gamma Log Activity\\n\\n\\\\s+\"\n\n # isolate species distribution block\n species_block <- isolate_block(str=extractme, begin_str=front_trim, end_str=\"\\n\\n.*$\")\n\n # split into substrings, each representing a separate row in the table\n species_block <- strsplit(species_block, \"\\n\")\n \n #create an empty data frame to store results\n df <- data.frame(species = character(0),\n molality = character(0),\n log_molality = character(0),\n log_gamma = character(0),\n log_activity = character(0),\n stringsAsFactors = FALSE)\n\n # convert into dataframe\n for(this_row in species_block[[1]]){\n\n # mine row data\n this_row <- trimspace(this_row)\n this_row_data <- strsplit(this_row, \" \")[[1]]\n\n # create a dataframe with results\n this_df <- data.frame(species=this_row_data[1],\n molality=this_row_data[2],\n log_molality=this_row_data[3],\n log_gamma=this_row_data[4],\n log_activity=this_row_data[5],\n stringsAsFactors=FALSE)\n\n # bind distribution of aqueous species to dataframe\n df <- rbind(df, this_df)\n\n }\n\n if(!(\"H2O\" %in% df$species)){\n # add a row for water\n df <- rbind(df, data.frame(species=\"H2O\",\n molality=sample_3o[[\"H2O_molality\"]],\n log_molality=sample_3o[[\"H2O_log_molality\"]],\n log_gamma=1,\n log_activity=sample_3o[[\"logact_H2O\"]],\n stringsAsFactors=FALSE))\n }\n\n # set rownames of aqueous species block as species names\n rownames(df) <- df$species\n df$species <- NULL\n \n # add aqueous block to this sample data\n sample_3o[[\"aq_distribution\"]] <- df\n \n } # end of 'aqueous distribution' extraction\n \n\n if(get_mass_contribution){\n ### begin extracting 'Major Species by Contribution to Aqueous Mass Balances' ###\n \n # string to isolate the species saturation section:\n front_trim <- \"^.*\\n\\n\\n --- Major Species by Contribution to Aqueous Mass Balances ---\\n\\n\\n\"\n\n # isolate contribution block\n contrib_block <- isolate_block(str=extractme, begin_str=front_trim, end_str=\"\\n\\n\\n\\n.*$\")\n \n # split into substrings, each representing a separate row in the table\n contrib_block <- strsplit(contrib_block, \"\\n\")\n # remove blank linkes\n contrib_block[[1]] <- contrib_block[[1]][contrib_block[[1]] != \"\"]\n \n # loop through rows in this block and mine contributions\n mine_vals <- FALSE\n for(this_row in contrib_block[[1]]){\n if(grepl(\"Accounting for\", this_row)){\n # get basis species for this block\n this_basis <- sub(\" Species Accounting for 99% or More of Aqueous \", \"\", this_row)\n } else if (grepl(\"Per Cent\", this_row)){\n # get ready to mine data for this basis species\n mine_vals <- TRUE\n df_basis <- data.frame(species=character(0),\n molality=character(0),\n factor=character(0),\n percent=character(0),\n stringsAsFactors = FALSE)\n } else if (mine_vals && !grepl(\" - - - - - - - - -\", this_row)){\n # mine data from this row\n row_data <- trimspace(this_row)\n row_data <- strsplit(row_data, \" \")[[1]]\n df_basis <- rbind(df_basis, data.frame(species=row_data[1], factor=row_data[2],\n molality=row_data[3], percent=row_data[4], stringsAsFactors = FALSE))\n } else if (grepl(\" - - - - - - - - -\", this_row)){\n # stop mining for this basis species\n mine_vals <- FALSE\n # specify rownames for this contribution block\n rownames(df_basis) <- df_basis$species\n df_basis$species <- NULL\n # add contribution data to list of sample data\n sample_3o[[\"mass_contribution\"]][[this_basis]] <- df_basis\n }\n }\n } # end 'aqueous contribution' extraction\n\n\n ### Begin mining mineral saturation section \n if(get_mineral_sat){\n \n # string to isolate the mineral saturation section:\n front_trim <- \"^.*\\n\\n\\n\\n --- Saturation States of Pure Solids ---\\n\\n Phase Log Q/K Affinity, kcal\\n\\n\\\\s+\"\n\n # isolate mineral block\n mineral_block <- isolate_block(str=extractme, begin_str=front_trim, end_str=\"\\n\\n.*$\")\n\n # split into substrings, each representing a separate row in the table\n mineral_block <- strsplit(mineral_block, \"\\n\")\n\n # create an empty data frame to store results\n df <- data.frame(mineral = character(0),\n logQoverK = character(0),\n affinity = character(0),\n stringsAsFactors = FALSE)\n\n # convert into dataframe\n for(this_row in mineral_block[[1]]){\n # get row data\n this_row_data <- strsplit(trimspace(this_row), \" \")[[1]]\n \n # create a dataframe with mined data\n this_df <- data.frame(mineral = this_row_data[1],\n logQoverK = this_row_data[2],\n affinity = this_row_data[3],\n stringsAsFactors = FALSE)\n \n # bind results to dataframe\n df <- rbind(df, this_df)\n }\n rownames(df) <- df$mineral\n df$mineral <- NULL\n \n # add mineral saturation block to this sample data\n sample_3o[[\"mineral_sat\"]] <- df\n\n if(get_solid_solutions){\n if(grepl(\"--- Saturation States of Hypothetical Solid Solutions ---\", extractme)){\n # string to isolate the solid solution saturation section:\n front_trim <- \"^.*\\n\\n\\n --- Saturation States of Hypothetical Solid Solutions ---\\n\\n\"\n\n # isolate solid solution block\n ss_block <- isolate_block(str=extractme, begin_str=front_trim, end_str=\"\\n\\n --- Fugacities ---.*$\") # end_str might be different if fugacity section is not present\n\n # split into substrings, each representing a separate solid solution\n ss_block <- strsplit(ss_block, \"\\n\\n\\n --- \")[[1]]\n\n ss_entries <- list()\n\n for(ss_entry in ss_block){\n ss_entry <- strsplit(ss_entry, \" ---\\n\\n \")[[1]]\n ss_name <- ss_entry[1]\n ss_name <- sub(\"\\n --- \", \"\", ss_name) # needed to clean up the first ss_entry name\n ss_data <- ss_entry[2]\n ss_data <- sub(\"Ideal solution\\n\\n Component x Log x Log lambda Log activity\\n\\n\", \"\", ss_data)[[1]]\n ss_entry <- strsplit(ss_data, \"\\n\\n\\n Mineral Log Q/K Aff, kcal State\\n\\n\")\n\n\n\n ss_entry <- lapply(ss_entry, FUN=strsplit, \"\\n\")[[1]]\n ss_entry <- lapply(ss_entry, FUN=trimws, \"l\")\n ss_entry <- lapply(ss_entry, FUN=strsplit, \"[ ]{2,}\", perl=TRUE)\n names(ss_entry) <- c(\"ideal solution\", \"mineral\")\n\n\n ideal_sol_df <- data.frame(component=character(),\n x=numeric(),\n `Log x`=numeric(),\n `Log lambda`=numeric(),\n `Log activity`=numeric(),\n stringsAsFactors = FALSE)\n for(row in ss_entry[[\"ideal solution\"]]){\n\n x <- suppressWarnings(as.numeric(row[2]))\n if(is.na(x)){\n x <- 0\n }\n\n ideal_sol_df <- rbind(ideal_sol_df, data.frame(component=as.character(row[1]),\n x = x,\n `Log x` = as.numeric(row[3]),\n `Log lambda` = as.numeric(row[4]),\n `Log activity` = as.numeric(row[5])),\n stringsAsFactors=FALSE)\n }\n names(ideal_sol_df) <- c(\"component\", \"x\", \"Log x\", \"Log lambda\", \"Log activity\") # rename columns because check.names doesn't work when creating the dataframes\n ss_entry[[\"ideal solution\"]] <- ideal_sol_df\n\n mineral_ss_df <- data.frame(mineral=character(), \n `Log Q/K`=numeric(),\n `Aff, kcal`=numeric(),\n `State`=character(),\n stringsAsFactors = FALSE)\n for(row in ss_entry[[\"mineral\"]]){\n\n\n if(length(row) == 3){\n row <- c(row, \"\")\n }\n mineral_ss_df <- rbind(mineral_ss_df, data.frame(mineral=as.character(row[1]),\n `Log Q/K`=as.numeric(row[2]),\n `Aff, kcal`=as.numeric(row[3]),\n `State`=row[4]),\n stringsAsFactors = FALSE)\n }\n names(mineral_ss_df) <- c(\"mineral\", \"Log Q/K\", \"Aff, kcal\", \"State\") # rename columns because check.names doesn't work when creating the dataframes\n ss_entry[[\"mineral\"]] <- mineral_ss_df\n\n ss_entries[[ss_name]] <- ss_entry\n }\n sample_3o[[\"solid_solutions\"]] <- ss_entries\n }\n }\n } # end 'mineral saturation affinity' extraction\n \n\n ### Begin mining redox data\n if(get_redox){\n # string to isolate the redox section:\n front_trim <- \"^.*\\n\\n\\n\\n --- Aqueous Redox Reactions ---\\n\\n Couple Eh, volts pe- log fO2 Ah, kcal\\n\\n\\\\s+\"\n\n # isolate redox block\n redox_block <- isolate_block(str=extractme, begin_str=front_trim, end_str=\"\\n\\n.*$\")\n\n # split into substrings, each representing a separate row in the table\n redox_block <- strsplit(redox_block, \"\\n\")\n\n #create an empty data frame to store results\n df <- data.frame(couple = character(0),\n Eh = character(0),\n pe = character(0),\n logfO2 = character(0),\n Ah = character(0),\n stringsAsFactors = FALSE)\n\n # convert into dataframe\n for(this_row in redox_block[[1]]){\n \n # get row data\n this_row_data <- strsplit(trimspace(this_row), \" \")[[1]]\n\n # create a dataframe with results\n this_df <- data.frame(couple = this_row_data[1],\n Eh = this_row_data[2],\n pe = this_row_data[3],\n logfO2 = this_row_data[4],\n Ah = this_row_data[5],\n stringsAsFactors = FALSE)\n \n # bind results to dataframe\n df <- rbind(df, this_df)\n }\n rownames(df) <- df$couple\n df$couple <- NULL\n \n # add mineral saturation block to this sample data\n sample_3o[[\"redox\"]] <- df\n } # end redox extraction\n \n\n ### begin mining charge balance data\n if(get_charge_balance){\n # string to isolate ionic strength:\n front_trim <- \"^.*Ionic strength \\\\(I\\\\)=\\\\s+\"\n\n # isolate ionic strength\n IS <- isolate_block(str=extractme, begin_str=front_trim, end_str=\"\\\\s+.*$\")\n names(IS) <- \"ionic strength\"\n\n # string to isolate stoichiometric ionic strength:\n front_trim <- \"^.*Stoichiometric ionic strength=\\\\s+\"\n\n IS_stoich <- isolate_block(str=extractme, begin_str=front_trim, end_str=\"\\\\s+.*$\")\n names(IS_stoich) <- \"stoichiometric ionic strength\"\n\n # string to isolate the electrical balance section:\n front_trim <- \"^.*Sigma\\\\(mz\\\\) cations=\\\\s+\"\n\n elec_block <- isolate_block(str=extractme, begin_str=front_trim, end_str=\"\\n\\n.*$\")\n\n # split electrical block into strings and numerics\n elec_block <- strsplit(elec_block, \"=\\\\s+|\\n\\\\s+\")[[1]]\n\n elec_block <- c(\"sigma(mz) cations\"=elec_block[1],\n \"sigma(mz) anions\"=elec_block[3],\n \"total charge\"=elec_block[5],\n \"mean charge\"=elec_block[7],\n \"charge imbalance\"=elec_block[9])\n\n # string to isolate charge balance:\n front_trim <- \"^.*The electrical imbalance is:\\n\\n\\\\s+\"\n\n cbal_bal <- isolate_block(str=extractme, begin_str=front_trim, end_str=\"\\n\\n.*$\")\n\n # split electrical block into strings and numerics\n cbal_block <- strsplit(cbal_bal, \" per cent|\\n\\\\s+\")[[1]]\n\n cbal_block <- c(\"charge imbalance % of total charge\"=cbal_block[1],\n \"charge imbalance % of mean charge\"=cbal_block[3])\n \n sample_3o[[\"charge_balance\"]] <- c(IS, IS_stoich, elec_block, cbal_block)\n } # end charge balance extraction\n\n\n if(get_ion_activity_ratios){\n ion_ratio_block <- isolate_block(extractme, \"^.*--- Ion-H\\\\+ Activity Ratios ---\\n\\n\", \"\\n\\n.*$\")\n ion_ratio_block_split <- strsplit(ion_ratio_block, \"\\n\")[[1]]\n ion_ratio_block_split <- strsplit(ion_ratio_block_split, \"=\")\n \n if (!identical(ion_ratio_block_split, character(0))){\n \n ion_ratio_logs <- trimspace(lapply(ion_ratio_block_split, `[[`, 1))\n ion_ratio_values <- suppressWarnings(as.numeric(lapply(ion_ratio_block_split, `[[`, 2)))\n \n which_to_divide <- grepl(\"/\", ion_ratio_logs) # which of these ratios divide by H+ (instead of multiply?)\n hydrogen_exponents <- unlist(lapply(lapply(strsplit(gsub(\"^Log \\\\( a\\\\(\", \"\", gsub(\" \\\\)$\", \"\", ion_ratio_logs)), \"\\\\)xx \"), `[[`, 2), as.numeric))\n ion <- unlist(lapply(strsplit(gsub(\"^Log \\\\( a\\\\(\", \"\", gsub(\" \\\\)$\", \"\", ion_ratio_logs)), \"\\\\) [x|/] a\\\\(\"), `[[`, 1))\n ion_times <- lapply(strsplit(gsub(\"^Log \\\\( a\\\\(\", \"\", gsub(\" \\\\)$\", \"\", ion_ratio_logs)), \"\\\\) x a\\\\(\")[!which_to_divide], `[[`, 1)\n ion_divide <- lapply(strsplit(gsub(\"^Log \\\\( a\\\\(\", \"\", gsub(\" \\\\)$\", \"\", ion_ratio_logs)), \"\\\\) / a\\\\(\")[which_to_divide], `[[`, 1)\n \n names(ion_ratio_values)[!which_to_divide] <- paste0(\"Log(\", ion_times, \" x H+**\", hydrogen_exponents[!which_to_divide], \")\")\n names(ion_ratio_values)[which_to_divide] <- paste0(\"Log(\", ion_divide, \" / H+**\", hydrogen_exponents[which_to_divide], \")\")\n \n ion_ratio_values[is.na(ion_ratio_values)] <- \"NA\"\n\n df <- data.frame(\"values\"=ion_ratio_values,\n \"H_exponent\"=hydrogen_exponents,\n \"divide\"=which_to_divide,\n \"ion\"=ion)\n\n df <- transform(transform(df, values = as.character(values)), values=as.numeric(values))\n df <- transform(df, ion = as.character(ion))\n sample_3o[[\"ion_activity_ratios\"]] <- df\n }\n }\n\n ### begin fugacity mining\n if(get_fugacity){\n fugacity_block <- isolate_block(extractme, \"^.*--- Fugacities ---\\n\\n\", \"\\n\\n\\n.*$\")\n str <- str_squish(strsplit(fugacity_block, \"\\n\")[[1]])\n str <- str[3:length(str)]\n split_str <- strsplit(str, \" \")\n df <- data.frame(gas=unlist(lapply(split_str, `[[`, 1)),\n log_fugacity=as.numeric(unlist(lapply(split_str, `[[`, 2))),\n stringsAsFactors=F, row.names=1)\n\n # fix an annoying behavior with R dataframes ignoring rownames when there is\n # only one row\n if(nrow(df) == 1){\n rownames(df) <- unlist(lapply(split_str, `[[`, 1))[1]\n df <- df[ , !(names(df)==\"gas\")]\n }\n\n sample_3o[[\"fugacity\"]] <- df\n }\n\n \n ### begin sensible composition mining (\"basis totals\")\n if(get_basis_totals){\n sc_block <- isolate_block(extractme, \"^.*--- Sensible Composition of the Aqueous Solution ---\\n\\n\", \"\\n\\n The above data have.*$\")\n str <- str_squish(strsplit(sc_block, \"\\n\")[[1]])\n str <- str[3:length(str)]\n split_str <- strsplit(str, \" \")\n sc_names <- unlist(lapply(lapply(split_str, `[[`, 1), paste0, \"_total\"))\n df <- data.frame(species=sc_names,\n `mg/L`=as.numeric(unlist(lapply(split_str, `[[`, 2))),\n `mg/kg.sol`=as.numeric(unlist(lapply(split_str, `[[`, 3))),\n `molarity`=as.numeric(unlist(lapply(split_str, `[[`, 4))),\n `molality`=as.numeric(unlist(lapply(split_str, `[[`, 5))),\n stringsAsFactors=F, row.names=1)\n \n # fix an annoying behavior with R dataframes ignoring rownames when there is\n # only one row\n if(nrow(df) == 1){\n rownames(df) <- sc_names[1]\n df <- df[ , !(names(df)==\"species\")]\n }\n \n sample_3o[[\"basis_totals\"]] <- df\n\n }\n\n ### begin energy mining\n if(get_affinity_energy){\n \n this_temp <- as.numeric(sample_3o[[\"temperature\"]])\n this_logact_H2O <- as.numeric(sample_3o[[\"logact_H2O\"]])\n this_H2O_log_molality <- as.numeric(sample_3o[[\"H2O_log_molality\"]])\n\n df <- sample_3o[[\"aq_distribution\"]]\n \n # get a list of mineral names in CHNOSZ\n CHNOSZ_cr_names <- unlist(thermo()$OBIGT %>% filter(state == \"cr\") %>% select(name))\n\n # clear any molal values upon moving to this sample\n remaining_react_molal_with_product_molal <- c()\n other_reactants_and_prod_names <- c()\n other_reactants_and_prod <- c()\n \n # create a dataframe for storing results\n df_rxn <- data.frame(rxn = character(0),\n affinity = numeric(0),\n energy_supply = numeric(0),\n mol_rxn = numeric(0),\n electrons= numeric(0),\n reaction = character(0),\n limiting = character(0),\n stringsAsFactors = FALSE)\n \n for(rxn in rxn_table){\n \n rxn_split <- unlist(strsplit(rxn, \"\\t\"))\n rxn_name <- rxn_split[1]\n electrons <- as.numeric(rxn_split[2])\n full_rxn <- rxn_split[3:length(rxn_split)]\n if(length(full_rxn) %% 2 != 0){\n stop(paste(\"Error: Number of reaction coefficients and species do not match in reaction\", rxn_name))\n }\n\n stoichs <- as.numeric(full_rxn[c(TRUE, FALSE)])\n species_EQ3 <- full_rxn[c(FALSE, TRUE)]\n# species_CHNOSZ <- gsub(\",AQ\", \"\", species_EQ3) # this won't work for mineral names, gases, etc.!\n# species_CHNOSZ <- gsub(\"METHANE\", \"CH4\", species_CHNOSZ) # temporary fix for methane\n# species_CHNOSZ <- gsub(\"SULFUR\", \"S\", species_CHNOSZ) # temporary fix for sulfur\n# species_CHNOSZ <- gsub(\"Ca(CO3)\", \"CaCO3\", species_CHNOSZ) # temporary fix for calcium carbonate\n# species_CHNOSZ <- gsub(\"Ca(CO3),AQ\", \"CaCO3\", species_CHNOSZ) # temporary fix for calcium carbonate\n\n species_CHNOSZ <- species_EQ3 # assuming no differences between EQ3 and CHNOSZ naming\n \n # handle minerals\n for(species in species_CHNOSZ){\n if(species %in% CHNOSZ_cr_names){\n #species_CHNOSZ <- gsub(species, lowercase_species, species_CHNOSZ)\n # add the mineral to master_df and master_df_mol dataframes assuming an\n # activity of 1 (log activity 0)\n df[species, \"log_activity\"] <- 0\n not_limiting <- c(not_limiting, species)\n }\n }\n\n ### calculate Q using EQ3-speciated activities\n # get speciated activities from master_df\n activities <- c()\n molalities <- c()\n \n for(species in species_EQ3){\n \n if(species %in% rownames(df)){\n \n activities <- c(activities, 10^as.numeric(df[species, \"log_activity\"]))\n\n if(!grepl(\"sub$\", rxn_name)){\n molalities <- c(molalities, as.numeric(df[species, \"molality\"]))\n } else {\n molalities <- c(molalities, remaining_react_molal_with_product_molal[species])\n }\n \n } else {\n \n activities <- c(activities, NA)\n molalities <- c(molalities, NA)\n }\n }\n \n if(!(NA %in% activities) & !is.null(molalities) & !is.null(activities)){\n \n names(activities) <- species_EQ3\n names(molalities) <- species_EQ3\n\n if(grepl(\"sub$\", rxn_name)){\n other_reactants_and_prod_names <- setdiff(names(remaining_react_molal_with_product_molal), names(molalities))\n other_reactants_and_prod <- remaining_react_molal_with_product_molal[other_reactants_and_prod_names]\n }\n\n # calculate Q\n reactant_stoich <- stoichs[which(stoichs < 0)]\n reactant_activities <- activities[which(stoichs < 0)]\n reactant_molalities <- molalities[which(stoichs < 0)]\n product_stoich <- stoichs[which(stoichs > 0)]\n product_activities <- activities[which(stoichs > 0)]\n product_molalities <- molalities[which(stoichs > 0)]\n this_logQ <- sum(abs(product_stoich)*log10(product_activities)) - sum(abs(reactant_stoich)*log10(reactant_activities))\n\n\n \n if(!is.na(this_logQ)){\n \n ### calculate K using subcrt() function in CHNOSZ\n this_logK <- suppressMessages(subcrt(species=species_CHNOSZ,\n coeff=stoichs,\n #state=phase,\n T=this_temp,\n P=this_pressure)$out$logK)\n }else{\n this_logK <- NA\n }\n \n ### calculate affinity, A\n affinity_per_mol_rxn <- 0.008314*(this_temp+273.15)*2.302585*(this_logK-this_logQ) # in kJ/mol, A=RT*ln(K/Q)=RT*2.302585*(logK-logQ)\n affinity_per_mol_e <- ((affinity_per_mol_rxn*1000)/4.184)/electrons # in cal/mol e-\n\n ### calculate activity of limiting reactant\n reactant_names <- species_EQ3[which(stoichs < 0)]\n product_names <- species_EQ3[which(stoichs > 0)]\n not_lim_index <- which(reactant_names %in% not_limiting)\n\n names(reactant_molalities) <- reactant_names\n \n if(length(not_lim_index) == 0){\n molality_div_stoich <- reactant_molalities/abs(reactant_stoich)\n }else if(all(reactant_names %in% not_limiting)){\n\n # if there are no limiting reactants (e.g., reactants are all minerals)\n # then append NAs and continue...\n df_rxn <- rbind(df_rxn, data.frame(rxn=rxn_name,\n affinity=affinity_per_mol_e,\n energy_supply=NA,\n mol_rxn=1,\n electrons=electrons,\n reaction=paste(full_rxn,collapse=\" \"),\n limiting=NA,\n stringsAsFactors=FALSE))\n \n next\n }else{\n molality_div_stoich <- reactant_molalities[-not_lim_index]/abs(reactant_stoich[-not_lim_index])\n }\n limiting_reactant <- min(molality_div_stoich)\n \n which_limiting <- which(reactant_molalities/abs(reactant_stoich) == limiting_reactant)\n\n # create a string of all limiting reactants\n limiting_reactants <- paste(reactant_names[which_limiting], collapse=\" \")\n\n ### If there is more than one limiting reactant, pick the first one.\n # Prevents warnings when calculating reactant molalities when the limiting\n # reactant runs out. The math should work out the same regardless of which limiting\n # reactant is chosen.\n which_limiting <- which_limiting[1]\n\n # calculate moles of rxn before limiting reactant runs out\n mol_rxn <- reactant_molalities[which_limiting] / abs(reactant_stoich[which_limiting])\n \n # calculate reactant molalities that remain when the limiting reactant runs out\n remaining_reactant_molalities <- reactant_molalities - abs(reactant_stoich) * mol_rxn\n \n # if 'nonlimiting' species are specified by user, restore their molalities back to their original values.\n if(length(not_lim_index) > 0){\n remaining_reactant_molalities[not_lim_index] <- reactant_molalities[not_lim_index]\n }\n\n remaining_react_molal_with_product_molal <- c(remaining_reactant_molalities, product_molalities)\n names(remaining_react_molal_with_product_molal) <- c(reactant_names, product_names)\n\n # attach molalities of other reactants and products that are in the \"mother\" reaction\n if(grepl(\"sub$\", rxn_name)){\n remaining_react_molal_with_product_molal <- c(remaining_react_molal_with_product_molal, other_reactants_and_prod)\n }\n\n ### calculate 'energy' in kJ/kg H2O by multiplying affinity (kJ/mol) by activity (mol/kg) of limiting reactant\n this_energy <- affinity_per_mol_rxn * limiting_reactant\n \n if(!negative_energy_supplies && this_energy < 0){\n this_energy <- 0\n }\n\n } else { # if there is an NA in one of the activities\n affinity_per_mol_rxn <- NA\n affinity_per_mol_e <- NA\n this_energy <- NA\n mol_rxn <- NA\n limiting_reactants <- NA\n }\n\n # unit conversion\n energy_supply <- (this_energy*1000)/4.184 # in cal/kg\n \n # append results\n df_rxn <- rbind(df_rxn, data.frame(rxn=rxn_name,\n affinity=affinity_per_mol_e,\n energy_supply=energy_supply,\n mol_rxn=mol_rxn,\n electrons=electrons,\n reaction=paste(full_rxn,collapse=\" \"),\n limiting=limiting_reactants,\n stringsAsFactors=FALSE))\n } # end rxn loop\n \n rownames(df_rxn) <- df_rxn$rxn\n df_rxn$rxn <- NULL\n\n # create a dataframe for storing results\n df_rxn_sum <- data.frame(affinity = numeric(0),\n energy_supply = numeric(0),\n electrons = numeric(0),\n reaction = character(0),\n stringsAsFactors = FALSE)\n \n ### sum reaction clusters (a reaction and its subreactions)\n if(sum(grepl(\"_sub$\", rownames(df_rxn))) > 0){\n # perform this chunk of code if \"_sub\" rxns are present\n rxn_list_sub <- c() # initialize vector of sub-reaction names\n df_rxn[, \"mol_rxn_perc\"] <- NA # add a new column to df_rxn to store percent mol rxn\n \n for(rxn in c(rownames(df_rxn), \"final_energy\")){\n # loop through columns (plus a dummy \"final_energy\" column)\n \n if(grepl(\"_sub\", rxn)){\n # if the rxn represents a sub-reaction in the cluster, add column name to vector\n rxn_list_sub <- c(rxn_list_sub, rxn)\n \n } else {\n # if the rxn does not represent a sub-reaction...\n if(rxn != \"final_energy\"){\n reaction <- df_rxn[rxn, \"reaction\"]\n }\n \n if(length(rxn_list_sub) != 0){\n # sum the previous reaction cluster and append to dataframe\n rxn_sum_sub_E <- colSums(df_rxn[rxn_list_sub, \"energy_supply\", drop=FALSE])\n rxn_sum_sub_mol <- colSums(df_rxn[rxn_list_sub, \"mol_rxn\", drop=FALSE])\n rxn_clust_sub_A <- df_rxn[rxn_list_sub, , drop=FALSE] %>% mutate(A_weighted=affinity*(mol_rxn/rxn_sum_sub_mol))\n rxn_clust_sub_mol_perc <- df_rxn[rxn_list_sub, , drop=FALSE] %>% mutate(mol_perc=round(100*(mol_rxn/rxn_sum_sub_mol), 1))\n df_rxn[rxn_list_sub, \"mol_rxn_perc\"] <- rxn_clust_sub_mol_perc[, \"mol_perc\"]\n rxn_sum_sub_A <- colSums(rxn_clust_sub_A[, \"A_weighted\", drop=FALSE])\n rxn_sum_row <- data.frame(row.names=rxn_name, \"affinity\"=rxn_sum_sub_A, \"energy_supply\"=rxn_sum_sub_E, electrons=electrons, reaction=reaction)\n df_rxn_sum <- rbind(df_rxn_sum, rxn_sum_row)\n }\n \n # re-initialize vector for new reaction or reaction cluster\n rxn_name <- rxn\n rxn_list_sub <- c(rxn)\n \n }\n }\n }else{\n df_rxn_sum <- df_rxn\n }\n \n # append affinity and energy results to this sample's data\n sample_3o[[\"affinity_energy_raw\"]] <- df_rxn\n sample_3o[[\"affinity_energy\"]] <- df_rxn_sum\n } # end calculation of affinity and energy supply\n \n setwd(\"../\")\n\n return(sample_3o)\n\n}\n\n\n# function to melt aqueous contribution data from multiple samples into\n# a single dataframe and then return it.\nmelt_mass_contribution <- function(batch_3o, other=F, verbose=1){\n\n # initialize empty dataframe\n df_aq_cont <- data.frame(sample=character(0),\n basis=character(0),\n species=character(0),\n factor=character(0),\n molality=character(0),\n percent=character(0),\n stringsAsFactors=FALSE)\n\n # get all aqueous contribution data\n mass_contributions <- lapply(batch_3o[[\"sample_data\"]], `[[`, 'mass_contribution') \n\n # loop through each sample and basis species\n for(sample in names(mass_contributions)){\n if(verbose > 1){\n writeLines(paste0(\"Processing mass contribution of basis species in \", sample, \"...\"))\n }\n for(basis in names(mass_contributions[[sample]])){\n df <- mass_contributions[[sample]][[basis]]\n df[, \"basis\"] <- basis\n df[, \"sample\"] <- sample\n df[, \"species\"] <- rownames(df)\n rownames(df) <- NULL\n \n if(other){\n percent <- round(100-sum(as.numeric(df[, \"percent\"])), 2)\n df <- rbind(df, data.frame(sample=sample,\n basis=basis,\n species=\"Other\",\n factor=NA,\n molality=NA,\n percent=toString(percent),\n stringsAsFactors=FALSE))\n }\n \n df_aq_cont <- rbind(df_aq_cont, df)\n }\n }\n \n df_aq_cont <- df_aq_cont[, c(\"sample\", \"basis\", \"species\", \"factor\", \"molality\", \"percent\")]\n \n return(df_aq_cont)\n\n}\n\n\n# function to create report versions of data categories (aq distributions, etc.)\ncreate_report_df <- function(data, category, out_type){\n\n df_cat <- lapply(data, `[[`, category)\n \n all_species <- unique(unlist(lapply(lapply(df_cat, FUN=t), FUN=colnames)))\n \n df <- read.csv(text=paste(all_species, collapse=\"\\t\"), check.names=FALSE, sep=\"\\t\", stringsAsFactors=FALSE)\n\n for(i in 1:length(df_cat)){\n row <- as.data.frame(t(df_cat[[i]])[out_type, , drop=FALSE], stringsAsFactors=FALSE)\n df <- bind_rows(mutate_all(df, as.character), mutate_all(row, as.character))\n }\n df <- df[, order(colnames(df))]\n df_cat <- cbind.data.frame(sample=names(df_cat), df, stringsAsFactors = FALSE)\n \n return(df_cat)\n \n}\n\n# function to compile a report\ncompile_report <- function(data, csv_filename, aq_dist_type, mineral_sat_type,\n redox_type, get_aq_dist, get_mineral_sat, get_redox,\n get_charge_balance, get_ion_activity_ratios, get_fugacity,\n get_basis_totals, get_affinity_energy, input_processed_df,\n df_input_processed_names){\n \n report_list <- list()\n \n # open processed input file and initialize report with it\n report <- input_processed_df\n names(report) <- df_input_processed_names\n #report <- read.csv(csv_filename, check.names=FALSE, stringsAsFactors=FALSE)\n \n report_list[[\"divs\"]][[\"input\"]] <- names(report)[2:length(report)] # start at 2 to exclude \"sample\" column\n \n # create report versions of EQ3 output blocks\n if(get_aq_dist){\n aq_distribution <- create_report_df(data=data, category='aq_distribution', out_type=aq_dist_type)\n report_list[[\"divs\"]][[\"aq_distribution\"]] <- names(aq_distribution)[2:length(aq_distribution)] # start at 2 to exclude \"sample\" column\n report <- report %>% inner_join(aq_distribution, by=c(\"Sample\"=\"sample\"))\n }\n \n if(get_mineral_sat){\n mineral_sat <- create_report_df(data=data, category='mineral_sat', out_type=mineral_sat_type)\n report_list[[\"divs\"]][[\"mineral_sat\"]] <- names(mineral_sat)[2:length(mineral_sat)] # start at 2 to exclude \"sample\" column\n report <- report %>% inner_join(mineral_sat, by=c(\"Sample\"=\"sample\"))\n }\n \n if(get_redox){\n redox <- create_report_df(data=data, category='redox', out_type=redox_type)\n report_list[[\"divs\"]][[\"redox\"]] <- names(redox)[2:length(redox)] # start at 2 to exclude \"sample\" column\n report <- report %>% inner_join(redox, by=c(\"Sample\"=\"sample\"))\n }\n \n if(get_charge_balance){\n charge_balance <- create_report_df(data=data, category='charge_balance', out_type=1)\n report_list[[\"divs\"]][[\"charge_balance\"]] <- names(charge_balance)[2:length(charge_balance)] # start at 2 to exclude \"sample\" column\n report <- report %>% inner_join(charge_balance, by=c(\"Sample\"=\"sample\"))\n }\n\n if(get_ion_activity_ratios){\n if('ion_activity_ratios' %in% names(data)){\n ion_activity_ratios <- create_report_df(data=data, category='ion_activity_ratios', out_type=1)\n report_list[[\"divs\"]][[\"ion_activity_ratios\"]] <- names(ion_activity_ratios)[2:length(ion_activity_ratios)] # start at 2 to exclude \"sample\" column\n report <- report %>% inner_join(ion_activity_ratios, by=c(\"Sample\"=\"sample\"))\n }\n }\n\n if(get_fugacity){\n fugacities <- create_report_df(data=data, category='fugacity', out_type=1)\n report_list[[\"divs\"]][[\"fugacity\"]] <- names(fugacities)[2:length(fugacities)] # start at 2 to exclude \"sample\" column\n report <- report %>% inner_join(fugacities, by=c(\"Sample\"=\"sample\"))\n }\n\n if(get_basis_totals){\n sc <- create_report_df(data=data, category='basis_totals', out_type=4) # 4 is the molality column\n report_list[[\"divs\"]][[\"basis_totals\"]] <- names(sc)[2:length(sc)] # start at 2 to exclude \"sample\" column\n report <- report %>% inner_join(sc, by=c(\"Sample\"=\"sample\"))\n }\n\n if(get_affinity_energy){\n affinity <- create_report_df(data=data, category='affinity_energy', out_type=1)\n names(affinity)[2:length(names(affinity))] <- paste0(names(affinity)[2:length(names(affinity))], \"_affinity\")\n report_list[[\"divs\"]][[\"affinity\"]] <- names(affinity)[2:length(affinity)] # start at 2 to exclude \"sample\" column\n energy <- create_report_df(data=data, category='affinity_energy', out_type=2)\n names(energy)[2:length(names(energy))] <- paste0(names(energy)[2:length(names(energy))], \"_energy\")\n report_list[[\"divs\"]][[\"energy\"]] <- names(energy)[2:length(energy)] # start at 2 to exclude \"sample\" column\n report <- report %>%\n inner_join(affinity, by=c(\"Sample\"=\"sample\")) %>%\n inner_join(energy, by=c(\"Sample\"=\"sample\"))\n \n }\n\n rownames(report) <- report$Sample\n report$Sample <- NULL\n\n report_list[[\"report\"]] <- report\n \n return(report_list)\n\n}\n\n\n### main\nmain_3o_mine <- function(files_3o,\n rxn_filename,\n get_aq_dist,\n get_mass_contribution,\n get_mineral_sat,\n get_redox,\n get_charge_balance,\n get_ion_activity_ratios,\n get_fugacity,\n get_basis_totals,\n get_solid_solutions,\n get_affinity_energy,\n negative_energy_supplies,\n load_rxn_file,\n not_limiting,\n mass_contribution_other,\n csv_filename,\n aq_dist_type,\n mineral_sat_type,\n redox_type,\n input_filename,\n input_pressures,\n batch_3o_filename,\n df_input_processed,\n df_input_processed_names,\n custom_obigt,\n water_model,\n fixed_species,\n verbose){\n \n start_time <- Sys.time()\n\n water(water_model)\n\n # allow user to add their custom data as an OBIGT\n if(!is.null(custom_obigt)){\n custom_obigt <- read.csv(custom_obigt, stringsAsFactors=F)\n custom_obigt <- custom_obigt[, c(\"name\", \"abbrv\", \"formula\", \"state\", \"ref1\", \"ref2\", \"date\", \"E_units\", \"G\", \"H\", \"S\", \"Cp\", \"V\", \"a1.a\", \"a2.b\", \"a3.c\", \"a4.d\", \"c1.e\", \"c2.f\", \"omega.lambda\", \"z.T\")]\n suppressMessages({\n thermo(OBIGT=thermo()$OBIGT[unique(info(fixed_species)), ]) # replaces the default OBIGT database with user-supplied database\n mod.OBIGT(custom_obigt, replace=TRUE) # produces a message\n })\n }\n\n rxn_table <- NULL\n if(get_affinity_energy){\n if(load_rxn_file){\n # read table of reactions\n rxn_table <- readLines(rxn_filename)\n }else{\n rxn_table <- strsplit(rxn_filename, \"\\n\")[[1]]\n }\n }\n\n # instantiate an empty object to store data from all 3o files\n batch_3o <- list()\n \n if(verbose > 1){\n writeLines(\"Now processing EQ3 output files...\")\n }\n \n names(input_pressures) <- files_3o\n \n # process each .3o file\n for(file in files_3o){\n \n # add this sample's aqueous data to list of all sample data\n sample_3o <- mine_3o(file,\n this_pressure=input_pressures[file],\n rxn_table=rxn_table,\n get_aq_dist=get_aq_dist,\n get_mass_contribution=get_mass_contribution,\n get_mineral_sat=get_mineral_sat,\n get_redox=get_redox,\n get_charge_balance=get_charge_balance,\n get_ion_activity_ratios=get_ion_activity_ratios,\n get_fugacity=get_fugacity,\n get_basis_totals=get_basis_totals,\n get_solid_solutions=get_solid_solutions,\n get_affinity_energy=get_affinity_energy,\n negative_energy_supplies=negative_energy_supplies,\n not_limiting=not_limiting,\n mass_contribution_other=mass_contribution_other,\n verbose=verbose)\n \n # if this file could be processed, add its data to the batch_3o object\n if(length(sample_3o)>1){\n batch_3o[[\"sample_data\"]][[sample_3o[[\"name\"]]]] <- sample_3o\n }\n }\n \n if(verbose > 1){\n writeLines(\"Finished processing EQ3 output files...\")\n }\n \n # compile aqueous contribution data into a single melted dataframe and\n # append it to the batch_3o object.\n if(get_mass_contribution && length(batch_3o)>0){\n if(verbose > 1){\n writeLines(\"Now processing mass contribution data...\")\n }\n batch_3o[[\"mass_contribution\"]] <- melt_mass_contribution(batch_3o=batch_3o,\n other=mass_contribution_other,\n verbose=verbose)\n if(verbose > 1){\n writeLines(\"Finished processing mass contribution data...\")\n }\n }\n \n if(length(batch_3o)>0){\n # create a report summarizing 3o data from all samples\n report_list <- compile_report(data=batch_3o[[\"sample_data\"]],\n csv_filename=csv_filename,\n aq_dist_type,\n mineral_sat_type,\n redox_type,\n get_aq_dist,\n get_mineral_sat,\n get_redox,\n get_charge_balance,\n get_ion_activity_ratios,\n get_fugacity,\n get_basis_totals,\n get_affinity_energy,\n df_input_processed,\n df_input_processed_names)\n \n\n # add the report to the batch_3o object\n report <- report_list[[\"report\"]]\n batch_3o[[\"report\"]] <- report\n batch_3o[[\"report_divs\"]] <- report_list[[\"divs\"]]\n }else{\n return(list())\n }\n\n # store user input file data\n batch_3o[[\"input\"]] <- read.csv(input_filename, check.names=FALSE, stringsAsFactors=FALSE)\n\n # save the batch_3o object as an rds file\n if(!is.null(batch_3o_filename)){\n saveRDS(batch_3o, file=batch_3o_filename)\n }\n \n time_elapsed <- Sys.time() - start_time\n if(verbose > 1){\n writeLines(paste(\"Finished mining .3o files. Time elapsed:\", round(time_elapsed, 2), \"seconds\"))\n }\n\n return(batch_3o)\n}", "meta": {"hexsha": "567470c42da5e6fd98a4c0220a19058bedc4fe5f", "size": 44135, "ext": "r", "lang": "R", "max_stars_repo_path": "AqEquil/3o_mine.r", "max_stars_repo_name": "worm-portal/AqEquil", "max_stars_repo_head_hexsha": "44cf30e779f31ed3fcf57e431ba9e43df99dca94", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2021-11-04T00:44:57.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T18:57:43.000Z", "max_issues_repo_path": "AqEquil/3o_mine.r", "max_issues_repo_name": "worm-portal/AqEquil", "max_issues_repo_head_hexsha": "44cf30e779f31ed3fcf57e431ba9e43df99dca94", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "AqEquil/3o_mine.r", "max_forks_repo_name": "worm-portal/AqEquil", "max_forks_repo_head_hexsha": "44cf30e779f31ed3fcf57e431ba9e43df99dca94", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.9933396765, "max_line_length": 206, "alphanum_fraction": 0.5726067747, "num_tokens": 10784, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.685949467848392, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.3643827869818059}} {"text": "NAME\tHF86\n\nMODE\tREDUCTION\n\nSORTS\tANY\n\nSIGNATURE\n\ta, b, c, d, e, f, g : ANY -> ANY\n sk : -> ANY\nORDERING KBO\n\ta = 5, b = 6, c = 6, d = 6, e = 1, f = 1, g = 1, sk = 1\n\tb > a > c > d > e > f > g > sk\n\nVARIABLES\n\tx : ANY\n\nEQUATIONS\n\t a (e (x)) = e (f (f (f (f (x)))))\n\t b (x) = e (f (f (f (x))))\n\t c (x) = e (f (f (x)))\n\t d (x) = e (f (x))\n\t g (e (x)) = x\n\nCONCLUSION\n% Loesung :\n% e (f (f (f (f (f (f (f (e (f (f (e (f (e (f (g (x)))))))))))))))) =\n% e (f (f (f (f (f (f (f (f (f (f (f (f (f (f (e (x))))))))))))))))\n\n a(b(c(d(e(f(g(sk))))))) = a(c(g(a(a(e(e(sk)))))))\n\n", "meta": {"hexsha": "b25bb366b0bc310349633ba9418a09efd633fe76", "size": 584, "ext": "rd", "lang": "R", "max_stars_repo_path": "src/main/resources/specs/hf86.rd", "max_stars_repo_name": "falsewasnottrue/forstmeister", "max_stars_repo_head_hexsha": "a6402a479d6218b71b12369a97dab8f61e3f9717", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "src/main/resources/specs/hf86.rd", "max_issues_repo_name": "falsewasnottrue/forstmeister", "max_issues_repo_head_hexsha": "a6402a479d6218b71b12369a97dab8f61e3f9717", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "src/main/resources/specs/hf86.rd", "max_forks_repo_name": "falsewasnottrue/forstmeister", "max_forks_repo_head_hexsha": "a6402a479d6218b71b12369a97dab8f61e3f9717", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 18.8387096774, "max_line_length": 69, "alphanum_fraction": 0.3681506849, "num_tokens": 296, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6959583250334526, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.3642787493341494}} {"text": "# Install the required R packages\ninstall.packages(\"vegan\")\ninstall.packages(\"compiler\")\n\nlibrary(vegan) # Contains the function for biodiversity metrics \nlibrary(compiler) # Contains the functions to compile the R-commands to byte code to speed up processing \n\n\niterations <- 5 # Number of iterations (manuscript used 100 iterations)\nts.length <- 100 # Time series length (manuscript used 100,000 time-steps)\nrep.freq <- 10 # Reporting frequency (manuscript reported biodiversity metrics every 1000 time-steps.)\n\nSpec <- 0.0025 # Speciation rate, v (manuscript used these levels: 0.00075, 0.0025, 0.005, 0.01)\nDispersal <- 0.75 # Dispersal rate, m (manuscript used these levels: 0.25, 0.5, 0.75)\nDisp <- (Dispersal/(1-Spec))*1\n\n\n# Reporters for null counter-factual (sr = species richness; ev = species evenness; beta = community dissimilarity; a = local diversity (alpha), g = regional diversity (gamma))\nnull.sr.a <- matrix(NA,ncol=(ts.length/rep.freq),nrow=iterations)\nnull.sr.g <- matrix(NA,ncol=(ts.length/rep.freq),nrow=iterations)\nnull.ev.a <- matrix(NA,ncol=(ts.length/rep.freq),nrow=iterations)\nnull.ev.g <- matrix(NA,ncol=(ts.length/rep.freq),nrow=iterations)\nnull.beta <- matrix(NA,ncol=(ts.length/rep.freq),nrow=iterations)\n\n#Reporters for development (dev) scenario (sr = species richness; ev = species evenness; beta = community dissimilarity; a = local diversity (alpha), g = regional diversity (gamma))\ndev.sr.a <- matrix(NA,ncol=(ts.length/rep.freq),nrow=iterations)\ndev.sr.g <- matrix(NA,ncol=(ts.length/rep.freq),nrow=iterations)\ndev.ev.a <- matrix(NA,ncol=(ts.length/rep.freq),nrow=iterations)\ndev.ev.g <- matrix(NA,ncol=(ts.length/rep.freq),nrow=iterations)\ndev.beta <- matrix(NA,ncol=(ts.length/rep.freq),nrow=iterations)\n\n# Reporters for restoration (res) scenrio (sr = species richness; ev = species evenness; beta = community dissimilarity; a = local diversity (alpha), g = regional diversity (gamma))\nres.sr.a <- matrix(NA,ncol=(ts.length/rep.freq),nrow=iterations)\nres.sr.g <- matrix(NA,ncol=(ts.length/rep.freq),nrow=iterations)\nres.ev.a <- matrix(NA,ncol=(ts.length/rep.freq),nrow=iterations)\nres.ev.g <- matrix(NA,ncol=(ts.length/rep.freq),nrow=iterations)\nres.beta <- matrix(NA,ncol=(ts.length/rep.freq),nrow=iterations)\n\n# Reporters for translocation (tran) scenario (sr = species richness; ev = species evenness; beta = community dissimilarity; a = local diversity (alpha), g = regional diversity (gamma))\ntran.sr.a <- matrix(NA,ncol=(ts.length/rep.freq),nrow=iterations)\ntran.sr.g <- matrix(NA,ncol=(ts.length/rep.freq),nrow=iterations)\ntran.ev.a <- matrix(NA,ncol=(ts.length/rep.freq),nrow=iterations)\ntran.ev.g <- matrix(NA,ncol=(ts.length/rep.freq),nrow=iterations)\ntran.beta <- matrix(NA,ncol=(ts.length/rep.freq),nrow=iterations)\n\n################################################################################\n################################################################################\n\n\n# Function for the forward neutral simulation (death-immigration function)\n# Based on: Buschke, F.T. et al. (2016) Ecology and Evolution, doi:10.1002/ece3.2379\n\ndeath.imm.fun <- function (comm.t,new.K) {\nspecies <- 1:dim(comm.t)[1]\nif (runif(1) < Spec) {\n pres.ab <- ifelse(colSums(comm.t)== 0,0,1)\n N.id <- sample(samples,1,prob=(new.K*pres.ab))\n ind.k <- sample(species,1,prob=comm.t[,N.id])\n new.r <- rep(0,N)\n new.r[N.id] <- 1\n comm.t <- rbind(comm.t,new.r)\n if (sum(comm.t[,N.id]) == new.K[N.id]) {\n comm.t[ind.k,N.id] <- comm.t[ind.k,N.id]-1\n }\n} else{\n if (runif(1)>Disp) {\n pres.ab <- ifelse(colSums(comm.t)== 0,0,1)\n N.id <- sample(samples,1,prob=(new.K*pres.ab))\n ind.k <- sample(species,1,prob=comm.t[,N.id])\n if (sum(comm.t[,N.id]) == new.K[N.id]) {\n comm.t[ind.k,N.id] <- comm.t[ind.k,N.id]-1\n }\n ind.rep <- sample(species,1,prob=comm.t[,N.id])\n comm.t[ind.rep,N.id] <- comm.t[ind.rep,N.id]+1\n } else {\n pres.ab <- ifelse(colSums(comm.t)== 0,0,1)\n N.id <- sample(samples,1,prob=(new.K*pres.ab))\n ind.k <- sample(species,1,prob=comm.t[,N.id])\n if (sum(comm.t[,N.id]) == new.K[N.id]) {\n comm.t[ind.k,N.id] <- comm.t[ind.k,N.id]-1\n }\n \n imm.cell <- sample(samples,1,replace=TRUE, prob = (as.vector(imm.prob[N.id,])*pres.ab))\n \n ind.imm <- sample(species,1,prob=comm.t[,imm.cell])\n comm.t[ind.imm,N.id] <- comm.t[ind.imm,N.id]+1\n }\n}\ncomm.t\n}\n\ndeath.imm <- cmpfun(death.imm.fun)\n\n####################################################################################################\n# The follwing code sets up the landscape\n\nfor (k in 1:iterations) {\n M <- 179 # Number of patches\n Sites <- 1:M\n K <- rep(100,M) # Habitat capacity of each patch\n\n\n# Setting up the dispersal kernel based on inverse-quared distance \ndist.mat <- matrix(NA,nrow=M,ncol=M)\n for (i in 1:M) {\n for (j in 1:M) {\n if (abs(Sites[i] - Sites[j])<=89) {\n dist.mat[i,j] <- abs(Sites[i] - Sites[j])\n } else {\n dist.mat[i,j] <- 179 - (abs(Sites[i] - Sites[j]))\n }\n }\n }\n\ndisp.mat <- 1/(dist.mat^2)\ndiag(disp.mat) <- 0\n\n\n###############################################################################\n\n# Create a vector of the site identification for each species unit.\nsites <- rep(1:M,K)\n\nJ <- sum(K) # total number of species units\n\nsp.name <- 1:J # Start by assigning each species unit a unique ID\nind <- 1:J\n\n# This is a probability vector that determines whether a species unit has already coalesed.\nind.prob <- rep(1,J)\n\n# This is simply to set the counter to display the number of time-steps (starts at 1)\nx <- 1\n\n \n################################################################################\n# Algorithm for the coalescence process to set up the simulation\n# See: Rosindell, J., et al. (2008) Ecological Informatics, 3, 259-271. \n################################################################################\n\n# Start the loop and continue until the number of species in the simulation matches the observed species richness\nwhile(sum(ind.prob)> 0) {\n\n# Choose a species unit at random\nind.id <- sample(ind,1,prob=ind.prob)\n\n# First, Speciation\nif (runif(1)Disp) {\n # Identify the site location of selected species unit\n site.id <- sites[ind.id]\n # Identify a subset of species units that occur in the source patch\n migr.id <- ind[which(sites==site.id)]\n if(length(table(sp.name[migr.id]))>1) {\n # Select a subset of species units that DO NOT already share the same species ID\n imm.id <- migr.id[which(sp.name[migr.id]!=sp.name[ind.id])]\n # Select a parent/immigrant from the source quadrat\n sist.sp <- sample(imm.id,1)\n # Assign the same species ID as the parent species unit to the randomly selected focal species unit\n # AND all other species units that already share that species ID\n sp.name[which(sp.name==ind.id)] <- sp.name[sist.sp]\n }\n # Since the focal bird unit already has an assigned species ID, it is excluded from the model from now on.\n ind.prob[ind.id] <- 0\n } else {\n # Identify the site location of selected species unit\n site.id <- sites[ind.id]\n # Identify the source of selected species unit based on the dispersal kernel\n source.id <- sample(1:M,1,prob=(disp.mat[site.id,]*(K/100)))\n # Identify a subset of species units that occur in the source quadrat\n migr.id <- ind[which(sites==source.id)]\n if(length(table(sp.name[migr.id]))>1) {\n # Select a subset of species units that DO NOT already share the same species ID\n imm.id <- migr.id[which(sp.name[migr.id]!=sp.name[ind.id])]\n # Select a parent/immigrant from the source quadrat\n sist.sp <- sample(imm.id,1)\n # Assign the same species ID as the parent bird unit to the randomly selected focal bird unit\n # AND all other bird units that already share that species ID\n sp.name[which(sp.name==ind.id)] <- sp.name[sist.sp]\n }\n # Since the focal bird unit already has an assigned species ID, it is excluded from the model from now on.\n ind.prob[ind.id] <- 0\n }\n }\n}\n\n# Rearrange the new assemblage into a species-by site matrix\nPatches <- as.matrix(table(sp.name,sites))\n\n \n# Remove the diversity at the offset-receiving site (i.e. recent, but unrelated, degraded habitat)\nPatches[,81:100] <- 0\nK[81:100] <- 0\n\n \n#####################################################################################\n#####################################################################################\n# Run the forward siimulation for scenario 1 (counterfactual)\n \nPatches.null <- Patches\nimm.prob <- disp.mat\n\nN <- dim(Patches.null)[2] \nS <- dim(Patches.null)[1]\n\nspecies <- seq(1:S) \nsamples <- seq(1:N) \n\nfor (i in 1:ts.length){\n Patches.null <- death.imm(Patches.null,K)\n if (i/rep.freq == floor(i/rep.freq))\n {\n # Summarise all the biodiversity metrics\n null.sr.a[k,i/rep.freq] <- mean(colSums(decostand(Patches.null,\"pa\")))\n null.sr.g[k,i/rep.freq] <- length(which(rowSums(decostand(Patches.null,\"pa\"))>0))\n null.ev.a[k,i/rep.freq] <- mean((diversity(t(Patches.null)))/(log(colSums(decostand(Patches.null,\"pa\")))),na.rm=TRUE)\n null.ev.g[k,i/rep.freq] <- mean((diversity(colSums(Patches.null)))/(log(length(which(rowSums(decostand(Patches.null,\"pa\"))>0)))),na.rm=TRUE)\n null.beta[k,i/rep.freq] <- mean(betadisper(vegdist(t(Patches.null[,which(colSums(Patches.null)>0)])), \n as.factor(rep(1,length(which(colSums(Patches.null)>0)))), type = \"centroid\")$distances)\n }\n }\n\n\n#####################################################################################\n#####################################################################################\n# Run the forward siimulation for scenario 2 (No offsets)\n\nPatches.dev <- Patches\nPatches.dev[,c(1:10,170:179)] <- 0\nK.dev <- K\nK.dev[c(1:10,170:179)] <- 0 # Clear the development site\n\nfor (i in 1:ts.length){\n Patches.dev <- death.imm(Patches.dev,K.dev)\n if (i/rep.freq == floor(i/rep.freq))\n {\n # Summarise all the biodiversity metrics\n dev.sr.a[k,i/rep.freq] <- mean(colSums(decostand(Patches.dev,\"pa\")))\n dev.sr.g[k,i/rep.freq] <- length(which(rowSums(decostand(Patches.dev,\"pa\"))>0))\n dev.ev.a[k,i/rep.freq] <- mean((diversity(t(Patches.dev)))/(log(colSums(decostand(Patches.dev,\"pa\")))),na.rm=TRUE)\n dev.ev.g[k,i/rep.freq] <- mean((diversity(colSums(Patches.dev)))/(log(length(which(rowSums(decostand(Patches.dev,\"pa\"))>0)))),na.rm=TRUE)\n dev.beta[k,i/rep.freq] <- mean(betadisper(vegdist(t(Patches.dev[,which(colSums(Patches.dev)>0)])), \n as.factor(rep(1,length(which(colSums(Patches.dev)>0)))), type = \"centroid\")$distances)\n }\n }\n\n\n#####################################################################################\n#####################################################################################\n# Run the forward siimulation for scenario 3 (passive restoration)\n\nPatches.res <- Patches\nPatches.res[,c(1:10,170:179)] <- 0\nK.res <- K\nK.res[c(1:10,170:179)] <- 0 # Clear the development site\nK.res[81:100] <- 100 # Increa the habitat capacity at the offset site\n\nfor (i in 1:ts.length){\n Patches.res <- death.imm(Patches.res,K.res)\n if (i/rep.freq == floor(i/rep.freq))\n {\n # Summarise all the biodiversity metrics\n res.sr.a[k,i/rep.freq] <- mean(colSums(decostand(Patches.res,\"pa\")))\n res.sr.g[k,i/rep.freq] <- length(which(rowSums(decostand(Patches.res,\"pa\"))>0))\n res.ev.a[k,i/rep.freq] <- mean((diversity(t(Patches.res)))/(log(colSums(decostand(Patches.res,\"pa\")))),na.rm=TRUE)\n res.ev.g[k,i/rep.freq] <- mean((diversity(colSums(Patches.res)))/(log(length(which(rowSums(decostand(Patches.res,\"pa\"))>0)))),na.rm=TRUE)\n res.beta[k,i/rep.freq] <- mean(betadisper(vegdist(t(Patches.res[,which(colSums(Patches.res)>0)])), \n as.factor(rep(1,length(which(colSums(Patches.res)>0)))), type = \"centroid\")$distances)\n }\n }\n\n#####################################################################################\n#####################################################################################\n# Run the forward siimulation for scenario 4 (Translocation)\n\nPatches.tran <- Patches\nPatches.tran[,81:100] <- Patches.tran[,c(1:10,170:179)] # Translocate the communities\nPatches.tran[,c(1:10,170:179)] <- 0 # Clear the development site\nK.tran <- K\nK.tran[c(1:10,170:179)] <- 0\nK.tran[81:100] <- 100\n\nfor (i in 1:ts.length){\n Patches.tran <- death.imm(Patches.tran,K.tran)\n if (i/rep.freq == floor(i/rep.freq))\n {\n # Summarise all the biodiversity metrics\n tran.sr.a[k,i/rep.freq] <- mean(colSums(decostand(Patches.tran,\"pa\")))\n tran.sr.g[k,i/rep.freq] <- length(which(rowSums(decostand(Patches.tran,\"pa\"))>0))\n tran.ev.a[k,i/rep.freq] <- mean((diversity(t(Patches.tran)))/(log(colSums(decostand(Patches.tran,\"pa\")))),na.rm=TRUE)\n tran.ev.g[k,i/rep.freq] <- mean((diversity(colSums(Patches.tran)))/(log(length(which(rowSums(decostand(Patches.tran,\"pa\"))>0)))),na.rm=TRUE)\n tran.beta[k,i/rep.freq] <- mean(betadisper(vegdist(t(Patches.tran[,which(colSums(Patches.tran)>0)])), \n as.factor(rep(1,length(which(colSums(Patches.tran)>0)))), type = \"centroid\")$distances)\n }\n }\n\n print(k)\nflush.console()\n}\n\n\n\n#################################################################################\n# Average the biodiversity metric over the 100 iterations\n#################################################################################\n\nm.null.sr.a <- apply(null.sr.a,2,function(x){mean(x,na.rm=TRUE)})\nm.null.sr.g <- apply(null.sr.g,2,function(x){mean(x,na.rm=TRUE)})\nm.null.ev.a <- apply(null.ev.a,2,function(x){mean(x,na.rm=TRUE)})\nm.null.ev.g <- apply(null.ev.g,2,function(x){mean(x,na.rm=TRUE)})\nm.null.beta <- apply(null.beta,2,function(x){mean(x,na.rm=TRUE)})\n\nm.dev.sr.a <- apply(dev.sr.a,2,function(x){mean(x,na.rm=TRUE)})\nm.dev.sr.g <- apply(dev.sr.g,2,function(x){mean(x,na.rm=TRUE)})\nm.dev.ev.a <- apply(dev.ev.a,2,function(x){mean(x,na.rm=TRUE)})\nm.dev.ev.g <- apply(dev.ev.g,2,function(x){mean(x,na.rm=TRUE)})\nm.dev.beta <- apply(dev.beta,2,function(x){mean(x,na.rm=TRUE)})\n\nm.res.sr.a <- apply(res.sr.a,2,function(x){mean(x,na.rm=TRUE)})\nm.res.sr.g <- apply(res.sr.g,2,function(x){mean(x,na.rm=TRUE)})\nm.res.ev.a <- apply(res.ev.a,2,function(x){mean(x,na.rm=TRUE)})\nm.res.ev.g <- apply(res.ev.g,2,function(x){mean(x,na.rm=TRUE)})\nm.res.beta <- apply(res.beta,2,function(x){mean(x,na.rm=TRUE)})\n\nm.tran.sr.a <- apply(tran.sr.a,2,function(x){mean(x,na.rm=TRUE)})\nm.tran.sr.g <- apply(tran.sr.g,2,function(x){mean(x,na.rm=TRUE)})\nm.tran.ev.a <- apply(tran.ev.a,2,function(x){mean(x,na.rm=TRUE)})\nm.tran.ev.g <- apply(tran.ev.g,2,function(x){mean(x,na.rm=TRUE)})\nm.tran.beta <- apply(tran.beta,2,function(x){mean(x,na.rm=TRUE)})\n\n\n#################################################################################\n# This plots the outputs from the simulation\n# Each plot shows how the log response ratio between the offset scenario and the counterfactual varies through time.\n\npar(mfrow=c(2,3)) # Set up a multi-panel plot with 2 rows and three columns.\n\n# Top-left panel is for local species richness\nyval <- seq(rep.freq,ts.length,by=rep.freq)\nplot (log(m.dev.sr.a/m.null.sr.a)~yval,type=\"l\",col=\"red\",ylab=\"Alpha richness\",ylim=c(-.2,.2), xlab=\"Time steps\", main=\"Local species richness\")\nlines(log(m.res.sr.a/m.null.sr.a)~yval,col=\"blue\")\nlines(log(m.tran.sr.a/m.null.sr.a)~yval,col=\"green\")\nabline(h=0,lty=2)\n\n# The top-middle panel is for regional species richness\nplot (log(m.dev.sr.g/m.null.sr.g)~yval,type=\"l\",col=\"red\",ylab=\"Gamma richness\",ylim=c(-.2,.2), xlab=\"Time steps\", main=\"Regional species richness\")\nlines(log(m.res.sr.g/m.null.sr.g)~yval,col=\"blue\")\nlines(log(m.tran.sr.g/m.null.sr.g)~yval,col=\"green\")\nabline(h=0,lty=2)\n\n# The top-right panel is for local species evenness\nplot (log(m.dev.ev.a/m.null.ev.a)~yval,type=\"l\",col=\"red\",ylab=\"Alpha evenness\",ylim=c(-.5,.5), xlab=\"Time steps\", main=\"Local species evenness\")\nlines(log(m.res.ev.a/m.null.ev.a)~yval,col=\"blue\")\nlines(log(m.tran.ev.g/m.null.ev.g)~yval,col=\"green\")\nabline(h=0,lty=2)\n\n# The bottom-left panel is for regional species evenness\nplot (log(m.dev.ev.g/m.null.ev.g)~yval,type=\"l\",col=\"red\",ylab=\"Gamma evennes\",ylim=c(-.2,.2), xlab=\"Time steps\", main=\"Regional species evenness\")\nlines(log(m.res.ev.g/m.null.ev.g)~yval,col=\"blue\")\nlines(log(m.tran.ev.g/m.null.ev.g)~yval,col=\"green\")\nabline(h=0,lty=2)\n\n# The bottom-middle panel is for community dissimilarity\nplot (log(m.dev.beta/m.null.beta)~yval,type=\"l\",col=\"red\",ylab=\"Beta dispersion\",ylim=c(-.05,.05), xlab=\"Time steps\", main=\"Community dissimilarity\")\nlines(log(m.res.beta/m.null.beta)~yval,col=\"blue\")\nlines(log(m.tran.beta/m.null.beta)~yval,col=\"green\")\nabline(h=0,lty=2)\n\n# This plots a makeshift legen in the bottom right panel\nplot(0,0,type=\"n\",xlim=c(0,10),ylim=c(0,10),axes=F, xlab=\"\",ylab=\"\")\nlines (c(1,3),c(8,8),lty=2) \ntext(3.5,8,\"No Net loss\",pos=4)\nlines (c(1,3),c(6,6),col=\"red\") \ntext(3.5,6,\"Scenario 2 (No offset)\",pos=4)\nlines (c(1,3),c(4,4),col=\"blue\") \ntext(3.5,4,\"Scenario 3 (Passive restoration)\",pos=4)\nlines (c(1,3),c(2,2),col=\"green\") \ntext(3.5,2,\"Scenario 4 (Translocation)\",pos=4)\n\n########################################################################################\n########################################################################################\n\n# Write all the outputs to file (will be saved in your default working directory)\nwrite.table(null.sr.a,\"Null_alpha.txt\",quote=F,row.names=F,sep=\"\\t\")\nwrite.table(null.sr.g,\"Null_gamma.txt\",quote=F,row.names=F,sep=\"\\t\")\nwrite.table(null.ev.a,\"Null_even_a.txt\",quote=F,row.names=F,sep=\"\\t\")\nwrite.table(null.ev.g,\"Null_even_g.txt\",quote=F,row.names=F,sep=\"\\t\")\nwrite.table(null.beta,\"Null_beta.txt\",quote=F,row.names=F,sep=\"\\t\")\n\nwrite.table(dev.sr.a,\"Dev_alpha.txt\",quote=F,row.names=F,sep=\"\\t\")\nwrite.table(dev.sr.g,\"Dev_gamma.txt\",quote=F,row.names=F,sep=\"\\t\")\nwrite.table(dev.ev.a,\"Dev_even_a.txt\",quote=F,row.names=F,sep=\"\\t\")\nwrite.table(dev.ev.g,\"Dev_even_g.txt\",quote=F,row.names=F,sep=\"\\t\")\nwrite.table(dev.beta,\"Dev_beta.txt\",quote=F,row.names=F,sep=\"\\t\")\n\nwrite.table(res.sr.a,\"Res_alpha.txt\",quote=F,row.names=F,sep=\"\\t\")\nwrite.table(res.sr.g,\"Res_gamma.txt\",quote=F,row.names=F,sep=\"\\t\")\nwrite.table(res.ev.a,\"Res_even_a.txt\",quote=F,row.names=F,sep=\"\\t\")\nwrite.table(res.ev.g,\"Res_even_g.txt\",quote=F,row.names=F,sep=\"\\t\")\nwrite.table(res.beta,\"Res_beta.txt\",quote=F,row.names=F,sep=\"\\t\")\n\nwrite.table(tran.sr.a,\"Tran_alpha.txt\",quote=F,row.names=F,sep=\"\\t\")\nwrite.table(tran.sr.g,\"Tran_gamma.txt\",quote=F,row.names=F,sep=\"\\t\")\nwrite.table(tran.ev.a,\"Tran_even_a.txt\",quote=F,row.names=F,sep=\"\\t\")\nwrite.table(tran.ev.g,\"Tran_even_g.txt\",quote=F,row.names=F,sep=\"\\t\")\nwrite.table(tran.beta,\"Tran_beta.txt\",quote=F,row.names=F,sep=\"\\t\")\n", "meta": {"hexsha": "5e6a1f6a5356364fbadffdff3d1207e9c79dfe2f", "size": 19195, "ext": "r", "lang": "R", "max_stars_repo_path": "Neutral_simulations.r", "max_stars_repo_name": "falko-buschke/biodiversity-offsets-neutral-theory", "max_stars_repo_head_hexsha": "0d1cb3a7c767690146844d1d7efae504d8da7ed9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Neutral_simulations.r", "max_issues_repo_name": "falko-buschke/biodiversity-offsets-neutral-theory", "max_issues_repo_head_hexsha": "0d1cb3a7c767690146844d1d7efae504d8da7ed9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Neutral_simulations.r", "max_forks_repo_name": "falko-buschke/biodiversity-offsets-neutral-theory", "max_forks_repo_head_hexsha": "0d1cb3a7c767690146844d1d7efae504d8da7ed9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2022-03-27T07:24:15.000Z", "max_forks_repo_forks_event_max_datetime": "2022-03-27T07:24:15.000Z", "avg_line_length": 46.5898058252, "max_line_length": 185, "alphanum_fraction": 0.6110966397, "num_tokens": 5538, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6757646010190476, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.36422578108397413}} {"text": "# first make a a determenisti and stochastic forcast and save the results in for.det and for.sto\n# load('run/FORECAST.RData'); for.det<-forecast; summary(for.det); summary(for.det[[1]]);\n# load('run/FORECAST.RData'); for.sto<-forecast ; summary(for.sto); summary(for.sto[[1]]);\n\n# N2013\nN2013.sto<-lapply(for.sto,function(x){exp(apply(x$last.state.sim[,1:10],2,median))}) \nN2013.det<-lapply(for.det,function(x){exp(apply(x$last.state.sim[,1:10],2,median))}) \nN2013.det\nmatrix(unlist(N2013.sto),ncol=10,byrow=T)/matrix(unlist(N2013.det),ncol=10,byrow=T)\n\n\n\n# N2014\nN2014.sto<-lapply(for.sto,function(x){exp(apply(x$s1.state.sim[,1:10],2,median))}) \nN2014.det<-lapply(for.det,function(x){exp(apply(x$s1.state.sim[,1:10],2,median))}) \nN2014.det\nmatrix(unlist(N2014.sto),ncol=10,byrow=T)/matrix(unlist(N2014.det),ncol=10,byrow=T)\n\nSSB2014.sto<-lapply(for.sto,function(x){(apply(x$s1.ssb.sim,2,median))}) \nSSB2014.det<-lapply(for.det,function(x){(apply(x$s1.ssb.sim,2,median))}) \nunlist(SSB2014.sto)/unlist(SSB2014.det)\n\n\nfor.det[[1]]$s2.ssb.sim\n\n# N2015 \nN2015.sto<-lapply(for.sto,function(x){exp(apply(x$s2.state.sim[,1:10],2,median))}) \nN2015.det<-lapply(for.det,function(x){exp(apply(x$s2.state.sim[,1:10],2,median))}) \nN2015.det\nround(matrix(unlist(N2015.sto),ncol=10,byrow=T)/matrix(unlist(N2015.det),ncol=10,byrow=T),4)\n\n#WB herring\nSSB2015.sto<-lapply(for.sto,function(x){median(x$s2.ssb.sim,2)}) \nSSB2015.det<-lapply(for.det,function(x){median(x$s2.ssb.sim,2)}) \n\n\nSSB2015.sto<-lapply(for.sto,function(x){(apply(x$s2.ssb.sim,2,median))}) \nSSB2015.det<-lapply(for.det,function(x){(apply(x$s2.ssb.sim,2,median))}) \n\nunlist(SSB2015.sto)/unlist(SSB2015.det)\n\n\n\n# N2016 \nN2016.sto<-lapply(for.sto,function(x){exp(apply(x$s3.state.sim[,1:10],2,median))}) \nN2016.det<-lapply(for.det,function(x){exp(apply(x$s3.state.sim[,1:10],2,median))}) \nN2016.det\nround(matrix(unlist(N2016.sto),ncol=10,byrow=T)/matrix(unlist(N2016.det),ncol=10,byrow=T),4)\n\n\n\nSSB2016.sto<-lapply(for.sto,function(x){(apply(x$s3.ssb.sim,2,median))}) \nSSB2016.det<-lapply(for.det,function(x){(apply(x$s3.ssb.sim,2,median))}) \n \n#WB herring\nSSB2016.sto<-lapply(for.sto,function(x){median(x$s3.ssb.sim,2)}) \nSSB2016.det<-lapply(for.det,function(x){median(x$s3.ssb.sim,2)}) \n\nround(unlist(SSB2016.sto)/unlist(SSB2016.det),4)\n\nfor.det[[1]]$s2.catch.sim\nC2015.sto<-lapply(for.sto,function(x){(median(x$s2.catch.sim))}) \nC2015.det<-lapply(for.det,function(x){(median(x$s2.catch.sim))}) \nround(unlist(C2015.sto)/unlist(C2015.det),4)\n\n\n\n#WB herring\nSSB2015.sto<-lapply(for.sto,function(x){median(x$s2.ssb.sim,2)}) \nSSB2015.det<-lapply(for.det,function(x){median(x$s2.ssb.sim,2)}) \n\n\n# extract N 2015 from the first forecast option\nmatrix(unlist(N2015.sto),ncol=10,byrow=T)\nN<-matrix(unlist(N2015.sto),ncol=10,byrow=T)[1,]\nN\n\n# just checing they are the same\nfor.sto[[1]]$ave.sw\nfor.det[[1]]$ave.sw\n\nsum(for.sto[[1]]$ave.sw*for.sto[[1]]$ave.pm*N) # the simple way\nN %*% (for.sto[[1]]$ave.sw*for.sto[[1]]$ave.pm) # the Anders way\nSSB2015.sto[[1]]\nSSB2015.sto[[1]] / sum(for.sto[[1]]$ave.sw*for.sto[[1]]$ave.pm*N)\n\nsum(for.det[[1]]$ave.sw*for.sto[[1]]$ave.pm*N) # the simple way\nN %*% (for.sto[[1]]$ave.sw*for.sto[[1]]$ave.pm) # the Anders way\nSSB2015.det[[1]]\nSSB2015.det[[1]] /sum(for.det[[1]]$ave.sw*for.sto[[1]]$ave.pm*N) \n\n\n#The right way\nlapply(for.det,function(x){apply(exp(x$s2.state.sim[,1:10])*rep(x$ave.sw*x$ave.pm,each=2),1,sum)}) \nSSB2015.det<-lapply(for.det,function(x){median(apply(exp(x$s2.state.sim[,1:10])*rep(x$ave.sw*x$ave.pm,each=2),1,sum))}) \n\nlapply(for.sto,function(x){apply(exp(x$s2.state.sim[,1:10])*rep(x$ave.sw*x$ave.pm,each=1000),1,sum)})\nSSB2015.sto<-lapply(for.sto,function(x){median(apply(exp(x$s2.state.sim[,1:10])*rep(x$ave.sw*x$ave.pm,each=1000),1,sum))}) \n\nunlist(SSB2015.sto)/unlist(SSB2015.det)\n\n# ###########################################\n library(MASS)\n \nnoSim<-30000\nvar1<-0.8\nvar2<-var1*0.75\nvar12<-0.1 # co-var\nmu1<-4\nmu2<-mu1/2\nweight<-c(1,10)\nsigma<-matrix(c(var1,var12,var12,var2),ncol=2)\nlogN<-mvrnorm(noSim, mu=c(mu1,mu2), Sigma=sigma)\n\nplot(logN[,1],logN[,2])\nhist(logN[,1])\n\nN<-exp(logN)\nN.median<-apply(N,2,median)\n#N.median\nif (noSim<=10) log(N.median)\nif (noSim<=10) c(mu1,mu2) # there is no bias in N\nbio.deter<-exp(c(mu1,mu2))*weight\nif (noSim<=10) bio.deter\nbio.deter<-sum(bio.deter)\nif (noSim<=10) bio.deter\n\nif (noSim<=10) N\nbio<-N*rep(weight,each=noSim)\nif (noSim<=10) bio\n\nbio<-apply(bio,1,sum)\nif (noSim<=10) bio\nbio.sto<-median(bio)\n\nbio.sto/bio.deter\n#######\n\n# The same, but mu and variance and weight is the same for both of them\n\nnoSim<-1000000\nsd1<-0.8\nvar1<-sd1**2\nvar2<-var1\nvar12<-var1/4 # co-var\nmu1<-4\nmu2<-mu1*1\nweight<-c(1,1)\nsigma<-matrix(c(var1,var12,var12,var2),ncol=2)\nlogN<-mvrnorm(noSim, mu=c(mu1,mu2), Sigma=sigma)\n\npar(mfcol=c(2,2))\nhist(logN[,1],xlab='logN1',main=paste(\"age 1, logN, mean:\",round(mean(logN[,1]),4)))\nabline(v=mean(logN[,1]),col='red')\n\nhist(exp(logN[,1]),xlab='exp(logN1)',main=paste(\"age 1, exp(logN),median:\",round(median(exp(logN[,1])),4),'\\n exp(logN):',round(exp(mu1),4)))\nabline(v=median(exp(logN[,1])),col='red')\n\nhist(logN[,2],xlab='logN2',main=paste(\"age 2, logN, mean:\",round(mean(logN[,2]),4)))\nabline(v=mean(logN[,2]),col='red')\n\nhist(exp(logN[,2]),xlab='exp(logN1)',main=paste(\"age 2, exp(logN),median:\",round(median(exp(logN[,2])),4),'\\n exp(logN):',round(exp(mu1),4)))\nabline(v=median(exp(logN[,2])),col='red')\n\npar(mfcol=c(1,1))\n\nN<-exp(logN)\nbio.deter<-exp(c(mu1,mu2))*weight\nbio.deter<-sum(bio.deter)\nbio.deter\n\nbio<-N*rep(weight,each=noSim)\nbio<-apply(bio,1,sum)\nbio.sto<-median(bio)\nhist(bio,main=paste('median bio:',round(bio.sto,4),'\\n determ bio:',round(bio.deter,4),'\\n ratio stock:determ',round(bio.sto/bio.deter,4)))\nabline(v=bio.sto,col='red')\n\n#######\n\nneafc<-function(sd1=0.8,var2Fac=1,mu1=4,mu2Fac=1,noSim=100000,weight=c(1,10)){\n var1<-sd1*sd1\n var2<-var1*var2Fac\n var12<-var1/5 # co-var \n \n mu2<-mu1*mu2Fac\n sigma<-matrix(c(var1,var12,var12,var2),ncol=2)\n logN<-mvrnorm(noSim, mu=c(mu1,mu2), Sigma=sigma)\n N<-exp(logN)\n bio.sto<-N*rep(weight,each=noSim)\n bio.sto.corrected<-bio.sto # \"corrected\" later on\n\n bio.sto<-apply(bio.sto,1,sum)\n bio.sto<-median(bio.sto)\n\n #cat('\\nbefore adjustement')\n #print(bio.sto.corrected) \n \n cor.fac<-exp(rep(0.5*c(var1,var2),each=noSim))\n #print(cor.fac)\n \n bio.sto.corrected<-bio.sto.corrected/cor.fac\n \n #cat('\\nafter adjustement\\n')\n #print(bio.sto.corrected)\n bio.sto.corrected<-apply(bio.sto.corrected,1,sum)\n #cat('\\nsum after adjustement\\n')\n #print(bio.sto.corrected)\n bio.sto.corrected<-mean( bio.sto.corrected)\n # cat('\\nmean of sum after adjustement\\n')\n #print(bio.sto.corrected)\n \n bio.deter<-sum(exp(c(mu1,mu2))*weight)\n \n return(list(dterm=bio.deter,stoch=bio.sto,stoch.corr=bio.sto.corrected))\n}\n\n\nsd1<-seq(0.1,1.0,0.05)\ndo.it<-function(i){neafc(sd1=sd1[i],mu2Fac=1,var2Fac=1,weight=c(1,1)) }\nres<-lapply(1:length(sd1),do.it)\n\nres<-matrix(unlist(res),ncol=3,byrow=T)\nmatplot(sd1,res,ylab='Absolute values') #abs values\n\nmatplot(sd1,res/rep(res[,1],each=3),ylab='Relativ to deterministic') #relative to deterministic values\n\n\n", "meta": {"hexsha": "82733a4b2751728dbbd7ea9a2aed1ed9bd86e0e9", "size": 7136, "ext": "r", "lang": "R", "max_stars_repo_path": "SMS_R_prog/r_prog_less_frequently_used/neafc.r", "max_stars_repo_name": "ices-eg/wg_WGSAM", "max_stars_repo_head_hexsha": "d5f93c431d1ec6c2fb1f3929f63cd9e636fc258a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-09-28T11:13:54.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-28T08:40:03.000Z", "max_issues_repo_path": "SMS_R_prog/r_prog_less_frequently_used/neafc.r", "max_issues_repo_name": "ices-eg/wg_WGSAM", "max_issues_repo_head_hexsha": "d5f93c431d1ec6c2fb1f3929f63cd9e636fc258a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "SMS_R_prog/r_prog_less_frequently_used/neafc.r", "max_forks_repo_name": "ices-eg/wg_WGSAM", "max_forks_repo_head_hexsha": "d5f93c431d1ec6c2fb1f3929f63cd9e636fc258a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 31.298245614, "max_line_length": 141, "alphanum_fraction": 0.6748878924, "num_tokens": 2780, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.679178699175393, "lm_q2_score": 0.5350984286266115, "lm_q1q2_score": 0.36342745468541887}} {"text": "# Benjamini-Hochberg procedure\n\nbh_apply <- function(data, alpha=0.05, time_windows=list(c(300, 500), c(600, 1000))) {\n tws <- time_windows\n dt <- data[, lapply(.SD, mean), by=list(Timestamp, Electrode), .SDcols=colnames(data)[grep(\"pval\", colnames(data))]]\n for (i in colnames(dt)[grep(\"pval\", colnames(dt))]) {\n dt[, paste0(\"sig_\", i)] <- rep(FALSE, nrow(dt))\n for (j in tws) { \n signi <- (p.adjust(dt[Timestamp >= j[1] & Timestamp <= j[2], ..i][[1]], method='fdr') < alpha)\n indi <- which(dt$Timestamp >= j[1] & dt$Timestamp <= j[2])\n dt[indi, paste0(\"sig_\", i) := signi]\n }\n }\n \n cols <- c(\"Timestamp\", \"Electrode\", colnames(dt)[grep(\"sig\", colnames(dt))])\n merge(data, dt[,..cols], by=c(\"Timestamp\", \"Electrode\"))\n}\n\nbh_apply_bonf <- function(data, alpha=0.05, time_windows=list(c(300, 500), c(600, 1000))) {\n tws <- time_windows\n dt <- data[, lapply(.SD, mean), by=list(Timestamp, Electrode), .SDcols=colnames(data)[grep(\"pval\", colnames(data))]]\n for (i in colnames(dt)[grep(\"pval\", colnames(dt))]) {\n dt[, paste0(\"sig_\", i)] <- rep(FALSE, nrow(dt))\n for (j in tws) { \n signi <- (p.adjust(dt[Timestamp >= j[1] & Timestamp <= j[2], ..i][[1]], method='none') < alpha)\n indi <- which(dt$Timestamp >= j[1] & dt$Timestamp <= j[2])\n dt[indi, paste0(\"sig_\", i) := signi]\n }\n }\n \n cols <- c(\"Timestamp\", \"Electrode\", colnames(dt)[grep(\"sig\", colnames(dt))])\n merge(data, dt[,..cols], by=c(\"Timestamp\", \"Electrode\"))\n}\n\nbh_apply_sepelec <- function(data, alpha=0.05, time_windows=list(c(300, 500), c(600, 1000))) {\n tws <- time_windows\n elecs <- c(\"Fz\", \"Cz\", \"Pz\")\n dt <- data[, lapply(.SD, mean), by=list(Timestamp, Electrode), .SDcols=colnames(data)[grep(\"pval\", colnames(data))]]\n for (i in colnames(dt)[grep(\"pval\", colnames(dt))]) {\n dt[, paste0(\"sig_\", i)] <- rep(FALSE, nrow(dt))\n for (j in tws) {\n for (e in elecs) {\n signi <- (p.adjust(dt[Timestamp >= j[1] & Timestamp <= j[2] & Electrode == e, ..i][[1]], method='fdr') < alpha)\n indi <- which(dt$Timestamp >= j[1] & dt$Timestamp <= j[2] & dt$Electrode == e)\n dt[indi, paste0(\"sig_\", i) := signi]\n } \n }\n }\n \n cols <- c(\"Timestamp\", \"Electrode\", colnames(dt)[grep(\"sig\", colnames(dt))])\n merge(data, dt[,..cols], by=c(\"Timestamp\", \"Electrode\"))\n}\n\n\nbh_apply_poolall <- function(data, alpha=0.05, time_windows=list(c(300, 500), c(600, 1000))) {\n tws <- time_windows\n elecs <- c(\"Fz\", \"Cz\", \"Pz\")\n dt <- data[, lapply(.SD, mean), by=list(Timestamp, Electrode), .SDcols=colnames(data)[grep(\"pval\", colnames(data))]]\n for (i in colnames(dt)[grep(\"pval\", colnames(dt))]) {\n dt[, paste0(\"sig_\", i)] <- rep(FALSE, nrow(dt))\n signi <- (p.adjust(dt[(Timestamp >= 300 & Timestamp <= 500) | (Timestamp >= 600 & Timestamp <= 1000), ..i][[1]], method='fdr') < alpha)\n indi <- which((dt$Timestamp >= 300 & dt$Timestamp <= 500) | (dt$Timestamp >= 600 & dt$Timestamp <= 1000))\n dt[indi, paste0(\"sig_\", i) := signi]\n }\n \n cols <- c(\"Timestamp\", \"Electrode\", colnames(dt)[grep(\"sig\", colnames(dt))])\n merge(data, dt[,..cols], by=c(\"Timestamp\", \"Electrode\"))\n}\n\nbh_none <- function(data, alpha=0.05, time_windows=list(c(300, 500), c(600, 1000))) {\n tws <- time_windows\n elecs <- c(\"Fz\", \"Cz\", \"Pz\")\n dt <- data[, lapply(.SD, mean), by=list(Timestamp, Electrode), .SDcols=colnames(data)[grep(\"pval\", colnames(data))]]\n for (i in colnames(dt)[grep(\"pval\", colnames(dt))]) {\n dt[, paste0(\"sig_\", i)] <- rep(FALSE, nrow(dt))\n signi <- dt[(dt$Timestamp >= 300 & dt$Timestamp <= 500) | (dt$Timestamp >= 600 & dt$Timestamp <= 1000),..i] < alpha\n indi <- which((dt$Timestamp >= 300 & dt$Timestamp <= 500) | (dt$Timestamp >= 600 & dt$Timestamp <= 1000))\n dt[indi, paste0(\"sig_\", i) := signi]\n }\n\n cols <- c(\"Timestamp\", \"Electrode\", colnames(dt)[grep(\"sig\", colnames(dt))])\n merge(data, dt[,..cols], by=c(\"Timestamp\", \"Electrode\"))\n}\n\nbh_identify_cutoff <- function(pvals, alpha = 0.05)\n{\n pvals <- sort(pvals) # sort ascending\n m <- length(pvals) # number of hypotheses\n k <- 1 # k iterator\n for (k in seq(1:m)){\n if (pvals[k] >= k/m * alpha) {\n break()\n } \n }\n # while (pvals[k] < (k / m) * alpha)\n # k <- k + 1\n return(pvals[k])\n}\n\nbh_plot <- function(pvals, alpha = 0.05)\n{\n pvals <- sort(pvals) # sort ascending\n m <- length(pvals) # number of hypothesis \n ks <- seq(1, length(pvals), 1)\n plot(pvals ~ ks)\n abline(0, alpha / m)\n}\n", "meta": {"hexsha": "1ad4de54ff45e36057e2fc66596796290c745ee0", "size": 5350, "ext": "r", "lang": "R", "max_stars_repo_path": "benjamini-hochberg.r", "max_stars_repo_name": "SFB1102/A1-PLOSONE21lmerERP", "max_stars_repo_head_hexsha": "63adf9c68d3d36a76b8d304648fdd07541c181eb", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "benjamini-hochberg.r", "max_issues_repo_name": "SFB1102/A1-PLOSONE21lmerERP", "max_issues_repo_head_hexsha": "63adf9c68d3d36a76b8d304648fdd07541c181eb", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "benjamini-hochberg.r", "max_forks_repo_name": "SFB1102/A1-PLOSONE21lmerERP", "max_forks_repo_head_hexsha": "63adf9c68d3d36a76b8d304648fdd07541c181eb", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 49.537037037, "max_line_length": 159, "alphanum_fraction": 0.4856074766, "num_tokens": 1551, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.7154239836484144, "lm_q2_score": 0.5078118642792044, "lm_q1q2_score": 0.3633007868865564}} {"text": "################################################################################\n# \n# Simulation script\n# \n# Andrew Robinson 15-April-2015\n#\n################################################################################\n\n\nthe.seed <- 10000000\n\nreps <- 1000\ncores <- 25\n\nMAIL <- TRUE\n\nmail <- function(address, subject, message, attach = NULL) {\n if (MAIL)\n if (is.null(attach)) {\n system(paste(\"echo '\", message,\n \"' | mutt -s '\", subject,\n \"' \", address, sep=\"\"))\n } else {\n system(paste(\"echo '\", message,\n \"' | mutt -s '\", subject, \"'\",\n \" \", address,\n paste(\" -a \", attach, collapse=\" \"), sep=\"\"))\n }\n}\n\nmail.and.stop <- function() {\n mail(\"mensurationist@gmail.com\",\n \"Sims on server: ERROR.\",\n \"Stopped.\")\n stop()\n}\n\noptions(error = mail.and.stop)\n\n\nlibrary(lme4) # For mixed-effects models\n\nlibrary(Amelia) # For imputation\n\nlibrary(equivalence) # For data that I know\n\nlibrary(parallel) # Speed things up\n\ndata(ufc)\n\nstr(ufc)\n\nufc <- subset(ufc, !is.na(Dbh))\nufc$Species[ufc$Species %in% c(\"F\",\"FG\")] <- \"GF\"\nufc$Species <- factor(ufc$Species)\nufc$ht.measured <- is.na(ufc$Height)\n\nufc <- subset(ufc,\n Species %in% names(sort(-table(Species)))[1:6],\n select = c(\"ht.measured\",\"Plot\",\"Dbh.in\",\"Species\"))\n\n## Fit a pair of models to compare using LRT\n\nufc.whole <- ufc\n\nisna.1.w <- glmer(ht.measured ~ Dbh.in + Species + (1 | Plot),\n data = ufc.whole, family = binomial)\nisna.0.w <- glmer(ht.measured ~ Dbh.in + (1 | Plot),\n data = ufc.whole, family = binomial)\n\nanova(isna.0.w, isna.1.w)\n\n################################################################################\n\nimputeLRT <- function(h0, h1, imputed.data.list) {\n m <- length(imputed.data.list)\n h0.models <- lapply(imputed.data.list,\n function (dataset) {\n update(h0, data = dataset)\n })\n h0.dev.funs <- lapply(imputed.data.list,\n function (dataset) {\n update(h0, data = dataset,\n devFunOnly = TRUE)\n })\n Q.bar.0 <-\n colMeans(do.call(rbind,\n lapply(h0.models,\n function (fit) {\n c(getME(fit, \"theta\"), fixef(fit))\n }))) \n h1.models <- lapply(imputed.data.list,\n function (dataset) {\n update(h1, data = dataset)\n })\n h1.dev.funs <- lapply(imputed.data.list,\n function (dataset) {\n update(h1, data = dataset,\n devFunOnly = TRUE)\n })\n Q.bar.1 <-\n colMeans(do.call(rbind,\n lapply(h1.models,\n function (fit) {\n c(getME(fit, \"theta\"), fixef(fit))\n })))\n d.prime.m.bar <- mean(unlist(lapply(1:m,\n function(i) {\n anova(h0.models[[i]],\n h1.models[[i]])$Chisq[2]\n })))\n d.L.bar <- mean(unlist(lapply(1:m,\n function(i) {\n h0.dev.funs[[i]](Q.bar.0) - \n h1.dev.funs[[i]](Q.bar.1) \n })))\n p0 <- length(Q.bar.0)\n p1 <- length(Q.bar.1)\n k <- p1 - p0\n rL <- (m + 1) / ((m - 1) * k) * (d.prime.m.bar - d.L.bar) # 3.8\n D.L <- d.L.bar / ((1 + rL) * k) # 3.7\n v <- k * (m - 1) \n w <- ifelse(v > 4, # 2.7 \n 4 + (v - 4) * (1 + (1 - v/2) / rL)^2,\n v / 2 * (1 + 1/k) * (1 + 1/rL)^2)\n Pval <- 1 - pf(D.L, k, w)\n return(list(\n D.L = D.L,\n Pval = Pval,\n rL = rL,\n d.L.bar = d.L.bar,\n d.prime.m.bar = d.prime.m.bar,\n Q.bar.0 = Q.bar.0,\n Q.bar.1 = Q.bar.1,\n k = k,\n w = w,\n p0 = p0,\n p1 = p1,\n m = m))\n}\n\n\nisna.1 <- glmer(ht.measured ~ Dbh.in + Species + (1 | Plot),\n data = ufc, family = binomial)\nisna.0 <- glmer(ht.measured ~ Dbh.in + (1 | Plot),\n data = ufc, family = binomial) \n\nimputeLRT(isna.0, isna.1,\n list(ufc, ufc, ufc, ufc, ufc))\n\nanova(isna.0, isna.1)\n\n\n\nsimulate <- function(m = 5, n = 30) {\n make.missing <- sample(1:nrow(ufc), size = n * 3, replace = FALSE)\n is.na(ufc$Species[make.missing[1:n]]) <- TRUE\n is.na(ufc$Dbh.in[make.missing[(n+1):(2*n)]]) <- TRUE\n is.na(ufc$ht.measured[make.missing[(2*n+1):(3*n)]]) <- TRUE\n isna.1 <- glmer(ht.measured ~ Dbh.in + Species + (1 | Plot),\n data = ufc, family = binomial)\n isna.0 <- glmer(ht.measured ~ Dbh.in + (1 | Plot),\n data = ufc, family = binomial) \n naive.p <- anova(isna.0, isna.1)[[\"Pr(>Chisq)\"]][2]\n ## Impute datasets using Amelia\n ufc.imputes <- amelia(ufc,\n m = m,\n cs = \"Plot\",\n noms = \"Species\",\n p2s = 0)\n imputed <- imputeLRT(isna.0, isna.1, ufc.imputes$imputations)\n return(list(naive.p = naive.p, imputed.p = imputed$Pval))\n}\n\nsimulate()\n\nframe <- expand.grid(ms = c(2, 5, 10, 20, 50, 100),\n ns = c(5, 10, 20, 30, 50, 100),\n reps = 1:reps)\n\nresults <- mclapply(1:nrow(frame),\n function(i) \n simulate(frame$ms[i], frame$ns[i]),\n mc.cores = cores)\n\nresults <- do.call(rbind, results)\n\nexperiment <- cbind(frame, results)\n\nsave(experiment, file = \"mi.RData\")\n\nmail(address = \"andrewpr\",\n subject = \"MI simulations\",\n message = \"All done.\",\n attach = \"mi.RData\")\n\n\n", "meta": {"hexsha": "423c949e9ff7d0f1b0c5971305c05154f3abae28", "size": 5936, "ext": "r", "lang": "R", "max_stars_repo_path": "scripts/experiment-sims.r", "max_stars_repo_name": "SteveLane/blistering-barnacles", "max_stars_repo_head_hexsha": "0fbe0071e290547565b53bf2ecb2cbf92b01ccdf", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scripts/experiment-sims.r", "max_issues_repo_name": "SteveLane/blistering-barnacles", "max_issues_repo_head_hexsha": "0fbe0071e290547565b53bf2ecb2cbf92b01ccdf", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 6, "max_issues_repo_issues_event_min_datetime": "2017-09-12T05:04:30.000Z", "max_issues_repo_issues_event_max_datetime": "2017-11-08T22:37:45.000Z", "max_forks_repo_path": "scripts/experiment-sims.r", "max_forks_repo_name": "SteveLane/blistering-barnacles", "max_forks_repo_head_hexsha": "0fbe0071e290547565b53bf2ecb2cbf92b01ccdf", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2017-08-28T04:09:34.000Z", "max_forks_repo_forks_event_max_datetime": "2017-08-28T04:09:34.000Z", "avg_line_length": 29.9797979798, "max_line_length": 80, "alphanum_fraction": 0.4290768194, "num_tokens": 1661, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802735722127, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.36311054136073484}} {"text": "subroutine locn(i,j,kj,nadj,madj,x,y,ntot,eps)\n\n# Find the appropriate location for j in the adjacency list\n# of i. This is the index which j ***will*** have when\n# it is inserted into the adjacency list of i in the\n# appropriate place. Called by insrt.\n\nimplicit double precision(a-h,o-z)\ndimension nadj(-3:ntot,0:madj), x(-3:ntot), y(-3:ntot)\nlogical before\n\nn = nadj(i,0)\n\n# If there is nothing already adjacent to i, then j will have place 1.\nif(n==0) {\n kj = 1\n return\n}\n\n# Run through i's list, checking if j should come before each element\n# of that list. (I.e. if i, j, and k are in anti-clockwise order.)\n# If j comes before the kj-th item, but not before the (kj-1)-st, then\n# j should have place kj.\ndo ks = 1,n {\n\tkj = ks\n k = nadj(i,kj)\n call acchk(i,j,k,before,x,y,ntot,eps)\n if(before) {\n km = kj-1\n if(km==0) km = n\n k = nadj(i,km)\n call acchk(i,j,k,before,x,y,ntot,eps)\n if(before) next\n # If j is before 1 and after n, then it should\n # have place n+1.\n if(kj==1) kj = n+1\n return\n }\n}\n\n# We've gone right through the list and haven't been before\n# the kj-th item ***and*** after the (kj-1)-st on any occasion.\n# Therefore j is before everything (==> place 1) or after\n# everything (==> place n+1).\nif(before) kj = 1\nelse kj = n+1\n\nreturn\nend\n", "meta": {"hexsha": "e2b581d8a5d3b5975a530b95a3784ac007c30851", "size": 1441, "ext": "r", "lang": "R", "max_stars_repo_path": "VisUncertainty/bin/Debug/R-3.4.4/library/deldir/ratfor/locn.r", "max_stars_repo_name": "hyeongmokoo/SAAR_beta1", "max_stars_repo_head_hexsha": "7406f30d7f39a03e8494b2171c2bc09904a36f62", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-08-23T15:35:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-24T12:20:59.000Z", "max_issues_repo_path": "VisUncertainty/bin/Debug/R-3.4.4/library/deldir/ratfor/locn.r", "max_issues_repo_name": "hyeongmokoo/SAAR_beta1", "max_issues_repo_head_hexsha": "7406f30d7f39a03e8494b2171c2bc09904a36f62", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-08-17T15:14:11.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-23T21:55:49.000Z", "max_forks_repo_path": "VisUncertainty/bin/Debug/R-3.4.4/library/deldir/ratfor/locn.r", "max_forks_repo_name": "hyeongmokoo/SAAR_beta1", "max_forks_repo_head_hexsha": "7406f30d7f39a03e8494b2171c2bc09904a36f62", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-11-04T05:34:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-04T05:34:16.000Z", "avg_line_length": 28.82, "max_line_length": 70, "alphanum_fraction": 0.5850104094, "num_tokens": 436, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.3618984898985668}} {"text": "subroutine swap(j,k1,k2,shdswp,nadj,madj,x,y,ntot,eps,nerror)\n\n# The segment k1->k2 is a diagonal of a quadrilateral\n# with a vertex at j (the point being added to the\n# triangulation). If the LOP is not satisfied, swap\n# it for the other diagonal.\n# Called by addpt.\n\nimplicit double precision(a-h,o-z)\ndimension nadj(-3:ntot,0:madj), x(-3:ntot), y(-3:ntot)\ndimension ntadj(1000)\nlogical shdswp, anticl\n\n\n# If vertices k1 and k2 are not connected there is no diagonal to swap.\n# This could happen if vertices j, k1, and k2 were colinear, but shouldn't.\ncall adjchk(k1,k2,shdswp,nadj,madj,ntot,nerror)\nif(nerror > 0) {\n return\n}\nif(!shdswp) return\n\n# Get the other vertex of the quadrilateral.\ncall pred(k,k1,k2,nadj,madj,ntot,nerror) # If these aren't the same, then\nif(nerror > 0) return\ncall succ(kk,k2,k1,nadj,madj,ntot,nerror) # there is no other vertex.\nif(nerror > 0) return\nif(kk!=k) {\n# if(j==580) call intpr(\"no other vertex\",-1,1,0)\n shdswp = .false.\n return\n}\n\n# Check whether the LOP is satisified; i.e. whether\n# vertex k is outside the circumcircle of vertices j, k1, and k2\nif(k==580) {\n call intpr(\"From swap; point being added =\",-1,j,1)\n# Adj. list of k1 (\"now\").\n nk1 = nadj(k1,0)\n do jc = 1,nk1 {\n ntadj(jc) = nadj(k1,jc)\n }\n call intpr(\"now =\",-1,k1,1)\n call intpr(\"adjacency list of now:\",-1,ntadj,nk1)\n# Adj. list of k1 (\"now\").\n nk2 = nadj(k2,0)\n do jc = 1,nk2 {\n ntadj(jc) = nadj(k2,jc)\n }\n call intpr(\"nxt =\",-1,k2,1)\n call intpr(\"adjacency list of nxt:\",-1,ntadj,nk2)\n# Adj. list of j (\"point being added\").\n nj = nadj(j,0)\n do jc = 1,nj {\n ntadj(jc) = nadj(j,jc)\n }\n call intpr(\"point being added =\",-1,j,1)\n call intpr(\"adjacency list of point being added:\",-1,ntadj,nj)\n# j, now, nxt should be in anticlockwise order.\n call acchk(j,k1,k2,anticl,x,y,ntot,eps)\n if(anticl) {\n call intpr(\"anticlockwise\",-1,1,0)\n } else {\n call intpr(\"clockwise\",-1,1,0)\n }\n#\n# i = now = k1, k = nxt = k2, and j = other vertex = k:\n}\ncall qtest(j,k1,k,k2,shdswp,x,y,ntot,eps,nerror)\nif(nerror > 0) return\n\n# Do the actual swapping.\nif(shdswp) {\n call delet(k1,k2,nadj,madj,ntot,nerror)\n\tif(nerror > 0) return\n\tcall insrt(j,k,nadj,madj,x,y,ntot,nerror,eps)\n\tif(nerror > 0) return\n}\nreturn\nend\n", "meta": {"hexsha": "66489c9528f77b286abe93a169738f496e6891a0", "size": 2338, "ext": "r", "lang": "R", "max_stars_repo_path": "deldir/SavedRatfor/swap.r", "max_stars_repo_name": "solgenomics/R_libs", "max_stars_repo_head_hexsha": "a936847f6063cdf3d207e8364f05f2e13be2d878", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "deldir/SavedRatfor/swap.r", "max_issues_repo_name": "solgenomics/R_libs", "max_issues_repo_head_hexsha": "a936847f6063cdf3d207e8364f05f2e13be2d878", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-08-17T15:14:11.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-23T21:55:49.000Z", "max_forks_repo_path": "deldir/SavedRatfor/swap.r", "max_forks_repo_name": "solgenomics/R_libs", "max_forks_repo_head_hexsha": "a936847f6063cdf3d207e8364f05f2e13be2d878", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-11-04T05:34:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-04T05:34:16.000Z", "avg_line_length": 28.8641975309, "max_line_length": 75, "alphanum_fraction": 0.6360136869, "num_tokens": 849, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.689305616785446, "lm_q2_score": 0.523420348936324, "lm_q1q2_score": 0.36079658646160623}} {"text": "\\docType{data}\n\\name{paises}\n\\alias{paises}\n\\title{Datos de Gapminder}\n\\format{El cuadro de datos principal tiene 1704 filas y 6 columnas\n\\describe{\n\\item{pais}{países incluídos (factor con 142 niveles)}\n\\item{continente}{continentes (factor con 5 niveles)}\n\\item{anio}{desde 1952 a 2007, datos cada 5 años}\n\\item{esperanza_de_vida}{esperanza de vida al nacer, en años}\n\\item{poblacion}{población}\n\\item{pib_per_capita}{PIB per cápita (en dólares americanos, ajustados según inflación)}\n}}\n\\usage{paises}\n\\description{Extracto de datos de Gapminder sobre expectativa de vida, PIB per cápita y población, según país}\n\\source{http://www.gapminder.org/data/}\n\\keyword{datasets}\n", "meta": {"hexsha": "f69b237c771b9d09e6376fb42c87a3a7564d6b13", "size": 675, "ext": "rd", "lang": "R", "max_stars_repo_path": "man/paises.rd", "max_stars_repo_name": "RubenMaier/datos", "max_stars_repo_head_hexsha": "c0606f7df0701d944cf0fe762cd29e821e53e75c", "max_stars_repo_licenses": ["CC0-1.0"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-10-15T08:12:23.000Z", "max_stars_repo_stars_event_max_datetime": "2019-10-15T08:12:23.000Z", "max_issues_repo_path": "man/paises.rd", "max_issues_repo_name": "RubenMaier/datos", "max_issues_repo_head_hexsha": "c0606f7df0701d944cf0fe762cd29e821e53e75c", "max_issues_repo_licenses": ["CC0-1.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "man/paises.rd", "max_forks_repo_name": "RubenMaier/datos", "max_forks_repo_head_hexsha": "c0606f7df0701d944cf0fe762cd29e821e53e75c", "max_forks_repo_licenses": ["CC0-1.0"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 37.5, "max_line_length": 110, "alphanum_fraction": 0.7748148148, "num_tokens": 222, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6001883449573376, "lm_q2_score": 0.6001883592602049, "lm_q1q2_score": 0.3602260580070423}} {"text": "# 3. faza: Vizualizacija podatkov\n\n# Uvozimo zemljevid.\nzemljevid <- uvozi.zemljevid(\"http://baza.fmf.uni-lj.si/OB.zip\", \"OB\",\n pot.zemljevida=\"OB\", encoding=\"Windows-1250\")\nlevels(zemljevid$OB_UIME) <- levels(zemljevid$OB_UIME) %>%\n { gsub(\"Slovenskih\", \"Slov.\", .) } %>% { gsub(\"-\", \" - \", .) }\nzemljevid$OB_UIME <- factor(zemljevid$OB_UIME, levels=levels(obcine$obcina))\nzemljevid <- fortify(zemljevid)\n\n# Izračunamo povprečno velikost družine\npovprecja <- druzine %>% group_by(obcina) %>%\n summarise(povprecje=sum(velikost.druzine * stevilo.druzin) / sum(stevilo.druzin))\n\nstevilo.po.letih <- data %>% group_by(leto) %>% summarise(Stevilo=sum(stevilo, na.rm = TRUE))\n \n#Graf po stevilu priseljenih po letih \ngraf1 <- ggplot(stevilo.po.letih) + aes(x = leto, y = Stevilo) + \n geom_bar(stat = 'identity',position = 'dodge', fill = \"darkcyan\") + \n xlab(\"Leto\") + ylab(\"Število\") + ggtitle(\"Število priseljenih glede na leto\") \ngraf1\n\n#Graf po stevilu priseljenih po namenu\nstevilo.po.namenu <- data %>% group_by(namen) %>% summarise(Stevilo=sum(stevilo, na.rm = TRUE))\ngraf2 <- ggplot(stevilo.po.namenu) + aes(x = namen, y = Stevilo) + \n geom_bar(stat = 'identity',position = 'dodge', fill = \"darksalmon\") + \n xlab(\"Leto\") + ylab(\"Namen\") + ggtitle(\"Število priseljenih glede na namen\") \n#2021/22\n###################################################################################\n\n#mojzemljevid\n\n\nlibrary(tmap)\n\nzemljevid <- uvozi.zemljevid(\"http://biogeo.ucdavis.edu/data/gadm2.8/shp/SVN_adm_shp.zip\",\"SVN_adm1\", encoding = \"UTF-8\")\nzemljevid$NAME_1 <- c(\"Gorenjska\", \"Goriška\",\"Jugovzhodna Slovenija\", \"Koroška\", \"Primorsko-notranjska\", \"Obalno-kraška\", \n \"Osrednjeslovenska\", \"Podravska\", \"Pomurska\", \"Savinjska\", \"Posavska\", \"Zasavska\")\n\n\n# 1.zemljevid: priseljevanje prebivalstva po regijah\nregije_pri <- medregijske %>% group_by(regijapri) %>% summarise(skupaj = sum(stevilo, na.rm = TRUE ))\nregije_pri$regijapri = regije_pri$regijapri %>% trimws()\n\npodatki_pri = merge(zemljevid, regije_pri, by.x = \"NAME_1\", by.y = \"regijapri\" )\ntm_shape(podatki_pri) +\n tm_polygons(\"skupaj\") + \n tm_format(\"NLD\", title=\"Število prebivalstva, ki se je priselilo iz določene regije\", bg.color=\"white\")\n\n\n#2. zemljevid: izseljevanje prebivalstva po regijah\nregije_izs <- medregijske %>% group_by(regijaiz) %>% summarise(skupaj = sum(stevilo, na.rm = TRUE ))\nregije_izs$regijaiz = regije_izs$regijaiz %>% trimws()\n\npodatki_izs = merge(zemljevid, regije_izs, by.x = \"NAME_1\", by.y = \"regijaiz\" )\ntm_shape(podatki_izs) +\n tm_polygons(\"skupaj\") +\n tm_format(\"NLD\", title=\"Število prebivalstva, ki se je izselilo iz določene regije\", bg.color=\"white\")\n\n\n#ŠE LEGENDO UREDIT!\n\n#Graf 1: Povprečno število prebivalstva, ki se je selilo glede na statistične regije Slovenije\n\ngraf1 <- ggplot(data = povprecje_regije, aes(x=\" \" ,y=povprecje, fill = regijaiz)) +\n geom_bar(stat=\"identity\", position = 'dodge') +\n facet_wrap(~regijapri, ncol= 6) +\n xlab(\" \") + ylab(\"Povprečno število\") +\n ggtitle(\"Priseljevanje in odseljevanje po statističnih regijah Slovenije\") +\n theme(plot.title = element_text(family=\"Trebuchet MS\", face=\"bold\", size=20, hjust=0, color=\"black\")) +\n theme(axis.text.x = element_text(angle=90)) \n+ coord_flip() + theme_dark() +\n scale_fill_brewer(palette = \"BrBG\") \n\n\n\n#Graf 2: Število priseljenih in izseljenih ljudi glede na drzavo selitve\n \ngraf2 <- ggplot(data=povprecje2, aes(x=drzava, y=povprecje, fill=`vrsta`)) +\n geom_col(position = 'dodge') +\n coord_flip() +\n labs(x = \"Država\", y = \"Povprečno število\", title = \"Povprečno število v priseljenega ali odseljenega prebivalstva glede na države\") +\n theme_dark() +\n scale_fill_brewer(palette = \"BrBG\")\n\nodseljeni<- meddrzavne %>% filter( vrsta != \"Priseljeni iz tujine\") %>% select(- 'vrsta') %>% \n group_by (drzava, spol) %>% summarise(Stevio=sum(stevilo))\n\npriseljeni <- meddrzavne %>% filter( vrsta != \"Odseljeni iz tujino\") %>% select(- 'vrsta') %>% \n group_by (drzava, spol) %>% summarise(Stevilo=sum(stevilo)) #to bos potrebovala za pielibr\n\n\n# Graf 3: Graf, ki prikazuje število priseljenega prebivalstva glede na namen selitve in državo predhodnega bivališča.\n\ngraf3b <- ggplot(namen_priseljevanja, aes(x=leto,y=stevilo, group=1)) +\n geom_point(aes(col=drzava, size=stevilo)) +\n facet_grid(namen ~ .) + xlab(\"Leto\") + ylab(\"Število\") +\n ggtitle(\"Priseljeni prebivalci glede na namen selitve po letih\") +\n coord_flip() + theme_dark() +\n scale_fill_brewer(palette = \"BrBG\")\n\n\n#Graf 4: Graf, ki prikazuje število priseljenega prebivalstva glede na njihovo izobrazvo in državo predhodnega bivališča\n\npovprecje4 <- izobrazba_priseljeni %>% group_by(drzava, izobrazba) %>%\n summarise(povprecje=(sum(stevilo)/9))\n\ngraf4 <- ggplot(izobrazba_priseljeni, aes(x=leto,y=stevilo, group=1)) +\n geom_point(aes(col=drzava, size=stevilo)) +\n facet_grid(izobrazba ~ .) + \n labs(y=\"Število ljudi\", \n x=\"Vrsta izobrazbe\", \n title=\"Število priseljenega prebivalstva glede na stopnjo izobrazbe\") +\n theme_dark() +\n scale_fill_brewer(palette = \"BrBG\") \n\n#Graf 5: Graf, ki prikazuje število izseljenega prebivalstva glede na njihovo izobrazbo in starostno skupino\n\n#starost <- c(\"15-24\", \"25-54\", \"55-64\") zdruziii\n\npovprecje5 <- izobrazba_izseljeni %>% group_by(starost, izobrazba) %>%\n summarise(povprecje=(sum(stevilo)/9))\n\ngraf5 <- ggplot(povprecje5, aes(x=izobrazba, y=povprecje)) + \n geom_point(aes(col=starost, size=povprecje)) + \n geom_smooth(method=\"loess\", se=F) + \n labs(y=\"Število ljudi\", \n x=\"Vrsta izobrazbe\", \n title=\"Povprečno število izseljenega prebivalstva glede na starostno skupino in vrsto izobrazbe\") +\n theme_dark() +\n scale_fill_brewer(palette = \"BrBG\") \n\ngraf5a <- ggplot(data=izobrazba_izseljeni, aes(x=leto, y=stevilo, col=spol)) +\n geom_line(size=1) + facet_grid(~starost) +\n theme_bw() +\n scale_color_manual(values=c(\"darkgoldenrod3\", \"cadetblue\")) +\n xlab(\"Država\") + ylab(\"Povprečno število(/100)\") +\n ggtitle(\"Odseljeni prebivalci glede na status aktivnosti\") +\n coord_flip() +\n theme_dark() +\n scale_fill_brewer(palette = \"BrBG\") + \n scale_x_continuous(breaks=seq(2010, 2020, 4))\n \n\n\n \n\n#Graf 6: Graf, ki prikazuje število izeljenega prebivalstva glede na status aktivosti in državo pihodnjega bivališča\npovprecje6 <- izseljeni_status_akt %>% group_by(drzava, status) %>%\n summarise(povprecje=(sum(stevilo)/9)/100)\n\ngraf6 <- ggplot(data=povprecje6, aes(x = drzava, y = povprecje, fill = status)) +\n geom_bar(stat = 'identity', position = 'dodge') +\n xlab(\"Država\") + ylab(\"Povprečno število(/100)\") +\n ggtitle(\"Odseljeni prebivalci glede na status aktivnosti\") +\n coord_flip() +\n theme_dark() +\n scale_fill_brewer(palette = \"BrBG\") \n #dva grafa: celine pa evropa po drzavah\n\n#####################################################################\n\n\n\n\n", "meta": {"hexsha": "e88d7ae9facf0d017b3ad75dee4241d83af64dd0", "size": 6939, "ext": "r", "lang": "R", "max_stars_repo_path": "vizualizacija/vizualizacija.r", "max_stars_repo_name": "admira05/APPR-2019-20", "max_stars_repo_head_hexsha": "ecbcd44f0579229a5ff8906e3c8fdf44bcb8f81f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "vizualizacija/vizualizacija.r", "max_issues_repo_name": "admira05/APPR-2019-20", "max_issues_repo_head_hexsha": "ecbcd44f0579229a5ff8906e3c8fdf44bcb8f81f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2019-12-19T12:45:10.000Z", "max_issues_repo_issues_event_max_datetime": "2020-01-17T18:36:40.000Z", "max_forks_repo_path": "vizualizacija/vizualizacija.r", "max_forks_repo_name": "admira05/APPR-2019-20", "max_forks_repo_head_hexsha": "ecbcd44f0579229a5ff8906e3c8fdf44bcb8f81f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.8012048193, "max_line_length": 136, "alphanum_fraction": 0.6787721574, "num_tokens": 2608, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5621764862150634, "lm_q2_score": 0.640635868562172, "lm_q1q2_score": 0.3601504215316171}} {"text": "#!/usr/bin/env Rscript\n#\n# Randomly draw distributions of fitness effects for variants and use those\n# to simulate S&R evolution.\n#\n# Can either specify \"all\" to draw fitness effects from an exponential\n# distribution, or a number to specify the number of SNPs that will have\n# an effect (all others set to zero).\n#\n\nlibrary(boot)\nlibrary(data.table)\nlibrary(dplyr)\nlibrary(dtplyr)\n\n## Program options:\ncargs = commandArgs(trailingOnly=TRUE)\ngenotype_file = cargs[1]\nn_snps = cargs[2]\nn_generations = as.numeric(cargs[3])\nmin_maf = as.numeric(cargs[4])\nmax_miss = as.numeric(cargs[5])\noutput_prefix = cargs[6]\n\n## Probability that the reference allele is more fit than the alternate\nref_allele_more_fit = 0.8\nif(length(cargs) > 6) {\n ref_allele_more_fit = as.numeric(cargs[7])\n}\n\n\n## Read in data\ngenotypes = fread(genotype_file, header=TRUE) %>%\n select(-pos, -contig, -rs) %>%\n as.matrix()\n\ngenotype_names = fread(genotype_file, header=TRUE) %>%\n select(pos, contig, rs)\n\ninitial_allele_freqs = apply(genotypes, 1, function(x) {\n ref = sum(!(is.na(x)) & x == 1)\n alt = sum(!(is.na(x)) & x == 0)\n ref / (ref + alt)\n})\n\n\n## Filter data\nmaf = ifelse(initial_allele_freqs < 0.5, initial_allele_freqs,\n 1 - initial_allele_freqs)\nmissingness = apply(genotypes, 1, function(x) sum(is.na(x)) / length(x))\n\nkeep = maf > min_maf & missingness < max_miss\ngenotypes = genotypes[keep, ]\ngenotype_names = genotype_names[keep, ]\ninitial_allele_freqs = initial_allele_freqs[keep]\nmaf = maf[keep]\nmissingness = missingness[keep]\n\n\n## Draw fitness effects\nif(!is.na(as.numeric(n_snps))) {\n ## Set a few SNPs to fitness effect of 1, all others = 0\n ns = as.numeric(n_snps)\n x = rep(0, nrow(genotypes))\n x[sample(1:nrow(genotypes), ns, FALSE)] = sample(c(1, -1), ns, TRUE,\n prob=c(1-ref_allele_more_fit, ref_allele_more_fit))\n snp_fitness_effects = x\n} else {\n ## Draw from exponential distribution for all SNPs\n snp_fitness_effects = rexp(nrow(genotypes)) * ifelse(sample(c(TRUE, FALSE), nrow(genotypes), TRUE,\n prob=c(1-ref_allele_more_fit, ref_allele_more_fit)),\n -1, 1)\n}\n\n\n## Simulate fitness of strains and calculate allele frequency and\n## allele frequency change. Takes fitness effects as Wrightian (average\n## number of offspring).\n\n## 1) Column-by-column, multiply the fitness_effect of the alternate\n## allele by whether the alternate allele is present. Do this in\n## a way that doesn't give any negative numbers (if alternate allele\n## effect is negative, make it a positive effect of the ref. allele).\n## 2) Row-by-row, set missing genotypes to have the average effect\n## 3) Add up all the fitness effects in a strain and divide by the\n## mean across strains.\n## Note that in the genotype input file 1 = reference, 0 = alternate\nsnp_effects =\n apply(genotypes, 2, function(x) {\n snp_fitness_effects * ifelse(snp_fitness_effects < 0, -x, 1-x)\n }) %>%\n apply(., 1, function(x) {\n mw = mean(x, na.rm=TRUE)\n ifelse(is.na(x), mw, x)\n }) %>%\n t()\nfitnesses = colSums(snp_effects) / mean(colSums(snp_effects))\n\n## Calculate final strain frequencies assuming equal starting frequencies.\n## Uses Wrightian fitness (fitness = average number of offspring).\ninitial_strain_freqs = rep(1/length(fitnesses), length(fitnesses))\nn_inds = (fitnesses^n_generations)\nstrain_freqs = n_inds / sum(n_inds)\nstopifnot(all(strain_freqs >= 0))\nrelative_fitnesses = log2(strain_freqs / initial_strain_freqs)\n## If fitness = 0, need to do a rough correction:\nrelative_fitnesses[is.na(relative_fitnesses) | is.infinite(relative_fitnesses)] =\n min(relative_fitnesses[!is.na(relative_fitnesses) & !(is.infinite(relative_fitnesses))]) - 2\n\n\n## Calculate final allele frequencies\nstopifnot(all(names(strain_freqs) == colnames(genotypes)))\nallele_freqs = apply(genotypes, 1, function(x) {\n ref = sum(strain_freqs[!(is.na(x)) & x == 1])\n alt = sum(strain_freqs[!(is.na(x)) & x == 0])\n ref / (ref + alt)\n })\nstopifnot(all(allele_freqs >= 0 & allele_freqs <= 1))\n\n\n## Calculate LD groups from final strain frequencies for the top 2000\n## snps (by allele frequency change); note groups with ties may not\n## be completely included in the top 5000. Order of ties is arbitrary.\nn_ld = 5000\naf_change = abs(allele_freqs - initial_allele_freqs)\naf_order = order(order(af_change, decreasing=TRUE))\nld_groups_95 = numeric(length(af_change)) * NaN\ngrp = -1\nfor(i in 1:(n_ld-1)) {\n ii = which(af_order == i)\n if(!is.na(ld_groups_95[ii])) next\n grp = grp + 1\n ld_groups_95[ii] = grp\n for(j in (i+1):n_ld) {\n jj = which(af_order == j)\n if(!is.na(ld_groups_95[jj])) next\n g = cbind(genotypes[ii, ], genotypes[jj, ])\n r2 = (corr(g[!(is.na(g[, 1])) & !(is.na(g[, 2])), ],\n w=strain_freqs[!(is.na(g[, 1])) & !(is.na(g[, 2]))]))^2\n if(is.na(r2)) {\n warning(paste('R^2 is NA at', genotype_names[['rs']][i],\n genotype_names[['rs']][j]))\n next\n }\n if(r2 >= 0.95) {\n ld_groups_95[jj] = grp\n }\n }\n}\ni = n_ld\nii = which(af_order == i)\nif(is.na(ld_groups_95[ii])) {\n grp = grp + 1\n ld_groups_95[ii] = grp\n}\n\nld_groups_80 = numeric(length(af_change)) * NaN\ngrp = -1\nfor(i in 1:(n_ld-1)) {\n ii = which(af_order == i)\n if(!is.na(ld_groups_80[ii])) next\n grp = grp + 1\n ld_groups_80[ii] = grp\n for(j in (i+1):n_ld) {\n jj = which(af_order == j)\n if(!is.na(ld_groups_80[jj])) next\n g = cbind(genotypes[ii, ], genotypes[jj, ])\n r2 = (corr(g[!(is.na(g[, 1])) & !(is.na(g[, 2])), ],\n w=strain_freqs[!(is.na(g[, 1])) & !(is.na(g[, 2]))]))^2\n if(is.na(r2)) {\n warning(paste('R^2 is NA at', genotype_names[['rs']][i],\n genotype_names[['rs']][j]))\n next\n }\n if(r2 >= 0.80) {\n ld_groups_80[jj] = grp\n }\n }\n}\ni = n_ld\nii = which(af_order == i)\nif(is.na(ld_groups_80[ii])) {\n grp = grp + 1\n ld_groups_80[ii] = grp\n}\n\n\n## Write output:\n\n## 1. Phenotype file for Plink with fitness of strains\n## (for external association testing)\nwrite.table(cbind(names(fitnesses), names(fitnesses), fitnesses),\n file=paste0(output_prefix, '.fitness.txt'),\n sep='\\t', col.names=FALSE, row.names=FALSE, quote=FALSE)\n\n## 2. Phenotype file with relative fitness\nwrite.table(cbind(names(relative_fitnesses), names(relative_fitnesses), relative_fitnesses),\n file=paste0(output_prefix, '.relative_fitness.txt'),\n sep='\\t', col.names=FALSE, row.names=FALSE, quote=FALSE)\n\n## 3. Table of fitness effects and allele frequency start and end for\n## each SNP\nwrite.table(data.frame(genotype_names, 'effect'=snp_fitness_effects,\n 'initial'=initial_allele_freqs,\n 'final'=allele_freqs,\n 'ld_95'=ld_groups_95,\n 'ld_80'=ld_groups_80),\n file=paste0(output_prefix, '.snp_effects.txt'),\n sep='\\t', col.names=TRUE, row.names=FALSE, quote=FALSE)\n\n## 4. Table of strain frequencies and fitnesses\nwrite.table(data.frame(strain=names(fitnesses), 'fitness'=fitnesses,\n 'relative_fitness'=relative_fitnesses,\n 'initial'=initial_strain_freqs,\n 'final'=strain_freqs),\n file=paste0(output_prefix, '.strain_frequencies.txt'),\n sep='\\t', col.names=TRUE, row.names=FALSE, quote=FALSE)\n\n## 5. Phenotype file with change in strain frequency\nwrite.table(cbind(names(strain_freqs), names(strain_freqs),\n strain_freqs - initial_strain_freqs),\n file=paste0(output_prefix, '.strain_freqs.txt'),\n sep='\\t', col.names=FALSE, row.names=FALSE, quote=FALSE)\n", "meta": {"hexsha": "4667898816e9da437aa86f098a7a817b048c0608", "size": 8151, "ext": "r", "lang": "R", "max_stars_repo_path": "simulate_strain_s_and_r_fitness.r", "max_stars_repo_name": "brendane/miscellaneous_bioinfo_scripts", "max_stars_repo_head_hexsha": "91ca3282823495299e4c68aa79bdc1c0225a6d7b", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "simulate_strain_s_and_r_fitness.r", "max_issues_repo_name": "brendane/miscellaneous_bioinfo_scripts", "max_issues_repo_head_hexsha": "91ca3282823495299e4c68aa79bdc1c0225a6d7b", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-09-17T11:14:13.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-17T11:14:13.000Z", "max_forks_repo_path": "simulate_strain_s_and_r_fitness.r", "max_forks_repo_name": "brendane/miscellaneous_bioinfo_scripts", "max_forks_repo_head_hexsha": "91ca3282823495299e4c68aa79bdc1c0225a6d7b", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 36.3883928571, "max_line_length": 116, "alphanum_fraction": 0.6162434057, "num_tokens": 2248, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7490872131147276, "lm_q2_score": 0.480478678047907, "lm_q1q2_score": 0.3599204338999551}} {"text": "#' Markov Chain Monte Carlo\n#' \n#' A flexible implementation of the Metropolis-Hastings MCMC algorithm.\n#' \n#' @param fun A function. Returns the log-likelihood.\n#' @param initial Either a numeric matrix or vector, or an object of class [coda::mcmc]\n#' or [coda::mcmc.list] (see details).\n#' initial values of the parameters for each chain (See details).\n#' @param nsteps Integer scalar. Length of each chain.\n#' @param nchains Integer scalar. Number of chains to run (in parallel).\n#' @param cl A `cluster` object passed to [parallel::clusterApply].\n#' @param thin Integer scalar. Passed to [coda::mcmc].\n#' @param kernel An object of class [fmcmc_kernel].\n#' @param burnin Integer scalar. Length of burn-in. Passed to \n#' [coda::mcmc] as \\code{start}.\n#' @param multicore Logical. If `FALSE` then chains will be executed in serial.\n#' @param ... Further arguments passed to \\code{fun}.\n#' @param conv_checker A function that receives an object of class [coda::mcmc.list],\n#' and returns a logical value with `TRUE` indicating convergence.\n#' \n#' @details This function implements MCMC using the Metropolis-Hastings ratio with\n#' flexible transition kernels. Users can specify either one of the available\n#' transition kernels or define one of their own (see [kernels]). Furthermore,\n#' it allows easy parallel implementation running multiple chains in parallel. In\n#' addition, we incorporate a variety of convergence diagnostics, alternatively\n#' the user can specify their own (see [convergence-checker]).\n#' \n#' We now give details of the various options included in the function.\n#' \n#' @section Starting point:\n#' \n#' By default, if `initial` is of class `mcmc`, `MCMC` will take the last `nchains`\n#' points from the chain as starting point for the new sequence. If `initial` is\n#' of class `mcmc.list`, the number of chains in `initial` must match the `nchains`\n#' parameter. \n#' \n#' If `initial` is a vector, then it must be of length equal to the number of\n#' parameters used in the model. When using multiple chains, if `initial` is not\n#' an object of class `mcmc` or `mcmc.list`, then it must be a numeric matrix\n#' with as many rows as chains, and as many columns as parameters in the model.\n#' \n#' @section Multiple chains:\n#' \n#' When \\code{nchains > 1}, the function will run multiple chains. Furthermore,\n#' if \\code{cl} is not passed, \\code{MCMC} will create a \\code{PSOCK} cluster\n#' using [parallel::makePSOCKcluster] with\n#' [parallel::detectCores]\n#' clusters and attempt to execute using multiple cores. Internally, the function does\n#' the following:\n#' \n#' \\preformatted{\n#' # Creating the cluster\n#' ncores <- parallel::detectCores()\n#' ncores <- ifelse(nchains < ncores, nchains, ncores)\n#' cl <- parallel::makePSOCKcluster(ncores)\n#' \n#' # Loading the package and setting the seed using clusterRNGStream\n#' invisible(parallel::clusterEvalQ(cl, library(fmcmc)))\n#' parallel::clusterSetRNGStream(cl, .Random.seed)\n#' }\n#' \n#' When running in parallel, objects that are\n#' used within \\code{fun} must be passed through \\code{...}, otherwise the cluster\n#' will return with an error.\n#' \n#' The user controls the initial value of the parameters of the MCMC algorithm\n#' using the argument `initial`. When using multiple chains, i.e., `nchains > 1`,\n#' the user can specify multiple starting points, which is recommended. In such a\n#' case, each row of `initial` is use as a starting point for each of the\n#' chains. If `initial` is a vector and `nchains > 1`, the value is recycled, so\n#' all chains start from the same point (not recommended, the function throws a\n#' warning message).\n#' \n#' @section Automatic stop:\n#' \n#' By default, no automatic stop is implemented. If one of the functions in \n#' [convergence-checker] is used, then the MCMC is done by bulks as specified\n#' by the convergence checker function, and thus the algorithm will stop if,\n#' the `conv_checker` returns `TRUE`. For more information see [convergence-checker].\n#' \n#' @return An object of class [coda::mcmc] from the \\CRANpkg{coda}\n#' package. The \\code{mcmc} object is a matrix with one column per parameter,\n#' and \\code{nsteps} rows. If \\code{nchains > 1}, then it returns a [coda::mcmc.list].\n#' \n#' @export\n#' @examples \n#' # Univariate distributed data with multiple parameters ----------------------\n#' # Parameters\n#' set.seed(1231)\n#' n <- 1e3\n#' pars <- c(mean = 2.6, sd = 3)\n#' \n#' # Generating data and writing the log likelihood function\n#' D <- rnorm(n, pars[1], pars[2])\n#' fun <- function(x) {\n#' x <- log(dnorm(D, x[1], x[2]))\n#' sum(x)\n#' }\n#' \n#' # Calling MCMC, but first, loading the coda R package for\n#' # diagnostics\n#' library(coda)\n#' ans <- MCMC(\n#' fun, initial = c(mu=1, sigma=1), nsteps = 2e3,\n#' kernel = kernel_reflective(scale = .1, ub = 10, lb = 0)\n#' )\n#' \n#' # Ploting the output\n#' oldpar <- par(no.readonly = TRUE)\n#' par(mfrow = c(1,2))\n#' boxplot(as.matrix(ans), \n#' main = expression(\"Posterior distribution of\"~mu~and~sigma),\n#' names = expression(mu, sigma), horizontal = TRUE,\n#' col = blues9[c(4,9)],\n#' sub = bquote(mu == .(pars[1])~\", and\"~sigma == .(pars[2]))\n#' )\n#' abline(v = pars, col = blues9[c(4,9)], lwd = 2, lty = 2)\n#' \n#' plot(apply(as.matrix(ans), 1, fun), type = \"l\",\n#' main = \"LogLikelihood\",\n#' ylab = expression(L(\"{\"~mu,sigma~\"}\"~\"|\"~D)) \n#' )\n#' par(oldpar)\n#' \n#' \\dontrun{\n#' # In this example we estimate the parameter for a dataset with ----------------\n#' # With 5,000 draws from a MVN() with parameters M and S.\n#' \n#' # Loading the required packages\n#' library(mvtnorm)\n#' library(coda)\n#' \n#' # Parameters and data simulation\n#' S <- cbind(c(.8, .2), c(.2, 1))\n#' M <- c(0, 1)\n#' \n#' set.seed(123)\n#' D <- rmvnorm(5e3, mean = M, sigma = S)\n#' \n#' # Function to pass to MCMC\n#' fun <- function(pars) {\n#' # Putting the parameters in a sensible way\n#' m <- pars[1:2]\n#' s <- cbind( c(pars[3], pars[4]), c(pars[4], pars[5]) )\n#' \n#' # Computing the unnormalized log likelihood\n#' sum(log(dmvnorm(D, m, s)))\n#' }\n#' \n#' # Calling MCMC\n#' ans <- MCMC(\n#' initial = c(mu0=5, mu1=5, s0=5, s01=0, s2=5), \n#' fun,\n#' kernel = kernel_reflective(\n#' lb = c(-10, -10, .01, -5, .01),\n#' ub = 5\n#' scale = 0.01\n#' ),\n#' nsteps = 1e5,\n#' thin = 20,\n#' burnin = 5e3\n#' )\n#' \n#' # Checking out the outcomes\n#' plot(ans)\n#' summary(ans)\n#' \n#' # Multiple chains -----------------------------------------------------------\n#' \n#' # As we want to run -fun- in multiple cores, we have to\n#' # pass -D- explicitly (unless using Fork Clusters)\n#' # just like specifying that we are calling a function from the\n#' # -mvtnorm- package.\n#' \n#' fun <- function(pars, D) {\n#' # Putting the parameters in a sensible way\n#' m <- pars[1:2]\n#' s <- cbind( c(pars[3], pars[4]), c(pars[4], pars[5]) )\n#' \n#' # Computing the unnormalized log likelihood\n#' sum(log(mvtnorm::dmvnorm(D, m, s)))\n#' }\n#' \n#' # Two chains\n#' ans <- MCMC(\n#' initial = c(mu0=5, mu1=5, s0=5, s01=0, s2=5), \n#' fun,\n#' nchains = 2,\n#' kernel = kernel_reflective(\n#' lb = c(-10, -10, .01, -5, .01),\n#' ub = 5\n#' scale = 0.01\n#' ),\n#' nsteps = 1e5,\n#' thin = 20,\n#' burnin = 5e3,\n#' D = D\n#' )\n#' \n#' summary(ans)\n#' }\n#' \n#' @aliases Metropolis-Hastings\nMCMC <- function(\n initial,\n fun,\n nsteps,\n ...,\n nchains = 1L,\n burnin = 0L,\n thin = 1L,\n kernel = kernel_normal(),\n multicore = FALSE,\n conv_checker = NULL, \n cl = NULL\n) UseMethod(\"MCMC\")\n\n#' @export\n#' @rdname MCMC\nMCMC.mcmc <- function(\n initial,\n fun,\n nsteps,\n ...,\n nchains = 1L,\n burnin = 0L,\n thin = 1L,\n kernel = kernel_normal(),\n multicore = FALSE,\n conv_checker = NULL, \n cl = NULL\n) {\n \n MCMC.default(\n initial = utils::tail(initial, nchains - 1L),\n fun = fun,\n nsteps = nsteps,\n ..., \n nchains = nchains,\n burnin = burnin,\n thin = thin,\n kernel = kernel,\n multicore = multicore,\n conv_checker = conv_checker,\n cl = cl\n )\n \n}\n\n#' @export\n#' @rdname MCMC\nMCMC.mcmc.list <- function(\n initial,\n fun,\n nsteps,\n ...,\n nchains = 1L,\n burnin = 0L,\n thin = 1L,\n kernel = kernel_normal(),\n multicore = FALSE,\n conv_checker = NULL, \n cl = NULL\n) {\n \n if (nchains != length(initial))\n stop(\n \"The parameter `nchains` must equal the number of chains passed by \",\n \"`initial`.\", call. = FALSE\n )\n \n MCMC.default(\n initial = do.call(rbind, utils::tail(initial, 0)),\n fun = fun,\n nsteps = nsteps,\n ..., \n nchains = nchains,\n burnin = burnin,\n thin = thin,\n kernel = kernel,\n multicore = multicore,\n conv_checker = conv_checker,\n cl = cl\n )\n \n}\n\n\n\n#' @export\n#' @rdname MCMC\nMCMC.default <- function(\n initial,\n fun,\n nsteps,\n ...,\n nchains = 1L,\n burnin = 0L,\n thin = 1L,\n kernel = kernel_normal(),\n multicore = FALSE,\n conv_checker = NULL, \n cl = NULL\n ) {\n \n # # if the coda package hasn't been loaded, then return a warning\n # if (!(\"package:coda\" %in% search()))\n # warning(\"The -coda- package has not been loaded.\", call. = FALSE, )\n\n # Checking initial argument\n initial <- check_initial(initial, nchains)\n \n if (multicore && nchains == 1L) \n stop(\"When `multicore = TRUE`, `nchains` should be greater than 1.\",\n call. = FALSE)\n \n if (nchains < 1L)\n stop(\"`nchains` must be an integer greater than 1.\", call. = FALSE)\n \n # Checkihg burnins\n if (burnin >= nsteps)\n stop(\"-burnin- (\",burnin,\") cannot be >= than -nsteps- (\",nsteps,\").\", call. = FALSE)\n \n # Checking thin\n if (thin >= nsteps)\n stop(\"-thin- (\",thin,\") cannot be > than -nsteps- (\",nsteps,\").\", call. = FALSE)\n \n if (thin < 1L)\n stop(\"-thin- should be >= 1.\", call. = FALSE)\n \n # Filling the gap on parallel\n if (multicore && !length(cl)) {\n \n # Creating the cluster\n ncores <- parallel::detectCores()\n ncores <- ifelse(nchains < ncores, nchains, ncores)\n cl <- parallel::makePSOCKcluster(ncores)\n \n # Loading the package and setting the seed using clusterRNGStream\n invisible(parallel::clusterEvalQ(cl, library(fmcmc)))\n parallel::clusterSetRNGStream(cl, .Random.seed)\n \n on.exit(parallel::stopCluster(cl))\n }\n \n if (nchains > 1L) {\n \n # Preparing the call for multicore\n fmcmc_call <- as.call(\n c(\n if (multicore) \n list(quote(parallel::clusterApply), cl=quote(cl), x = quote(1L:nchains)) \n else \n list(quote(lapply), X = quote(1L:nchains)),\n list(\n FUN = quote(function(\n i, fun., initial., nsteps., thin., kernel., burnin., ...) {\n \n MCMC(\n fun = fun.,\n ...,\n initial = initial.[i, , drop = FALSE],\n nsteps = nsteps.,\n burnin = burnin.,\n thin = thin.,\n kernel = kernel.,\n nchains = 1L,\n multicore = FALSE,\n cl = NULL,\n conv_checker = NULL\n )\n \n }),\n fun. = quote(fun),\n initial. = quote(initial),\n nsteps. = quote(nsteps),\n burnin. = quote(burnin),\n thin. = quote(thin),\n kernel. = quote(kernel),\n quote(...)\n )\n )\n )\n \n # updating names\n if (multicore)\n names(fmcmc_call)[names(fmcmc_call) == \"FUN\"] <- \"fun\"\n \n fmcmc_call <- as.call(list(quote(do.call),quote(coda::mcmc.list), fmcmc_call))\n \n } else if (!is.null(conv_checker)) {\n \n # If not multicore, still we need to make sure that we are passing some\n # variables as symbols and not as constants. As in the convergence checker\n # function we modify the current environment in order to adapt the algorithm.\n fmcmc_call <- match.call()\n fmcmc_call$fun <- quote(fun)\n fmcmc_call$nsteps <- quote(nsteps)\n fmcmc_call$thin <- quote(thin)\n fmcmc_call$burnin <- quote(burnin)\n fmcmc_call$conv_checker <- enquote(NULL)\n \n }\n \n # If conv_checker, we run it with the conv checker and return. Notice that\n # we already adapted the code for the case in which we are runing multiple\n # chains\n if (!is.null(conv_checker)) {\n \n fmcmc_call <- call(\n \"with_autostop\",\n fmcmc_call,\n conv_checker = quote(conv_checker)\n )\n \n ans <- eval(fmcmc_call)\n return(ans)\n \n # If we are not using conv_checker, but still have multiple chains, then\n # we still have to run this somewhat recursively.\n } else if (nchains > 1L) {\n ans <- eval(fmcmc_call)\n return(ans)\n }\n \n # Adding names\n initial <- initial[1,,drop=TRUE]\n cnames <- names(initial)\n \n # Wrapping function. If ellipsis is there, it will wrap it\n # so that the MCMC call only uses a single argument\n passedargs <- names(list(...))\n # print(match.call())\n funargs <- methods::formalArgs(eval(fun))\n \n # Compiling\n # cfun <- compiler::cmpfun(fun)\n \n # ... has extra args\n if (length(passedargs)) {\n # ... has stuff that fun doesnt\n if (any(!(passedargs %in% funargs))) {\n \n stop(\"The following arguments passed via -...- are not present in -fun-:\\n - \",\n paste(setdiff(passedargs, funargs), collapse=\",\\n - \"),\".\\nThe function\",\n \"was expecting:\\n - \", paste0(funargs, collapse=\",\\n - \"), \".\", call. = FALSE)\n \n # fun has stuff that ... doesnt\n } else if (length(funargs) > 1 && any(!(funargs[-1] %in% passedargs))) {\n \n stop(\"-fun- requires more arguments to be passed via -...-.\", call. = FALSE)\n \n # Everything OK\n } else {\n \n f <- function(z) {\n fun(z, ...)\n }\n \n }\n # ... doesnt have extra args, but funargs does!\n } else if (length(funargs) > 1) {\n \n stop(\"-fun- has extra arguments not passed by -...-.\", call. = FALSE)\n \n # Everything OK\n } else {\n \n f <- function(z) fun(z)\n \n }\n \n # MCMC algorithm -----------------------------------------------------------\n \n theta0 <- initial\n theta1 <- theta0\n f0 <- f(theta0)\n f1 <- f(theta1)\n \n # The updates can be done jointly or sequentially\n klogratio <- kernel$logratio(environment())\n if (length(klogratio) > 1L) {\n joint_rate <- FALSE\n R <- matrix(stats::runif(nsteps * length(initial)), nrow = nsteps)\n R[] <- log(R)\n } else {\n joint_rate <- TRUE\n R <- matrix(log(stats::runif(nsteps)), nrow = nsteps)\n }\n \n ans <- matrix(ncol = length(initial), nrow = nsteps,\n dimnames = list(1:nsteps, cnames))\n \n for (i in 1L:nsteps) {\n # Step 1. Propose\n theta1[] <- kernel$proposal(environment())\n f1 <- f(theta1)\n \n # Checking f(theta1) (it must be a number, can be Inf)\n if (is.nan(f1) | is.na(f1) | is.null(f1)) \n stop(\n \"fun(par) is undefined (\", f1, \")\",\n \"Check either -fun- or the -lb- and -ub- parameters.\",\n call. = FALSE\n )\n \n # Step 2. Hastings ratio\n klogratio <- kernel$logratio(environment())\n if (joint_rate) {\n \n if (R[i] < klogratio) {\n theta0 <- theta1\n f0 <- f1\n }\n \n } else {\n \n klogratio <- (R[i, ] < klogratio)\n theta0[klogratio] <- theta1[klogratio]\n \n }\n \n \n # Step 3. Saving the state\n ans[i,] <- theta0\n \n }\n \n # Thinning the data\n if (burnin) ans <- ans[-c(1:burnin), , drop = FALSE]\n if (thin) ans <- ans[(1:nrow(ans) %% thin) == 0, , drop = FALSE]\n \n # Returning an mcmc object from the coda package\n return(\n coda::mcmc(\n ans,\n start = as.integer(rownames(ans)[1]),\n end = as.integer(rownames(ans)[nrow(ans)]),\n thin = thin\n )\n )\n \n}\n", "meta": {"hexsha": "46404063c892a1f1aa47edf1c5a528e0ad70c402", "size": 16043, "ext": "r", "lang": "R", "max_stars_repo_path": "R/mcmc.r", "max_stars_repo_name": "arokem/fmcmc", "max_stars_repo_head_hexsha": "2b897e6978d1b23107d3e88d39abb68f4ad3ab97", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2019-09-20T17:37:05.000Z", "max_stars_repo_stars_event_max_datetime": "2019-09-20T17:37:05.000Z", "max_issues_repo_path": "R/mcmc.r", "max_issues_repo_name": "arokem/fmcmc", "max_issues_repo_head_hexsha": "2b897e6978d1b23107d3e88d39abb68f4ad3ab97", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/mcmc.r", "max_forks_repo_name": "arokem/fmcmc", "max_forks_repo_head_hexsha": "2b897e6978d1b23107d3e88d39abb68f4ad3ab97", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 29.4908088235, "max_line_length": 89, "alphanum_fraction": 0.5796297451, "num_tokens": 4657, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5851011542032313, "lm_q2_score": 0.6150878555160665, "lm_q1q2_score": 0.35988861419884083}} {"text": "\n# Function to fit continous heavy tail functions\n# Mostly using poweRlaw package\n#\nfit_con_heavy_tail <- function (data_set,xmins,options.output)\n{\n\tn <- length(unique(data_set))\n\tn_models <- 4\n\tn_sets <- 1 # delete set 3\n\t# List of models\n\tmodel_list = list(list(model=vector(\"list\", length=0), \n\t\t\t\t\t\t \t\t\t\t\t\tGOF=vector(\"list\", length=0),\n\t\t\t\t\t\t\t\t\t\t\t\t xmin_estimation=vector(\"list\", length=0),\n\t\t\t\t\t\t\t\t\t\t\t\t uncert_estimation=vector(\"list\", length=0),\n\t\t\t\t\t\t\t\t\t\t\t\t k=0,\n\t\t\t\t\t\t\t\t\t\t\t\t LL=0,\n\t\t\t\t\t\t\t\t\t\t\t\t n=n,\n\t\t\t\t\t\t\t\t\t\t\t\t AICc=0,\n\t\t\t\t\t\t\t\t\t\t\t\t delta_AICc=0,\n\t\t\t\t\t\t\t\t\t\t\t\t AICc_weight=0,\n\t\t\t\t\t\t model_name=character(0),\n\t\t\t\t\t\t model_set=character(0))) \n\tfit_ht <- rep(model_list,n_models*n_sets)\n\tdim(fit_ht) <- c(n_models,n_sets)\n\t# Two sets: power law with and without cut-off\n\t# Declare models\n\tfor (i_set in 1:(n_sets)){\n\t\t# Continuous power law\n\t\tfit_ht[[1,i_set]]$model <- conpl$new(data_set)\n\t\tfit_ht[[1,i_set]]$k <- 1\n\t\t# Continuous log-normal\n\t\tfit_ht[[2,i_set]]$model <- conlnorm$new(data_set)\n\t\tfit_ht[[2,i_set]]$k <- 2\n\t\t# Continuous exponential\n\t\tfit_ht[[3,i_set]]$model <- conexp$new(data_set)\n\t\tfit_ht[[3,i_set]]$k <- 1\n\t\t# power law with exponential cutoff\n\t\tfit_ht[[4,i_set]]$model <- \"\" \n\t\tfit_ht[[4,i_set]]$k <- 2\n\t}\n\t\n\t# Set xmin for set 1\n\t#fit_ht[[1,1]]$model$xmin <- 9\n\t\n\t# Estimate Xmin with complete data_set for power law model\n\tfit_ht[[1,1]]$xmin_estimation <- estimate_xmin(fit_ht[[1,1]]$model,\n\t\txmins = xmins, \n\t\tpars = NULL, \n\t\txmax = max(data_set))\n\n\tfit_ht[[1,1]]$model$setXmin(fit_ht[[1,1]]$xmin_estimation)\n\n\n\tmodel_names <- c(\"Power\", \"LogNorm\",\"Exp\",\"PowerExp\")\n\tlabels_set <- c(\"Estimated Xmin\")\n\n\tAICc_weight <- matrix( nrow = n_models, ncol = n_sets,\n\t\t\t\t\t\t\tdimnames = list(model_names,labels_set))\n\n\tdelta_AICc <- AICc_weight\n\tGOF <- delta_AICc\n\tif(n>8) {\n\t\tfor (i_set in 1:n_sets){\n\t\taic_min=Inf\n\t\tnorm_aic_weight=0\n\t\tfor (i in 1:(n_models)){\n\t\t\t# Set cut-off (x_min)\n\t\t\tfit_ht[[i,i_set]]$model$xmin <- fit_ht[[1,i_set]]$model$xmin\n\t\t\t\n\t\t\t# Correct n with xmin\n\t\t\tfit_ht[[i,i_set]]$n <-length(data_set[data_set>=fit_ht[[1,i_set]]$model$xmin])\n\n\t\t\t# Fit models\n\t\t\t#\n\t\t\tif(i!=n_models){\n\t\t\t\tfit_ht[[i,i_set]]$model$setPars(estimate_pars(fit_ht[[i,i_set]]$model))\n\t\t\t\t# \n\t\t\t\t# Get Loglikelihood\n\t\t\t\tfit_ht[[i,i_set]]$LL <- dist_ll(fit_ht[[i,i_set]]$model)\n\t\t\t} else {\n\t\t\t\t# Fit Power Exponential (not poweRlaw package)\n\t\t\t\t#\n\t\t\t\tfit_ht[[i,i_set]]$model<- powerexp.fit(data_set,fit_ht[[1,i_set]]$model$xmin)\n\t\t\t\t# \n\t\t\t\t# Get Loglikelihood\n\t\t\t\tfit_ht[[i,i_set]]$LL <- fit_ht[[i,i_set]]$model$loglike \t\t\t\n\t\t\t}\n\t\t\tLL <- fit_ht[[i,i_set]]$LL\n\t\t\tk <- fit_ht[[i,i_set]]$k\n\t\t\t# Compute AICc\n\t\t\t#\n\t\t\tfit_ht[[i,i_set]]$AICc <- (2*k-2*LL)+2*k*(k+1)/(n-k-1)\n\t\t\taic_min <- min(aic_min,fit_ht[[i,i_set]]$AICc)\n\t\t\tif (i==1 & options.output$GOF){\n\t\t\t\t#\n\t\t\t\t# Goodness of fit via boostrap\n\t\t\t\t#\n\t\t\t\t# xmins is fixed at estimated value\n\t\t\t\tfit_ht[[i,i_set]]$GOF <- bootstrap_p(fit_ht[[i,i_set]]$model,\n\t\t\t\t\t\t\t\t\t\t\t xmins=fit_ht[[i,i_set]]$model$xmin,\n\t\t\t\t\t\t\t\t\t\t\t pars = NULL, \n\t\t\t\t\t\t\t\t\t\t\t xmax = max(data_set),\n\t\t\t\t\t\t\t\t\t\t\t no_of_sims = 1000,\n\t\t\t\t\t\t\t\t\t\t\t threads = parallel::detectCores())\n\t\t\t\t#\n\t\t\t\t# Uncertainty in parms estimation via bootstrap\n\t\t\t\t#\n\t\t\t\t# Range of xmins to make bootstrap\n\t\t\t\tl_xmin <- round(fit_ht[[i,i_set]]$model$xmin * 0.8)\n\t\t\t\tu_xmin <- round(fit_ht[[i,i_set]]$model$xmin * 1.2)\n\t\t\t\t\n\t\t\t\tfit_ht[[i,i_set]]$uncert_estimation <- bootstrap(fit_ht[[i,i_set]]$model,\n\t\t\t\t\t\t\t\t\t\t\t xmins=l_xmin:u_xmin,\n\t\t\t\t\t\t\t\t\t\t\t pars = NULL, \n\t\t\t\t\t\t\t\t\t\t\t xmax = max(data_set),\n\t\t\t\t\t\t\t\t\t\t\t no_of_sims = 1000,\n\t\t\t\t\t\t\t\t\t\t\t threads = parallel::detectCores())\n\t\t\t}\n\t\t\tfit_ht[[i,i_set]]$model_set <- labels_set[i_set]\n\t\t\tfit_ht[[i,i_set]]$model_name <- model_names[i]\n\t\t}\n\n\t\tfor (i in 1:n_models){\n\t\t\tdelta_AICc[i,i_set] <- fit_ht[[i,i_set]]$AICc - aic_min\n\t\t\tfit_ht[[i,i_set]]$delta_AICc <- delta_AICc[i,i_set]\n\t\t\tnorm_aic_weight <- norm_aic_weight + exp(-0.5*fit_ht[[i,i_set]]$delta_AICc) \n\t\t}\n\t\t# Akaike weigths\n\t\tfor (i in 1:n_models){\n\t\t\tAICc_weight[i,i_set] <- exp(-0.5*fit_ht[[i,i_set]]$delta_AICc)/norm_aic_weight \n\t\t\tfit_ht[[i,i_set]]$AICc_weight <- AICc_weight[i,i_set]\n\t\t}\n\t\t# Plots\n\t\tif (options.output$ploting){\n\t\t\t#setwd(options.output$resultsDir)\n\t\t\tfnam <-paste0(strsplit(options.output$data_set_name[i_im],\".tif\"),\"_\",labels_set[i_set], \".png\")\n\t\t\tpng(filename=fnam, res=300,units = \"mm\", height=200, width=200,bg=\"white\")\n\n\t\t\tpo <-plot(fit_ht[[1,i_set]]$model,xlab=\"Area\",ylab=\"CCDF\",main=labels_set[i_set])\n\t\t\tfor (i in 1:n_models){\n\t\t\t\tif(i!=n_models) {\n\t\t\t\t\tlines(fit_ht[[i,i_set]]$model, col=i+1)\n\t\t\t\t} else {\n\t\t\t\t\test1 <- fit_ht[[i,i_set]]$model\n\t\t\t\t\tx <- sort(unique(data_set))\n\t\t\t\t\tx <- x[x>=est1$xmin]\n\t\t\t\t\tshift <- max(po[po$x>=est1$xmin,]$y)\n\t\t\t\t\ty <- ppowerexp(x,est1$xmin,est1$exponent,est1$rate,lower.tail=F)*shift\n\t\t\t\t\tlines(x,y,col=i+1)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlegend(\"topright\",model_names,bty=\"n\",col=seq(2,5),lty=c(1,1,1,1),cex=0.5)\n\t\t\tdev.off()\n\t\t}\n\t}\n\t}\n\treturn(list(fitted_models=fit_ht,delta_AICc=delta_AICc,AICc_weight=AICc_weight)) \n}\n\n# Function to extract a data frame from output generated by fit_con_heavy_tail\n#\n#\nextract_fit_ht <-function(e)\n{\n\tee <- e$model\n\tgg <- e$GOF\n\tuu <- e$uncert_estimation\n\tbootXmin <-list(quantile(uu$bootstraps[,2],probs=c(0.025,0.25,0.5,0.75,0.975),na.rm=T))\n\tbootPar1 <-list(quantile(uu$bootstraps[,3],probs=c(0.025,0.25,0.5,0.75,0.975),na.rm=T))\n\t\n\tif(grepl(\"con\",class(ee),fixed = T))\n\t{\n# \t\tif(class(ee)==\"conlnorm\") { \n# \t\t\tpa<-ee$getPars()\n# \t\t\tif(length(pa)!=2) stop(\"conlnorm must have 2 parameters\")\n# \t\t} else {\n# \t\t\tpa<-double(2)\n# \t\t\tpa[1]<- ee$getPars()\n# \t\t\tpa[2]<- 0\n# \t\t}\n\t\tdata_frame(model_name=e$model_name,model_set=e$model_set,\n\t\t\t\t par1=ifelse(is.null(ee$pars[1]),NA,ee$pars[1]),\n\t\t\t\t par2=ifelse(is.null(ee$pars[2]),NA,ee$pars[2]),\n\t\t\t\t xmin=ee$getXmin(),n=e$n,LL=e$LL,AICc=e$AICc,delta_AICc=e$delta_AICc,\n\t\t\t\t AICc_weight=e$AICc_weight,GOFp=ifelse(is.null(gg$p),NA,gg$p),bXminQuant=bootXmin,bPar1Quant=bootPar1)\n\t\t\n\t} else {\n\t\tdata_frame(model_name=e$model_name,model_set=e$model_set,par1=ee$exponent,par2=ee$rate,\n\t\t\t\t xmin=ee$xmin,n=e$n,LL=e$LL,AICc=e$AICc,delta_AICc=e$delta_AICc,\n\t\t\t\t AICc_weight=e$AICc_weight,GOFp=ifelse(is.null(gg$p),NA,gg$p),bXminQuant=bootXmin,bPar1Quant=bootPar1)\n\t}\n\t\n}\n\n# Read data to call fit_con_heavy_tail and format output in a data.frame\n#\n#\ncall_fit_con_heavy_tail <-function(options,i){\n\t\n\t# Read binary data\n\tconnection_file <- file(options$original_bin_files[i], \"rb\")\n\tdata_set <- readBin(connection_file, \"double\", n = 10^6)\n\t\n\tta<-sum(data_set)*233*233/1000000\n\t\n\tcat(options$original_bin_files[i],ta,\"\\n\")\n\t\n\tfit_ht_df<-data_frame()\n\t\n\tif(ta>100000){# Set folder with results for the region \n\n\t\t#\n\t\t# Sample data for testing\n\t\tif(options$sample_data>0) data_set<- sample(data_set,options$sample_data) ### TESTING\n\t\t\n\t\t# Fit distribution models\n\t\tfit_ht <- fit_con_heavy_tail(data_set,options$xmins,options)\n\t\t\n\t\t# List to data.frame\n\t\tfit_ht_df <- ldply(fit_ht$fitted_models,extract_fit_ht)\n\t\tfit_ht_df$data_set_name <- strsplit(options$data_set_name[i],\".tif\")[[1]][1]\n\t\tss <- strsplit(options$data_set_name[i],\"_\")\n\t\tfit_ht_df$region <- ss[[1]][2]\n\t\tfit_ht_df$subregion <- ss[[1]][3]\n\t\tfit_ht_df$threshold <- ss[[1]][4]\n\t\tfit_ht_df$year <- gsub(\".*\\\\.A([0-9]{4}).*\",\"\\\\1\",options$data_set_name[i])\n\t}\n\t\n\tclose(connection_file)\n\t\n\treturn(fit_ht_df)\n\t\n}\n\n# Returns a data.frame with: number of patches, max patch, and total patch area\n#\ndata_con_heavy_tail <-function(options,i){\n\t\n\t# Read binary data\n\tconnection_file <- file(options$original_bin_files[i], \"rb\")\n\tdata_set <- readBin(connection_file, \"double\",n = 10^7)\n\tif(length(data_set)==10^7)\n\t\t\twarning(\"Data set\",options$original_bin_files[i], \" may be bigger than 10^7\")\n\tnl<-length(data_set)\n\tmx<-max(data_set)*233*233/1000000 # Convert to km2\n\tta<-sum(data_set)*233*233/1000000\n\tmx2 <- (sort(data_set,partial=nl-1)[nl-1])*233*233/1000000\n\tcat(options$original_bin_files[i],\"\\tNo.patches\",nl,\"\\tMax.PatchKm2\",mx,\"\\t2nd.Max.PatchKm2\",mx2,\"\\tTotalKm2\",ta,\"\\n\")\n\t\n\tfit_ht_df <- data_frame(number_of_patches=nl,max_patch=mx,second_max=mx2,total_patch_area=ta)\n\tfit_ht_df$data_set_name <- strsplit(options$data_set_name[i],\".tif\")[[1]][1]\n\tss <- strsplit(options$data_set_name[i],\"_\")\n\tfit_ht_df$region <- ss[[1]][2]\n\tfit_ht_df$subregion <- ss[[1]][3]\n\tfit_ht_df$threshold <- ss[[1]][4]\n\tfit_ht_df$year <- gsub(\".*\\\\.A([0-9]{4}).*\",\"\\\\1\",options$data_set_name[i])\n\n\tclose(connection_file)\n\t\n\treturn(fit_ht_df)\n\t\n}\n\n\n\n# Fit all the images patch sizes for a region with maybe different areas \n#\n#\nregion_fit_con_heavy_tail <-function(options,region,year=0){\n\n\t# Change to results folder \n\t#\n\tsetwd(options$resultsDir)\n\t\n\t# Get files with patch sizes (*.bin) and image file names *.tif (data_set_name)\n\t#\n\toptions$original_bin_files <- list.files(pattern=paste0(\"^.*\",region,\".*\\\\.bin$\")) # list.files(pattern=\"*.\\\\.bin\")\n\toptions$data_set_name <- unlist(strsplit(options$original_bin_files,\".bin\")) \n\t\n\tif( year > 0)\n\t\toptions$data_set_name <- options$data_set_name[gsub(\".*\\\\.A([0-9]{4}).*\",\"\\\\1\",options$data_set_name)==year]\n\t\n\t\n\tfit <- data_frame()\n\n\n\tfor(i in 1:length(options$data_set_name))\n\t{ \n\t\tif(options$fit)\n\t\t{\n\t\t \tfit <- rbind(fit,call_fit_con_heavy_tail(options,i))\t# Fit models\n\t\t} else {\n\t\t \tfit <- rbind(fit,data_con_heavy_tail(options,i)) \t\t# calculate patch stats\n\t\t}\n\t}\n\tif(region!=fit$region[1]) warning(\"Regions don't match \",region, fit$region)\n\t\n\t# Change to base folder \n\t#\n\tsetwd(oldcd)\n\t\n\treturn(fit)\n}\n\n\n# Plot of frequencies of patch sizes with fitted continuous heavy tail functions\n# x: data\n# fit_ht_df : dataframe with fitted parameters\n#\nfreq_plot_con_ht <- function(x,fit_ht,tit=\"\") # PLOT ALL FROM X=1 ?????????????????\n{\n\trequire(dplyr)\n\trequire(ggplot2)\n\txx <-as.data.frame(table(x))\n\txx$x <- as.numeric(as.character(xx$x))\n\tff <- filter(fit_ht,model_name==\"PowerExp\")\n\txmin <- ff$xmin\n\txx$pexp <-dpowerexp(xx$x,1,ff$par1,ff$par2)\n\t\n\tff <- filter(fit_ht,model_name==\"Power\")\n\txx$pow <-dpareto(xx$x,xmin,ff$par1)\n\n\tff <- filter(fit_ht,model_name==\"Exp\")\n\txx$exp <-dexp(xx$x,ff$par1)\t\n\n\txx <-mutate(xx,pexp=ifelse(x= min(tP$Rank))\n\t#tP1 <-filter(tP1, powl>= min(tP$Rank))\n\t\n\t#mc <- c(\"#E69F00\", \"#56B4E9\", \"#009E73\",\"#F0E442\", \"#0072B2\",\"#D55E00\", \"#CC79A7\")\n\t# Brewer\n\t#mc <- c(\"#d7191c\",\"#fdae61\",\"#abd9e9\",\"#2c7bb6\")\n\t\n\tg <- ggplot(tP, aes(x=x,y=y)) + theme_bw() + geom_point(alpha=0.3) + \n\t\tcoord_cartesian(ylim=c(1,min(tP$y)))+\n\t\tscale_y_log10() +scale_x_log10() + ylab(\"log[P(X > x)]\") + xlab(\"Patch size\") #+ggtitle(tit)\n\tif(xmax>0) {\n\t\tg<-g + xlim(0,xmax+1) + scale_x_log10()\n\t}\n\tbrk<-unique(tP1$model)\n\tg <- g + geom_line(data=tP1,aes(y=powl,x=psize,colour=model)) + \n\t\t#scale_colour_discrete(name=\"\",breaks=brk)\n\t\t#scale_colour_manual(values=mc,name=\"\",breaks=brk) \n\t\tscale_colour_brewer(type=\"div\",palette=7,name=\"\",breaks=brk)\n\n\t\n\t\n# \tif(!is.null(fit_ht1))\n# \t{\t\n# \t\t#tP <-filter(tP,x x)]\") + xlab(\"Patch size\") #+ggtitle(tit)\n# \t\t\n# \n# \t\t#xmin <- fit_ht1$xmin \n# \t\ttP2 <- cdfplot_conpl_exp_helper(x,tP,fit_ht1,xmin,\"lt\")\n# \t\tbrk<-unique(tP2$model)\n# \t\t\n# \t\tg <- g + geom_line(data=tP2,aes(y=powl,x=psize,colour=model)) + \n# \t\t\t#scale_colour_discrete(name=\"\",breaks=brk)\n# \t\t\t#scale_colour_manual(values=mc,name=\"\",breaks=brk) \n# \t\t\tscale_colour_brewer(type=\"div\",palette=7,name=\"\",breaks=brk)\n# \t\t\n# \t\tfil <- gsub(\" \", \"\", tit, fixed = TRUE)\n# \t\tfil <- paste0(fil,\"_1.png\")\n# \t\tif(tit==\"\")\n# \t\t\tprint(g)\n# \t\telse\n# \t\t\tggsave(fil,plot=g,width=6,height=4,units=\"in\",dpi=600)\n# \t\t\n# \n# \t}\n\tfil <- gsub(\" \", \"\", tit, fixed = TRUE)\n\tfil <- paste0(fil,\".png\")\n\tif(tit==\"\")\n\t\tprint(g)\n\telse\n\t\tggsave(fil,plot=g,width=6,height=4,units=\"in\",dpi=600)\n\t\n}\n\ncdfplot_conpl_exp_helper <- function(x,tP,fit_ht,xmin,mode=\"gt\")\n{\n\tx1 <- unique(x)\n\n\t# Select model and generate a data frame \n\t#\n\tff <- filter(fit_ht,model_name==\"PowerExp\")\n\n\tif(mode==\"gt\") {\n\t\tx1 <- x1[x1>=xmin]\n\t\tshift <- max(filter(tP,x>=xmin)$y)\n\t} else {\n\t\tx1 <- x1[x1=xmin)$y)\n\t}\n\n\ttP2 <- data.frame(psize=x1, powl=ppowerexp(x1,xmin,ff$par1,ff$par2,lower.tail=F)*shift,model=\"PowerExp\")\n\n\tff <- filter(fit_ht,model_name==\"Power\")\n\n\ttP1 <-data.frame(psize=x1, powl=ppareto(x1,xmin,ff$par1,lower.tail=F)*shift,model=\"Power\")\n\n\tff <- filter(fit_ht,model_name==\"Exp\")\n\tm <- conexp$new(x)\n\tm$setPars(ff$par1)\n\tm$setXmin(xmin)\n\ttP3 <- data.frame(psize=x1,powl=dist_cdf(m,x1,lower_tail=F)*shift,model=\"Exp\")\n\t\n\tff <- filter(fit_ht,model_name==\"LogNorm\")\n\tm <- conlnorm$new(x)\n\tm$setPars(c(ff$par1,ff$par2))\n\tm$setXmin(xmin)\n\ttP4 <- data.frame(psize=x1,powl=dist_cdf(m,x1,lower_tail=F)*shift,model=\"LogNorm\")\n\ttP1 <- bind_rows(tP1,tP2,tP3,tP4)\n}\n\n\n# Function to plot CCDF of heavy tailed distributions using base graphics\n# x: data set\n# fit_ht: a data frame with the fitted parameters\n#\ncdfplot_con_ht <- function(x,fit_ht,fnam=\"\")\n{\n\trequire(dplyr)\n\tif(fnam!=\"\"){\n\t\t\tfnam <-paste0(fnam,\".png\")\n\t\t\tpng(filename=fnam, res=300,units = \"mm\", height=200, width=200,bg=\"white\")\n\t}\n\n\t#fil <- gsub(\" \", \"\", tit, fixed = TRUE)\n\t#fil <- paste0(fil,\".png\")\n\n\tmc <- c(\"#E69F00\", \"#56B4E9\", \"#009E73\", \"#F0E442\", \"#0072B2\", \"#D55E00\", \"#CC79A7\")\n\n\trequire(poweRlaw)\n\tm <- conpl$new(x)\n\tpo <- plot(m,xlab=\"Area\",ylab=\"CCDF\")\n\t#x <- x[x>=xmin]\n\n\t\t\n\t#x <- unique(x)\n\t# Plot with base plot and poweRlaw package\n\t#\n\tff <- filter(fit_ht,model_name==\"Power\")\n\txmin <- ff$xmin\n\tm$setPars(ff$par1)\n\tm$setXmin(xmin)\n\tlines(m, col=mc[1])\n\n\tshift <- max(filter(po,x>=xmin)$y)\n\tff <- filter(fit_ht,model_name==\"PowerExp\")\n\tx1 <- sort(unique(x))\n\t#x1 <- sort(x)\n\tx1 <- x1[x1>=xmin]\n\ty1 <- ppowerexp(x1,xmin,ff$par1,ff$par2,lower.tail=F)*shift\n\tlines(x1,y1,col=mc[2])\n\n\t\n\tff <- filter(fit_ht,model_name==\"Exp\")\n\tm <- conexp$new(x)\n\tm$setPars(ff$par1)\n\tm$setXmin(xmin)\n\tlines(m, col=mc[3])\n\n\tff <- filter(fit_ht,model_name==\"LogNorm\")\n\tm <- conlnorm$new(x)\n\tm$setPars(c(ff$par1,ff$par2))\n\tm$setXmin(xmin)\n\tlines(m, col=mc[4])\n\t\n\tmodel_names <- c(\"Power\",\"PowerExp\",\"Exp\",\"LogNorm\")\n\tlegend(\"topright\",model_names,bty=\"n\",col=mc[1:4],lty=c(1,1,1,1),cex=0.5)\n\n\tif(fnam!=\"\")\n\t\tdev.off()\n\n}\n\n# Function to plot distributions fits from the complete dataset Xmin=9\n# and the dataset from the estimated Xmin \n# calls the function cdfplot_con_ht and use global variables\n#\n# reg: geographic region {SA,CA,NA,EU, etc}\n#\nccdfPlots_one_region <- function(options,region)\n{\n\tfor( i_im in 1:length(options$data_set_name)) \n\t{\n\t\tconnection_file <- file(options$original_bin_files[i_im], \"rb\")\n\t\tdata_set <- readBin(connection_file, \"double\", n = 10^6)\n\t\tif(options$sample_data>0) data_set<- sample(data_set,options$sample_data) \n\t\tta<-sum(data_set)*233*233/1000000\n\t\tif(ta>100000){\n\t\t\tss <- strsplit(options$data_set_name[i_im],\"_\")[[1]][2]\n\t\t\tif( region != ss) warning(\"Region extracted from file names: \",ss, \" Different from parameter: \",region)\n\t\t\t\n\t\n\t\t\tnn <- strsplit(options$original_bin_files[i_im],\".tif\")[[1]][1]\n\t\t\t\n\t\t\t# Complete data set (Xmin=1)\n\t\t\t#\n\t\t\tff <- filter(all_fit,grepl(nn,data_set_name,ignore.case = T),model_set==\"Xmin=9\",region==region)\n\t\t\tna<-paste0(ff$region[1],\"_\", ff$subregion[1],\"_\",ff$year[1],\"_\",ff$model_set[1])\n\t\t\tcdfplot_conpl_exp(data_set,ff,na)\n\t\t\t\n\t\t\t# data set< Estimated Xmin (=hmin & h<=hmax) \n\t} else {\n\t dn1 <- dn\n\t}\n\tstr_sub(dn1$V1,28,40) <- \"*\"\n\t\n\twrite.table(str_c(dn1$V1,\"*\"),file=\"MOD44BFiles\",row.names = F,col.names = F,quote = F)\n\t\n\tsystem(\"modis_download_from_list.py -U lsaravia -P Octa2004 -p MOD44B.051 -f MOD44BFiles hdf \")\n\t\n\tsetwd(oldcd)\n\t\n\treturn(dn1)\n\t}\n\n\n# Make mosaic of hdf files downloaded with down_modis\n# in a folder \"hdf\" with base dataDir, it uses a file called\n# \"Download.txt\" to read the files to compose and the Python PyModis package\n#\n# dataDir: base folder to output mosaic geotif files\n# \n#\nmosaic_modis <- function(dataDir,hmin,hmax) {\n\t\n\tsetwd(dataDir)\n\tdn <- read.table(\"Download.txt\",stringsAsFactors = F)\n\trequire(stringr)\n\tdn$h=as.numeric(str_sub(dn[,1],18,19))\n\tdn$v=as.numeric(str_sub(dn[,1],21,22))\n\tdn$year=str_sub(dn[,1],9,12)\n\n\trequire(dplyr)\n\tdn1 <- filter(dn,h>=hmin & h<=hmax) \n\tsetwd(\"hdf\")\n\tgroup_by(dn1,year) %>% do( s=mosaic_by_year(.))\n\n\tsetwd(oldcd)\n}\n\n# helper function for mosaic_modis\n#\nmosaic_by_year <-function(x) {\n \n # write list of file names to use in the mosaic\n #\n\twrite.table(x$fname,file=\"listfileMOD44B.051.txt\",quote=F,col.names = F,row.names = F)\n \n # Output file name \n #\n gname <- paste0('MOD44B.MRTWEB.A',x$year[1],'065.051.Percent_Tree_Cover.tif')\n \n\ts <- paste0('modis_mosaic.py -s \"1 0 0 0 0 0 0\" listfileMOD44B.051.txt -o ', gname)\n\tsystem(s)\n\t\n\treturn(gname)\n}\n\n# Read the h and v limits for modis hdf files to make composite images by continent \n#\n#\nget_modis_limits <-function(region,hmin,hmax){\n \n setwd(\"MODIS_tools\")\n fn <- paste0(\"Download_\",region,\".txt\")\n dn <- read.table(fn,stringsAsFactors = F)\n setwd(oldcd)\n \n require(stringr)\n \n # regexpr(\"h[0-9]\",dn[1,1])\n \n dn$h=as.numeric(str_sub(dn[,1],18,19))\n dn$v=as.numeric(str_sub(dn[,1],21,22))\n dn$year=str_sub(dn[,1],9,12)\n \n # Generate a DF with only the h v needed for a region\n #\n require(dplyr)\n dn <- filter(dn,h>=hmin & h<=hmax) \n m <- matrix(0,nrow=max(dn$v),ncol=max(dn$h))\n m[dn$v,dn$h]<-1\n print(m) \n mod_limits <- dn %>% filter(year==2000) %>% arrange(v,h) %>% select(h,v) %>% mutate( Region=region) \n \n}\n\n\n#' Make geotiff mosaic of hdf files for a region defined as h & v modis granules\n#' in a folder \"hdf\" within base dataDir\n#'\n#' @param dataDir Folder where the geotiff file will be generated and where there is \n#' a subfolder hdf with granules \n#' \n#' @param destDir Destination folder for the generated geotiff files\n#' \n#' @param granules Data frame with h & v columns identifying granules to be mosaicked, with\n#' fields h,v,region \n#' @param region region defined in the data frame to generate the geotiff\n#' \n#' @param year year of the modis granules to generate the geotiff \n#'\n#' @return\n#' @export\n#'\n#' @examples\n#' \nmosaic_modis_region <- function(dataDir,destDir,granules,region,year) {\n oldcd <-getwd() \n setwd(dataDir)\n \n # read the files in dir 'hdf'\n #\n dn <- list.files(\"hdf\",pattern = \"^.*\\\\.hdf$\")\n if(length(dn)==0) stop(\"The folder hdf is empty\")\n require(dplyr)\n dn <- tibble(dn)\n names(dn) <- \"fname\"\n \n require(stringr)\n dn$h <- as.numeric(str_match(dn$fname, \"h(\\\\d{2})\")[,2])\n dn$v <- as.numeric(str_match(dn$fname, \"v(\\\\d{2})\")[,2])\n dn$year <- str_match(dn$fname, \"A(\\\\d{4})\")[,2]\n \n\n dn1 <- granules %>% filter(Region==region) %>% inner_join(dn) \n setwd(\"hdf\")\n \n dn2 <- group_by(dn1,year) %>% do( gname=mosaic_by_year(.))\n dn2$gname <-unlist(dn2$gname)\n \n dn2$toname <- paste0(destDir,\"/\",dn2$gname)\n \n # dn2 <- data.frame(gname=\"MOD44B.MRTWEB.A2015065.051.Percent_Tree_Cover.tif\",stringsAsFactors = F)\n file.rename(dn2$gname,dn2$toname)\n \n setwd(oldcd)\n}\n\n\n\n# Read data to call fit_con_heavy_tail and format output in a data.frame\n#\n#\nmax_patch_size <-function(im_names,opts.out){\n\t\n\tmax_s_df <- data_frame()\n\t\n\tfor(i in 1:length(im_names))\n\t{ \n\t\t# Read binary data\n\t\tconnection_file <- file(original_bin_files[i], \"rb\")\n\t\tdata_set <- readBin(connection_file, \"double\", n = 10^6)\n\t\tif(options.output$sample_data>0) data_set<- sample(data_set,options.output$sample_data) ### TESTING\n\t\tmax_s_df <- rbind(max_s_df,data_frame( maxS=max(data_set), data_set_name=strsplit(options.output$data_set_name[i],\".tif\")[[1]][1],\n\t\t\t\t\t\t\t\tyear=substr(data_set_name,16,19),region=opts.out$region))\n\t\t\n\t}\n\n\treturn(max_s_df)\n}\n\n\nread_random_percolation <-function(region) {\n\t\n\tpercolation_R_files <- list.files(pattern=\"^.*_randomized_p_sweep\\\\.R$\")\n\tdf <- data.frame()\n\t\n\tfor(i in 1:length(percolation_R_files)){\n\t\tss <- strsplit(percolation_R_files[i],\"_\")\n\t\t#df$region <- ss[[1]][2]\n\t\t#df$subregion <- ss[[1]][3]\n\t\tif(ss[[1]][2]!=region) warning(\"Regions don't match \",region, ss[[1]][2])\n\n\t\tsource(percolation_R_files[i])\n\t\tll <- length(p_set)\n\t\tdf1 <- data.frame(region=rep(ss[[1]][2],ll),subregion=rep(ss[[1]][3],ll),correlation_length_km=t(correlation_length_km_set),p_set=t(p_set))\n\t\tdf1$equivalent_diameter_km <- equivalent_diameter_km\n\t\tdf1$maximum_length_km <- maximum_length_km\n\t\tdf1$total_area_km2 <- total_area_km2\n\t\tdf <- rbind(df,df1)\n\t\t\n\t}\n\treturn(df)\n}\n\n\nread_region_correlation<-function(region) {\n\n\tr_files <- list.files(pattern=\"^.*_Tree_Cover.tif_Correlation_analisys\\\\.R$\")\n\tdf <- data.frame()\n\t\n\tfor(i in 1:length(r_files)){\n\n\t\tss <- strsplit(r_files[i],\"_\")\n\t\t#df$region <- ss[[1]][2]\n\t\t#df$subregion <- ss[[1]][3]\n\t\tif(ss[[1]][2]!=region) warning(\"Regions don't match \",region, ss[[1]][2])\n\n\t\tsource(r_files[i])\n\t\tdf1 <- data.frame(region=ss[[1]][2],subregion=ss[[1]][3],year=gsub(\".*\\\\.A([0-9]{4}).*\",\"\\\\1\",r_files[i]),\n\t\t\tcorrelation_length_km,maximum_length_km,total_area_km2,equivalent_diameter_km)\n\n\t\tdf <- rbind(df,df1)\n\t}\n\treturn(df)\n}\n\n# Estimation of the correlation exponent epsilon ~ (p-pc)^-nu\n# based in the potential relationship near the critical point\n#\n# range: range of p to estimate exponent\n# cp: critical point\n# df: data frame with data\n#\nest_correlation_exponent <- function(range,cp,df)\n{\n\trequire(ggplot2)\n\t\n\tf_df <- df %>% group_by(region,subregion) %>% filter(p_set>=range[1] & p_set<=range[2]) %>% mutate(p_dif=abs(p_set-cp))\n\t\n\tg <- ggplot(f_df,aes(p_dif,correlation_length_km,colour=subregion))+theme_bw() + geom_point() + scale_y_log10() +scale_x_log10() \n\tprint(g + geom_smooth(method=lm, se=FALSE)) # Don't add shaded confidence region\n\t\n\tmods <- do(f_df,mod=lm(log(correlation_length_km) ~ log(p_dif),data=.),max_corr_length=max(.$correlation_length_km),min_corr_length=min(.$correlation_length_km))\n\tslop <- mods %>% mutate(log_inter=coef(summary(mod))[1],correl_exp=coef(summary(mod))[2],\n\t\t\t\t\t\tR2 = summary(mod)$r.squared,pvalue_exp=coef(summary(mod))[2,4], #full_coef=coef(summary(.$mod)),\n\t\t\t\t\t\tmax_corr_length=max_corr_length,min_corr_length=min_corr_length) %>% select(-mod)\n\t\n\t#slop <- mods %>% do(data.frame(region=.$region, subregion=.$subregion, var = names(coef(.$mod)), coef(summary(.$mod)))) %>% filter(var==\"log(p_dif)\")\n\t#R2s <- mods %>% summarise(region=region, subregion=subregion,R2 = summary(mod)$r.squared)\n\t#slop$R2 <- R2s$R2\n\t\n\treturn(slop) # %>% select(-var,-t.value) %>% rename(correl_exp=Estimate,SE=Std..Error,pvalue=Pr...t..))\n}\n\n# Calculates critical probability from correlation length based on the estimated exponents using \n# function est_correlation_exponent\n#\n# range: range of p to estimate exponent (not used)\n# cp: critical point\n# corexp: data frame ouput of the function est_correlation_exponent\n# regcor: data frame with data \n#\ncalc_critical_probability <- function(range,cp,corexp,regcor)\n{\n\tallcor <- regcor %>% inner_join(corexp) %>% mutate(p=cp-(correlation_length_km/exp(log_inter))^(1/correl_exp),\n\t\t\t\t\t\t\t\t\t\t\t\t\t p=ifelse(p<0,0,ifelse(p>1,1,p)))\n#\tincor <- allcor %>% filter(correlation_length_km>=min_corr_length,correlation_length_km<=max_corr_length) %>%\n#\t\tmutate(pdist=exp((log_inter-log(correlation_length_km))/correl_exp))\n#\t\tmutate(p=cp-(correlation_length_km/exp(log_inter))^(1/correl_exp))\n#\tltcor <- allcor %>% filter(correlation_length_km% mutate(p=0.1)\n#\tgtcor <- allcor %>% filter(correlation_length_km>max_corr_length) %>% mutate(p=0.9)\n\t\n\treturn(select(allcor, -(max_corr_length:pvalue_exp)))\n}\n\n# Estimation of the critical point using logistic regression \n#\n#\nest_critical_point <- function(rndper)\n{\n # Estimate the probability of percolation as correlation_length/equivalent_diameter\n #\n\trp <-rndper %>% group_by(region,subregion) \t%>% mutate(p_correlation_length=correlation_length_km/equivalent_diameter_km) %>% mutate(p_correlation_length=ifelse(p_correlation_length>1,1,p_correlation_length))\n\t\n # Fit a binomial model to estimate the critical point\n\t#\n\trfit <- rp %>% do(lfit= glm(.$p_correlation_length ~ .$p_set, family=binomial(logit), data = .))\n\t# slop <- rfit %>% mutate(beta0 = coef(lfit)[1],\n\t# \t\t\t\t\t\tbeta1 = coef(lfit)[2],\n\t# \t\t\t\t\t\tpcrit = - beta0 / beta1) \n\t\n\t# Estimate the critical point using a regression of the values around the probability of percolation =0.50\n\t# p_correlation_length = 0.5\n\t#\n\tslop <- rp %>% do(pcrit = est_critical_point_helper(.)) %>% mutate(pcrit=unlist(pcrit))\n\n\t# Calculate the predicted values of the binomial regression to plot\n\t#\n\trfit <-rfit %>% inner_join(rp %>% slice(1) %>% transmute(max_cl=equivalent_diameter_km))\n\trp1 <-rfit %>% do(data.frame(fit = .$lfit$fitted*.$max_cl))\n\trp <- bind_cols(rp, rp1)\n\t\n\tgt <- slop %>% mutate(label = sprintf(\"p == %.3f\", pcrit),x=0.9,y=0.1)\n\tg <-ggplot(rp,aes(p_set,correlation_length_km))+theme_bw() + geom_point(shape=21) + \t\t\n\t\tgeom_line(aes(x = p_set, y = fit), linetype = 2) +\n\t\tgeom_vline(aes(xintercept = pcrit),data = slop, color = \"blue\") +\n\t\tgeom_text(aes(x,y,label = label) ,data=gt,parse = TRUE ) +\n\t\tfacet_wrap(region ~ subregion,scales=\"free_y\") \n\tprint(g)\n\n\treturn(slop)\n}\n\nest_critical_point_helper<- function(x)\n{\n # lf <-glm(p_correlation_length ~ p_set, family=binomial(logit), data = x)\n # pcrit=- (lf$coefficients[1] / lf$coefficients[2])\n # x$p <-predict(lf,x,type=\"resp\")\n x1 <- x %>% filter(p_correlation_length>0.50) %>% arrange(p_correlation_length) %>% slice(1:10) \n x1 <- bind_rows(x1, x %>% filter(p_correlation_length<=0.50) %>% arrange(desc(p_correlation_length)) %>% slice(1:10))\n pcrit <- approx(x1$p_correlation_length,x1$p_set,xout=0.5)[[\"y\"]]\n \n}\n\n\n\n#' Plot estimated correlations lenght with ramdomized correlation lengths \n#'\n#' @param cpoint Data frame with critical points\n#' @param rndcor Data frame with randomized correlation lengths\n#' @param corlen Data frame with correlation lengths\n#'\nplot_corr_length <- function(cpoint,rndcor,corlen)\n{\n gt <- cpoint %>% mutate(label = sprintf(\"p == %.3f\", pcrit),x=0.9,y=0.1)\n g <-ggplot(rndcor,aes(p_set,correlation_length_km))+theme_bw() + geom_point(shape=21) + \t\t\n geom_vline(aes(xintercept = pcrit),data = cpoint, color = \"blue\") +\n geom_text(aes(x,y,label = label) ,data=gt,parse = TRUE ) +\n geom_point(aes(),data=corlen)\n facet_wrap(region ~ subregion,scales=\"free_y\") \n print(g)\n} \n\n# Calculates the percolation probability using logistic equation parms from est_critical_point\n#\n# cripoi: critical point and logistic parameters \n# regcor: data frame with data \n#\ncalc_critical_probability_logis <- function(cripoi,regcor)\n{\n\tallcor <- regcor %>% inner_join(cripoi) %>% mutate( pl = (-log((max_cl-correlation_length_km)/correlation_length_km) -beta0) / beta1)\n\t\t\t\t\t\t\t\t\t\t\t\t\t \n\treturn(select(allcor,-(lfit:max_cl)))\t\n\t\n}\n\n\n# Plot inverse cumulative size distributions fits by region\n#\n# region\n# odir: folder with the size distribution files\n#\nplot_size_dist_by_region <-function(region,odir,Thres=0,Year=0)\n{\n\trequire(ggplot2)\n\n\toptions.glo$resultsDir <- odir\n\toptions.glo$sample_data <- 0 # Set >0 For testing\n\t\n\tsetwd(options.glo$resultsDir)\n\toptions.glo$original_bin_files <- list.files(pattern=paste0(\"^.*\",region,\".*\\\\.bin$\")) # list.files(pattern=\"*.\\\\.bin\")\n\t\n\toptions.glo$data_set_name <- unlist(strsplit(options.glo$original_bin_files,\".bin\")) \n\tyear <- gsub(\".*\\\\.A([0-9]{4}).*\",\"\\\\1\",options.glo$data_set_name)\n\tthreshold <- sub(\"^(?:[^_]*_){3}([^_]+).*\",\"\\\\1\",options.glo$data_set_name)\n\n\tif(Thres>0)\n\t\toptions.glo$data_set_name <- options.glo$data_set_name[threshold==thres] \n\n\tif(Year>0)\n\t\toptions.glo$data_set_name <- options.glo$data_set_name[year==Year] \n\t\n\t# Read binary data\n\tset.seed(seed=0)\n\t\n\tccdfPlots_one_region(options.glo,region)\n\t\n\tsetwd(oldcd)\n}\n\n\n# Fit continuos heavy tail models (used for small data sets not patch size distributions)\n# \n#\nfit_cont_heavy_tail_mdls <- function (data_set,xmins,ploting=TRUE,gof=FALSE)\n{\n\tn <- length(unique(data_set))\n\tn_models <- 3\n\t# List of models\n\tmodel_list = list(list(model=vector(\"list\", length=0), \n\t\t\t\t\t\t \t\t\t\t\t\tGOF=vector(\"list\", length=0),\n\t\t\t\t\t\t\t\t\t\t\t\t xmin_estimation=vector(\"list\", length=0),\n\t\t\t\t\t\t\t\t\t\t\t\t uncert_estimation=vector(\"list\", length=0),\n\t\t\t\t\t\t\t\t\t\t\t\t k=0,\n\t\t\t\t\t\t\t\t\t\t\t\t LL=0,\n\t\t\t\t\t\t\t\t\t\t\t\t n=n,\n\t\t\t\t\t\t\t\t\t\t\t\t AICc=0,\n\t\t\t\t\t\t\t\t\t\t\t\t delta_AICc=0,\n\t\t\t\t\t\t\t\t\t\t\t\t AICc_weight=0,\n\t\t\t\t\t\t model_name=character(0),\n\t\t\t\t\t\t modelfit_cont_heavy_tail_mdls_set=character(0))) \n\tfit_ht <- rep(model_list,n_models)\n\tdim(fit_ht) <- c(n_models)\n\n\t# Declare models\n\t# Continuous power law\n\tfit_ht[[1]]$model <- conpl$new(data_set)\n\tfit_ht[[1]]$k <- 1\n\t# Continuous log-normal\n\tfit_ht[[2]]$model <- conlnorm$new(data_set)\n\tfit_ht[[2]]$k <- 2\n\t# Continuous exponential\n\tfit_ht[[3]]$model <- conexp$new(data_set)\n\tfit_ht[[3]]$k <- 1\n\n\t# Set xmin for set 1\n\tfit_ht[[1]]$model$xmin <- xmins\n\tif(length(xmins)>1){\n\t\t# Estimate Xmin with complete data_set for power law model\n\t\tfit_ht[[1]]$xmin_estimation <- estimate_xmin(fit_ht[[1]]$model,\n\t\t\txmins = xmins, \n\t\t\tpars = NULL, \n\t\t\txmax = max(data_set))\n\t\tfit_ht[[1]]$model$setXmin(fit_ht[[1]]$xmin_estimation)\n\t} else if(xmins-1){\n\t\tfit_ht[[1]]$xmin_estimation <- estimate_xmin(fit_ht[[1]]$model,\n\t\t\t\t\t\t\t\t\t\t\t\t\t pars = NULL, \n\t\t\t\t\t\t\t\t\t\t\t\t\t xmax = max(data_set))\n\t\tfit_ht[[1]]$model$setXmin(fit_ht[[1]]$xmin_estimation)\n\t} else {\t\t\n\t\tfit_ht[[1]]$model$setXmin(xmins)\n\t}\n\t\n\t\n\tmodel_names <- c(\"Power\", \"LogNorm\",\"Exp\")\n\n\tAICc_weight <- matrix( nrow = n_models, ncol = 1,\n\t\t\t\t\t\t\tdimnames = list(model_names))\n\n\tdelta_AICc <- AICc_weight\n\tGOF <- delta_AICc\n\tif(n>8) {\n\t\taic_min=Inf\n\t\tnorm_aic_weight=0\n\t\tfor (i in 1:(n_models)){\n\t\t\t# Set cut-off (x_min)\n\t\t\tfit_ht[[i]]$model$xmin <- fit_ht[[1]]$model$xmin\n\t\t\t\n\t\t\t# Correct n with xmin\n\t\t\tfit_ht[[i]]$n <-length(data_set[data_set>=fit_ht[[1]]$model$xmin])\n\n\t\t\t# Fit models\n\t\t\t#\n\t\t\tfit_ht[[i]]$model$setPars(estimate_pars(fit_ht[[i]]$model))\n\t\t\t# \n\t\t\t# Get Loglikelihood\n\t\t\tfit_ht[[i]]$LL <- dist_ll(fit_ht[[i]]$model)\n\n\t\t\tLL <- fit_ht[[i]]$LL\n\t\t\tk <- fit_ht[[i]]$k\n\t\t\t# Compute AICc\n\t\t\t#\n\t\t\tfit_ht[[i]]$AICc <- (2*k-2*LL)+2*k*(k+1)/(n-k-1)\n\t\t\taic_min <- min(aic_min,fit_ht[[i]]$AICc)\n\t\t\tif (gof && fit_ht[[i]]$n>4){\n\t\t\t\t#\n\t\t\t\t# Goodness of fit via boostrap\n\t\t\t\t#\n\t\t\t\t# xmins is fixed at estimated value (or 9)\n\t\t\t\tfit_ht[[i]]$GOF <- try(bootstrap_p(fit_ht[[i]]$model,\n\t\t\t\t\t\t\t\t\t\t\t #xmins=fit_ht[[i]]$model$xmin,\n\t\t\t\t\t\t\t\t\t\t\t pars = NULL, \n\t\t\t\t\t\t\t\t\t\t\t xmax = max(data_set),\n\t\t\t\t\t\t\t\t\t\t\t no_of_sims = 999,\n\t\t\t\t\t\t\t\t\t\t\t threads = parallel::detectCores()))\n\t\t\t\tGOF <- fit_ht[[i]]$GOF\n\t\t\t\tif(class(GOF)!=\"bs_p_xmin\"){\n\t\t\t\t\tfit_ht[[i]]$GOF <-NULL\n\t\t\t\t} else {\n\t\t\t\t\tfit_ht[[i]]$GOF$p <- sum(GOF$gof >= GOF$bootstraps$gof,na.rm = TRUE)/999\n\t\t\t\t}\n\t\t\t\t#\n\t\t\t\t# Uncertainty in parms estimation via bootstrap\n\t\t\t\t#\n\t\t\t\t# Range of xmins to make bootstrap\n# \t\t\t\tl_xmin <- fit_ht[[i]]$model$xmin * 0.8\n# \t\t\t\tu_xmin <- fit_ht[[i]]$model$xmin * 1.2\n# \t\t\t\tfit_ht[[i]]$uncert_estimation <- bootstrap(fit_ht[[i]]$model,\n# \t\t\t\t\t\t\t\t\t\t\t xmins=l_xmin:u_xmin,\n# \t\t\t\t\t\t\t\t\t\t\t pars = NULL, \n# \t\t\t\t\t\t\t\t\t\t\t xmax = max(data_set),\n# \t\t\t\t\t\t\t\t\t\t\t no_of_sims = 1000,\n# \t\t\t\t\t\t\t\t\t\t\t threads = parallel::detectCores())\n\t\t\t}\n\t\t\tfit_ht[[i]]$model_name <- model_names[i]\n\t\t}\n\n\t\tfor (i in 1:n_models){\n\t\t\tdelta_AICc[i] <- fit_ht[[i]]$AICc - aic_min\n\t\t\tfit_ht[[i]]$delta_AICc <- delta_AICc[i]\n\t\t\tnorm_aic_weight <- norm_aic_weight + exp(-0.5*fit_ht[[i]]$delta_AICc) \n\t\t}\n\t\t# Akaike weigths\n\t\tfor (i in 1:n_models){\n\t\t\tAICc_weight[i] <- exp(-0.5*fit_ht[[i]]$delta_AICc)/norm_aic_weight \n\t\t\tfit_ht[[i]]$AICc_weight <- AICc_weight[i]\n\t\t}\n\t\t# Plots\n\t\tif (ploting){\n\t\t\t#setwd(options.output$resultsDir)\n\t\t\t#fnam <-paste0(strsplit(options.output$data_set_name[i_im],\".tif\"),\"_\",labels_set[i_set], \".png\")\n\t\t\t#png(filename=fnam, res=300,units = \"mm\", height=200, width=200,bg=\"white\")\n\n\t\t\tpo <-plot(fit_ht[[1]]$model,xlab=\"Area\",ylab=\"CCDF\")\n\t\t\tfor (i in 1:n_models){\n\t\t\t\tif(model_names[i]!=\"PowerExp\") \n\t\t\t\t{\n\t\t\t\t\tlines(fit_ht[[i]]$model, col=i+1)\n\t\t\t\t} else {\n\t\t\t\t\test1 <- fit_ht[[i]]$model\n\t\t\t\t\tx <- sort(unique(data_set))\n\t\t\t\t\tx <- x[x>=est1$xmin]\n\t\t\t\t\tshift <- max(po[po$x>=est1$xmin,]$y)\n\t\t\t\t\ty <- ppowerexp(x,est1$xmin,est1$exponent,est1$rate,lower.tail=F)*shift\n\t\t\t\t\tlines(x,y,col=i+1)\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlegend(\"topright\",model_names,bty=\"n\",col=seq(2,5),lty=c(1,1,1,1),cex=0.5)\n\t\t\t#dev.off()\n\t\t}\n\t}\n\tfit_ht_df <- ldply(fit_ht,extract_fit_ht_mdls)\n\n\treturn(fit_ht_df) \n}\n\n# Function to extract a data frame from output generated by fit_con_heavy_tail\n#\n#\nextract_fit_ht_mdls <-function(e)\n{\n\tee <- e$model\n\tgg <- e$GOF\n\tuu <- e$uncert_estimation\n\tbootXmin <-list(quantile(uu$bootstraps[,2],probs=c(0.025,0.25,0.5,0.75,0.975),na.rm=T))\n\tbootPar1 <-list(quantile(uu$bootstraps[,3],probs=c(0.025,0.25,0.5,0.75,0.975),na.rm=T))\n\t\n\tif(grepl(\"con\",class(ee),fixed = T))\n\t{\n\t\tdata_frame(model_name=e$model_name,\n\t\t\t\t par1=ifelse(is.null(ee$pars[1]),NA,ee$pars[1]),\n\t\t\t\t par2=ifelse(is.null(ee$pars[2]),NA,ee$pars[2]),\n\t\t\t\t xmin=ee$getXmin(),n=e$n,LL=e$LL,AICc=e$AICc,delta_AICc=e$delta_AICc,\n\t\t\t\t AICc_weight=e$AICc_weight,\n\t\t\t\t GOFp=ifelse(is.null(gg$p),NA,\n\t\t\t\t \t\tifelse(is.na(gg$p),sum(gg$bootstraps$KS>gg$gof,na.rm=TRUE)/nrow(gg$bootstraps),gg$p)),\n\t\t\t\t \n\t\t\t\t bXminQuant=bootXmin,bPar1Quant=bootPar1)\n\t\t\n\t} else {\n\t\tdata_frame(model_name=e$model_name,model_set=e$model_set,par1=ee$exponent,par2=ee$rate,\n\t\t\t\t xmin=ee$xmin,n=e$n,LL=e$LL,AICc=e$AICc,delta_AICc=e$delta_AICc,\n\t\t\t\t AICc_weight=e$AICc_weight,GOFp=ifelse(is.null(gg$p),NA,gg$p),bXminQuant=bootXmin,bPar1Quant=bootPar1)\n\t}\n\t\n}\n\n\n# Fit all the images patch sizes for a region with maybe different areas \n#\n#\nmerge2_region_fit_con_heavy_tail <-function(options,region,new_region){\n\n\t# Change to results folder \n\t#\n\tsetwd(options$resultsDir)\n\n\t# If new_region files already exist don't merge\n\t#\n\tif(list.files(pattern=paste0(\"^.*\",new_region,\".*\\\\.bin$\"))==\"\") {\n\t\t\n\t\t# Get the original files nameswith patch sizes (*.bin) and image file names *.tif (data_set_name)\n\t\t#\n\t\toptions$original_bin_files <- list.files(pattern=paste0(\"^.*\",region,\".*\\\\.bin$\")) # list.files(pattern=\"*.\\\\.bin\")\n\t\n\t\toptions$data_set_name <- unlist(strsplit(options$original_bin_files,\".bin\")) \n\t\t\n\t\t# Merge the two largest patches\n\t\t#\n\t\tfor(i in 1:length(options$data_set_name))\n\t\t{ \n\t\t\tconnection_file <- file(options$original_bin_files[i], \"rb\")\n\t\t\tdata_set <- sort(readBin(connection_file, \"double\", n = 10^6),decreasing=TRUE)\n\t\t\tdata_set[2] <- data_set[1]+data_set[2]\n\t\t\tdata_set <- data_set[2:length(data_set)]\n\t\t\tclose(connection_file)\n\t\n\t\t\t# Change the name of the file to new_region\n\t\t\t#\n\t\t\toptions$original_bin_files[i] <- sub(region,new_region,options$original_bin_files[i])\n\t\t\tconnection_file <- file(options$original_bin_files[i], \"wb\")\n\t\t\twriteBin(data_set,connection_file)\n\t\t\tclose(connection_file)\n\t\t}\t\t\n\t}\n\t\n\t# Get the new files names with merged patches\n\t#\n\t\n\toptions$original_bin_files <- list.files(pattern=paste0(\"^.*\",new_region,\".*\\\\.bin$\")) # list.files(pattern=\"*.\\\\.bin\")\n\t\n\toptions$data_set_name <- unlist(strsplit(options$original_bin_files,\".bin\")) \n\n\tfit <- data_frame()\n\t\n\tfor(i in 1:length(options$data_set_name))\n\t{ \n\t\tif(options$fit)\n\t\t{\n\t\t \tfit <- rbind(fit,call_fit_con_heavy_tail(options,i))\t# Fit models\n\t\t} else {\n\t\t \tfit <- rbind(fit,data_con_heavy_tail(options,i)) \t\t# calculate patch stats\n\t\t}\n\t}\n\n\t# Change to base folder \n\t#\n\tsetwd(oldcd)\n\t\n\treturn(fit)\n}\n\n\n# Plot of RSmax by year and threshold\n#\n# pst: pstat_threshold data frame\n# regions: vector of regions to include\nplot_RSmax_yearThreshold <- function(pst,regions){\n\n\tff1 <- filter(pst,regsub %in% regions) \n\tff2<- group_by(ff1,regsub,threshold) %>% summarise(mprop=mean(prop_max_patch))\n\t\n\tif(length(unique(ff1$regsub))==1)\n\t{\n\t\trequire(viridis)\n\t\tg <- ggplot(ff1, aes(y=prop_max_patch,x=year,colour=regsub)) + theme_bw() +\n\t\tgeom_point(shape=19) + geom_line() + facet_wrap(~threshold) + scale_colour_viridis(discrete = T,guide=F) + \n\t\t\tggtitle(unique(ff1$regsub)) + theme(plot.title = element_text(hjust = 0.5)) +\n\t\t\tgeom_hline(aes(yintercept=mprop,colour=regsub),ff2,linetype = 2)\n\t\t\n\t} else {\n\t\tpd <-position_dodge(.3)\n\t\tg <- ggplot(ff1, aes(y=prop_max_patch,x=year,colour=regsub)) + theme_bw() +\n\t\tgeom_point(shape=19,position=pd) + facet_wrap(~threshold) + scale_colour_brewer(palette=\"Set1\",name=\"Region\") +\n\t\tgeom_hline(aes(yintercept=mprop,colour=regsub),ff2,linetype = 2)\n\t}\n\n\tprint(g + ylab(expression(RS[max])) +\n\t\ttheme(axis.text.x = element_text(angle=90,hjust=0)) \n\t\t)\n\n\n}\n\n# Plot fluctuations of RSmax by year and faceted by threshold\n#\n# pst: pstat_threshold data frame\n# regions: vector of regions to include\nplot_RSmax_Fluctuations_yearThreshold <- function(pst,regions,isSignif,numcol=3){\n\trequire(viridis)\n\tff1 <- filter(pst,regsub %in% regions) \n\tff1 <- filter(ff1,threshold %in% isSignif) %>% mutate(is_signif=TRUE) %>% bind_rows( filter(ff1,!(threshold %in% isSignif)) %>% mutate(is_signif=FALSE) )\n\t#\n\t# Fluctuations around the mean Smax - /TotArea\n\t#\n\tg <- ggplot(ff1, aes(y=delta_prop_max_patch,x=year,colour=is_signif)) + theme_bw() +\n\t\tgeom_point(shape=19,size=1) + facet_wrap(~threshold,ncol=numcol) + \n\t\tylab(expression(Delta~RS[max])) + scale_colour_viridis(discrete = T,guide=F,direction = -1) + \n\t\tggtitle(unique(ff1$regsub)) +\n\t\ttheme(axis.text.x = element_text(angle=90,hjust=0),plot.title = element_text(hjust = 0.5,size=12)) +\n\t\tstat_quantile(quantiles=c(.10,.90),linetype=2)\n\n\tprint(g)\n\treturn(g)\n}\n\n\nplot_RSmax_Fluctuations_yearThreshold_regions <- function(pst,regions,isSignif,numcol=3){\n\trequire(viridis)\n\tff1 <- filter(pst,regsub %in% regions) \n\tff2 <- inner_join(ff1,isSignif) %>% mutate(is_signif=TRUE) \n\tff3 <- anti_join(ff1 %>% ungroup(),isSignif) %>% mutate(is_signif=FALSE) \n\tff1 <- bind_rows(ff2,ff3)\n\t#%>% bind_rows( filter(ff1,!(threshold %in% isSignif)) %>% mutate(is_signif=FALSE) )\n\t#\n\t# Fluctuations around the mean Smax - /TotArea\n\t#\n\tg <- ggplot(ff1, aes(y=delta_prop_max_patch,x=year,colour=is_signif)) + theme_bw() +\n\t\tgeom_point(shape=19) + facet_grid(threshold~regsub) + \n\t\tylab(expression(Delta~RS[max])) + scale_colour_viridis(discrete = T,guide=F,direction = -1) + \n\t\ttheme(axis.text.x = element_text(angle=90,hjust=0),plot.title = element_text(hjust = 0.5)) +\n\t\tstat_quantile(quantiles=c(.10,.90),linetype=2)\n\t\n\tprint(g)\n}\n\n# Plot fluctuations of Absolute max patch Smax by year and faceted by threshold\n#\n# pst: pstat_threshold data frame\n# regions: vector of regions to include\nplot_Smax_Fluctuations_yearThreshold <- function(pst,regions){\n\t\n\tff1 <- filter(pst,regsub %in% regions) \n\t#\n\t# Fluctuations around the mean Smax - /TotArea\n\t#\n\tg <- ggplot(ff1, aes(y=delta_max_patch,x=year,colour=region)) + theme_bw() +\n\t\tgeom_point(shape=19) + facet_wrap(~threshold) +\n\t\tylab(expression(Delta~S[max]~~~(km^2))) + scale_colour_brewer(palette=\"Set1\",name=\"Sub-Region\",guide=F) +\n\t\ttheme(axis.text.x = element_text(angle=90,hjust=0)) +\n\t\tstat_quantile(quantiles=c(.10,.50,.90),linetype=2)\n\t\n\tprint(g)\n}\n\n\n#\n#' Call python routine to estimate distributions and likelihood ratio tests \n#'\n#' @param binDir folder with bin files with patch sizes\n#'\n#' @return data frame with results\n#'\ncall_python_powlawfit <- function(binDir,fit=TRUE){\n\t\n\tps <- paste0(\"python \", oldcd,\"/Code/powlawfit.py 1\")\n\n\tsetwd(binDir)\n\tif(fit){\n\t\tfile.remove(\"fittedDistributions.txt\")\n\t\t\n\t\tsystem(ps)\n\t}\n\tpyfit <- read.table(\"fittedDistributions.txt\", header=TRUE,sep=\"\\t\",stringsAsFactors=FALSE)\n\t#names(pyfit)\n\n\tpyfit1 <- pyfit %>% group_by(model_name,file_name) %>% do( {\n\t\tss <- strsplit(.$file_name,\"_\")\n\t\tregion <- ss[[1]][2]\n\t\tsubregion <- ss[[1]][3]\n\t\tthreshold <- ss[[1]][4]\n\t\tyear <- gsub(\".*\\\\.A([0-9]{4}).*\",\"\\\\1\",.$file_name)\n\t\tdata.frame(region=region,subregion=subregion,threshold=threshold,year=year)})\n\t\n\tpyfit <- pyfit %>% inner_join(pyfit1) %>% arrange(region,subregion,threshold)\n\t\n\t# Lognormal without restriction has mu negative which results in a 99.7% probability is outside the range of patch data\n\t#\n\t\n\tlNorm <- pyfit %>% ungroup() %>% filter(grepl(\"Log.*\",model_name)) %>% select(model_name:xmin) %>% mutate(mu=exp(par1),si=exp(par2),lowd=mu/si^3,hid=mu*si^3)\n\n\tprint(lNorm %>% mutate(higher= hid>.01) %>% group_by(model_name,higher) %>% summarize(n=n(), mlow=mean(lowd),mhi=mean(hid)) %>% mutate(modFreq= n/sum(n)))\n\t#\n\t#\n\tpyfit <- filter(pyfit, model_name!=\"LogNorm\")\n\t\n\tpyfit <- pyfit %>% group_by(file_name) %>% mutate(delta_AICc= AICc - min(AICc),\n\t\t\t\t\t\t\t\t\t\t\t\t\t norm_AICc_w = exp(-0.5*delta_AICc),\n\t\t\t\t\t\t\t\t\t\t\t\t\t AICc_weight=exp(-0.5*delta_AICc)/sum(norm_AICc_w))\n\t\n\tsetwd(oldcd)\n\t\n\treturn(list(pyfit=pyfit,lNorm=lNorm))\n\t}\n\n\n#\n#' Call python routine to estimate distributions and likelihood ratio tests \n#' for delta_Smax and delta_RSmax\n#'\n#' @param binDir folder with bin files with patch sizes\n#'\n#' @return data frame with results\n#'\ncall_python_powlawfit_delta_threshold <- function(ff,binDir,fit=TRUE){\n\t\n\tsetwd(binDir)\n\n\tgroup_by(ff, regsub,threshold) %>% do( nothing={ \t\n\t\tzz <- file(paste0(\"delta_\", .$regsub,\"_\",.$threshold,\"_.bin\")[1], \"wb\")\n\t\twriteBin(.$delta_max_patch,zz) \n\t\tclose(zz)\n\t\treturn(.$regsub)\n\t })\n\n\n\n\tps <- paste0(\"python \", oldcd,\"/Code/powlawfit.py 0\")\n\n\tif(fit){\n\t\tfile.remove(\"fittedDistributions.txt\")\n\t\t\n\t\tsystem(ps)\n\t}\n\tpyfit <- read.table(\"fittedDistributions.txt\", header=TRUE,sep=\"\\t\",stringsAsFactors=FALSE)\n\t#names(pyfit)\n\n\tpyfit1 <- pyfit %>% group_by(model_name,file_name) %>% do( {\n\t\tss <- strsplit(.$file_name,\"_\")\n\t\tregsub <- ss[[1]][2]\n\t\tthreshold <- ss[[1]][3]\n\t\tdata.frame(regsub=regsub,threshold=threshold)})\n\t\n\tpyfit <- pyfit %>% inner_join(pyfit1) %>% arrange(regsub,threshold)\n\t\n\t#\n\t#\n\tpyfit <- filter(pyfit, model_name!=\"LogNormPos\")\n\tpyfit <- filter(pyfit, model_name!=\"PowerExp\")\n\t\n\tpyfit <- pyfit %>% group_by(file_name) %>% mutate(delta_AICc= AICc - min(AICc),\n\t\t\t\t\t\t\t\t\t\t\t\t\t norm_AICc_w = exp(-0.5*delta_AICc),\n\t\t\t\t\t\t\t\t\t\t\t\t\t AICc_weight=exp(-0.5*delta_AICc)/sum(norm_AICc_w)) %>% \n\t\tungroup() %>% select( -file_name )\n\t\n\tunlink(\"*.bin\")\n\tsetwd(oldcd)\n\t\n\treturn(pyfit=pyfit)\n\t}", "meta": {"hexsha": "7b43388f1e739c248a804389a764f61485919f6d", "size": 44971, "ext": "r", "lang": "R", "max_stars_repo_path": "R/power_fun.r", "max_stars_repo_name": "lsaravia/CriticalGlobalForest", "max_stars_repo_head_hexsha": "36d5be4ee16706708923bbcff3ace5c0a31576c7", "max_stars_repo_licenses": ["CC-BY-4.0"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/power_fun.r", "max_issues_repo_name": "lsaravia/CriticalGlobalForest", "max_issues_repo_head_hexsha": "36d5be4ee16706708923bbcff3ace5c0a31576c7", "max_issues_repo_licenses": ["CC-BY-4.0"], "max_issues_count": 5, "max_issues_repo_issues_event_min_datetime": "2015-12-01T15:29:28.000Z", "max_issues_repo_issues_event_max_datetime": "2017-12-30T13:05:54.000Z", "max_forks_repo_path": "R/power_fun.r", "max_forks_repo_name": "lsaravia/CriticalGlobalForest", "max_forks_repo_head_hexsha": "36d5be4ee16706708923bbcff3ace5c0a31576c7", "max_forks_repo_licenses": ["CC-BY-4.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-07-05T21:48:21.000Z", "max_forks_repo_forks_event_max_datetime": "2021-07-05T21:48:21.000Z", "avg_line_length": 31.1649341649, "max_line_length": 209, "alphanum_fraction": 0.6623601877, "num_tokens": 15188, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6297746074044134, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.3588787298227148}} {"text": "#Generacion de la Linea de Muerte para la UBA año 2020\n#Solo necesita 32GB de memoria RAM , 8 vCPU y una hora para correr\n\n#limpio la memoria\nrm( list=ls() ) #remove all objects\ngc() #garbage collection\n\nrequire(\"data.table\")\nrequire(\"lightgbm\")\nrequire(\"DiceKriging\")\nrequire(\"mlrMBO\")\n\n#en estos archivos queda el resultado\nkbayesiana <- paste0(\"~/buckets/b2/opt_bayesiana_lgbm/linea_de_muerte.RDATA\")\n\nkBO_iter <- 10 #cantidad de iteraciones de la Optimizacion Bayesiana\n\n#------------------------------------------------------------------------------\n#esta es la funcion de ganancia, que se busca optimizar\n#se usa internamente a LightGBM\n#se calcula internamente la mejor ganancia para todos los puntos de corte posibles\n\nfganancia_logistic_lightgbm <- function(probs, data) \n{\n vlabels <- getinfo(data, \"label\")\n\n tbl <- as.data.table( list( \"prob\"=probs, \"gan\"= ifelse( vlabels==1, 29250, -750 ) ) )\n\n setorder( tbl, -prob )\n tbl[ , gan_acum := cumsum( gan ) ]\n gan <- max( tbl$gan_acum )\n\n return( list( name= \"ganancia\", value= gan, higher_better= TRUE ) )\n}\n#------------------------------------------------------------------------------\n#funcion que va a optimizar la Bayesian Optimization\n\nestimar_lightgbm <- function( x )\n{\n modelo <- lgb.train(data= dBO_train,\n objective= \"binary\", #la clase es binaria\n eval= fganancia_logistic_lightgbm, #esta es la fuciona optimizar\n valids= list( valid1= dBO_test1 ),\n first_metric_only= TRUE,\n metric= \"custom\", #ATENCION tremendamente importante\n num_iterations= 999999, #un numero muy grande\n early_stopping_rounds= 200,\n min_data_in_leaf= as.integer( x$pmin_data_in_leaf ),\n feature_fraction= 0.25,\n learning_rate= 0.02,\n feature_pre_filter= FALSE,\n verbose= -1,\n seed= 102191\n )\n\n ganancia1 <- unlist(modelo$record_evals$valid1$ganancia$eval)[ modelo$best_iter ] \n\n #esta es la forma de devolver un parametro extra\n attr(ganancia1 ,\"extras\" ) <- list(\"pnum_iterations\"= modelo$best_iter )\n\n cat( modelo$best_iter, ganancia1, \"\\n\" )\n\n return( ganancia1 )\n}\n#------------------------------------------------------------------------------\n#Aqui comienza el programa\ndataset <- fread(\"~/buckets/b1/datasets/fe_exthist.txt.gz\")\n\ncampos_lags <- setdiff( colnames(dataset) , c(\"clase_ternaria\",\"clase01\", \"numero_de_cliente\",\"foto_mes\") )\n\n#agreglo los lags de orden 1\nsetorderv( dataset, c(\"numero_de_cliente\",\"foto_mes\") )\ndataset[, paste0( campos_lags, \"_lag1\") :=shift(.SD, 1, NA, \"lag\"), by=numero_de_cliente, .SDcols= campos_lags]\n\n#agrego los deltas de los lags, de una forma nada elegante\nfor( vcol in campos_lags )\n{\n dataset[, paste0(vcol, \"_delta1\") := get( vcol) - get(paste0( vcol, \"_lag1\"))]\n}\n \n#paso la clase a binaria que tome valores {0,1} enteros\ndataset[ , clase01 := ifelse( clase_ternaria==\"BAJA+2\", 1L, 0L) ]\n\n\n#los campos que se van a utilizar, intencionalmente no uso numero_de_cliente\ncampos_buenos <- setdiff( colnames(dataset) , c(\"clase_ternaria\",\"clase01\",\"numero_de_cliente\") )\n\n#hago undersampling de los negativos\n#me quedo con TODOS los positivos, pero con solo el 5% de los negativos\nset.seed(102191)\ndataset[ , azar:= runif( nrow(dataset) ) ]\n\ndataset[ ( foto_mes>=201701 & foto_mes<=202003 & foto_mes!=201912 & ( clase01==1 | azar<=0.05) ), BO_train := 1L]\n\n#Testeo en 201902, el mismo mes pero un año antes\ndataset[ foto_mes==201912, BO_test1 := 1L]\n\n#dejo los datos en el formato que necesita LightGBM\ndBO_train <- lgb.Dataset( data = data.matrix( dataset[ BO_train==1, campos_buenos, with=FALSE]),\n label = dataset[ BO_train==1, clase01],\n free_raw_data = TRUE\n )\n\ndBO_test1 <- lgb.Dataset( data = data.matrix( dataset[ BO_test1==1, campos_buenos, with=FALSE]),\n label = dataset[ BO_test1==1, clase01],\n free_raw_data = TRUE\n )\n\ndataset_aplicacion <- copy( dataset[ foto_mes==202005, ] )\n\n#libero la memoria borrando el dataset\nrm(dataset)\ngc()\n\n#Aqui comienza la configuracion de la Bayesian Optimization\nconfigureMlr(show.learner.output = FALSE)\n\n#configuro la busqueda bayesiana, los hiperparametros que se van a optimizar\n#por favor, no desesperarse por lo complejo\nobj.fun <- makeSingleObjectiveFunction(\n name = \"OptimBayesiana\", #un nombre que no tiene importancia\n fn = estimar_lightgbm, #aqui va la funcion que quiero optimizar\n minimize= FALSE, #quiero maximizar la ganancia \n par.set = makeParamSet(\n makeNumericParam(\"pmin_data_in_leaf\", lower= 10, upper= 30000 )\n ),\n has.simple.signature = FALSE, #porque le pase los parametros con makeParamSet\n noisy= TRUE\n )\n\nctrl <- makeMBOControl( save.on.disk.at.time = 600, save.file.path = kbayesiana )\nctrl <- setMBOControlTermination(ctrl, iters = kBO_iter )\nctrl <- setMBOControlInfill(ctrl, crit = makeMBOInfillCritEI())\n\nsurr.km <- makeLearner(\"regr.km\", predict.type= \"se\", covtype= \"matern3_2\", control = list(trace = FALSE))\n\nif(!file.exists(kbayesiana))\n{\n #lanzo la busqueda bayesiana\n run <- mbo(obj.fun, learner = surr.km, control = ctrl)\n} else {\n #retoma el procesamiento en donde lo dejo\n run <- mboContinue( kbayesiana ) \n}\n\n#En run$x$pmin_data_in_leaf ha quedo el optimo\n#------------------------------------------------------------------------------\n\n#calculo el modelo final\nmodelo_final <- lgb.train(data= dBO_train,\n objective= \"binary\",\n eval= fganancia_logistic_lightgbm,\n valids= list( valid1= dBO_test1 ),\n first_metric_only= TRUE,\n metric= \"custom\",\n num_iterations= 999999,\n early_stopping_rounds= 200,\n learning_rate= 0.02, #ATENCION, este es el valor que se cambia\n min_data_in_leaf= as.integer( run$x$pmin_data_in_leaf ),\n feature_pre_filter= FALSE,\n feature_fraction= 0.25,\n verbose= -1,\n seed= 102191\n )\n\n#Genero los archivos que voy a probar contra el Leaderboard Publico y quedarme con el mejor\nprediccion_202005 <- predict( modelo_final, data.matrix( dataset_aplicacion[ , campos_buenos, with=FALSE]))\n\n#Genero posibles probabilidades de corte, tener en \nfor( vprob_corte in (25:25)/100 ) #de 0.15 a 0.35\n{\n entrega <- as.data.table( list( \"numero_de_cliente\"= dataset_aplicacion[ , numero_de_cliente], \n \"estimulo\"= (prediccion_202005> vprob_corte) ) )\n\n #genero el archivo de salida\n fwrite( entrega, logical01=TRUE, sep=\",\", file= paste0(\"~/buckets/b1/work/BORRADOR_lineademuerte_04_\", vprob_corte*100, \".csv\") )\n \n data = data.table('numero_de_cliente' = dataset_aplicacion[, numero_de_cliente], 'prob' = prediccion_202005)\n fwrite(data, sep = ',', file = paste0(\"~/buckets/b1/work/BORRADOR_lineademuerte_04.probs\"))\n}\n\n#Se deben probar con el metodo de busqueda binaria contra el leaderboard publico las salidas, y quedarse con el mejor\n\n ", "meta": {"hexsha": "409183875a6811d8f62be8931ac1a03143c2d3b0", "size": 7561, "ext": "r", "lang": "R", "max_stars_repo_path": "scripts/lineademuerte.r", "max_stars_repo_name": "miglesias91/dmeyf", "max_stars_repo_head_hexsha": "6b73adacd2f23644b8a14efd784d038c5ec79157", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "scripts/lineademuerte.r", "max_issues_repo_name": "miglesias91/dmeyf", "max_issues_repo_head_hexsha": "6b73adacd2f23644b8a14efd784d038c5ec79157", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "scripts/lineademuerte.r", "max_forks_repo_name": "miglesias91/dmeyf", "max_forks_repo_head_hexsha": "6b73adacd2f23644b8a14efd784d038c5ec79157", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 41.0923913043, "max_line_length": 132, "alphanum_fraction": 0.6078561037, "num_tokens": 2040, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7401743620390163, "lm_q2_score": 0.4843800842769844, "lm_q1q2_score": 0.3585257198641219}} {"text": "model_cumulttfrom <- function (calendarMoments_t1 = c('Sowing'),\n calendarCumuls_t1 = c(0.0),\n cumulTT = 8.0){\n #'- Name: CumulTTFrom -Version: 1.0, -Time step: 1\n #'- Description:\n #' * Title: CumulTTFrom Model\n #' * Author: Pierre Martre\n #' * Reference: Modeling development phase in the \n #' Wheat Simulation Model SiriusQuality.\n #' See documentation at http://www1.clermont.inra.fr/siriusquality/?page_id=427\n #' * Institution: INRA Montpellier\n #' * Abstract: Calculate CumulTT \n #'- inputs:\n #' * name: calendarMoments_t1\n #' ** description : List containing appearance of each stage at previous day\n #' ** variablecategory : state\n #' ** datatype : STRINGLIST\n #' ** default : ['Sowing']\n #' ** unit : \n #' ** inputtype : variable\n #' * name: calendarCumuls_t1\n #' ** description : list containing for each stage occured its cumulated thermal times at previous day\n #' ** variablecategory : state\n #' ** datatype : DOUBLELIST\n #' ** default : [0.0]\n #' ** unit : °C d\n #' ** inputtype : variable\n #' * name: cumulTT\n #' ** description : cumul TT at current date\n #' ** datatype : DOUBLE\n #' ** variablecategory : auxiliary\n #' ** min : -200\n #' ** max : 10000\n #' ** default : 8.0\n #' ** unit : °C d\n #' ** inputtype : variable\n #'- outputs:\n #' * name: cumulTTFromZC_65\n #' ** description : cumul TT from Anthesis to current date \n #' ** variablecategory : auxiliary\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 5000\n #' ** unit : °C d\n #' * name: cumulTTFromZC_39\n #' ** description : cumul TT from FlagLeafLiguleJustVisible to current date \n #' ** variablecategory : auxiliary\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 5000\n #' ** unit : °C d\n #' * name: cumulTTFromZC_91\n #' ** description : cumul TT from EndGrainFilling to current date \n #' ** variablecategory : auxiliary\n #' ** datatype : DOUBLE\n #' ** min : 0\n #' ** max : 5000\n #' ** unit : °C d\n cumulTTFromZC_65 <- 0.0\n cumulTTFromZC_39 <- 0.0\n cumulTTFromZC_91 <- 0.0\n if ('Anthesis' %in% calendarMoments_t1)\n {\n cumulTTFromZC_65 <- cumulTT - calendarCumuls_t1[which(calendarMoments_t1 %in% 'Anthesis')]\n }\n if ('FlagLeafLiguleJustVisible' %in% calendarMoments_t1)\n {\n cumulTTFromZC_39 <- cumulTT - calendarCumuls_t1[which(calendarMoments_t1 %in% 'FlagLeafLiguleJustVisible')]\n }\n if ('EndGrainFilling' %in% calendarMoments_t1)\n {\n cumulTTFromZC_91 <- cumulTT - calendarCumuls_t1[which(calendarMoments_t1 %in% 'EndGrainFilling')]\n }\n return (list (\"cumulTTFromZC_65\" = cumulTTFromZC_65,\"cumulTTFromZC_39\" = cumulTTFromZC_39,\"cumulTTFromZC_91\" = cumulTTFromZC_91))\n}", "meta": {"hexsha": "a86e13953e066fcf3a691778ec2353d565fdecf6", "size": 3901, "ext": "r", "lang": "R", "max_stars_repo_path": "src/r/SQ_Wheat_Phenology/Cumulttfrom.r", "max_stars_repo_name": "Crop2ML-Catalog/SQ_Wheat_Phenology", "max_stars_repo_head_hexsha": "8e9ec229e5f0754d0f4b9d79ac96a084d75dde67", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2020-06-21T18:58:04.000Z", "max_stars_repo_stars_event_max_datetime": "2022-01-29T21:32:28.000Z", "max_issues_repo_path": "src/r/SQ_Wheat_Phenology/Cumulttfrom.r", "max_issues_repo_name": "Crop2ML-Catalog/SQ_Wheat_Phenology", "max_issues_repo_head_hexsha": "8e9ec229e5f0754d0f4b9d79ac96a084d75dde67", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 27, "max_issues_repo_issues_event_min_datetime": "2018-12-04T15:35:44.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-11T08:25:03.000Z", "max_forks_repo_path": "src/r/SQ_Wheat_Phenology/Cumulttfrom.r", "max_forks_repo_name": "Crop2ML-Catalog/SQ_Wheat_Phenology", "max_forks_repo_head_hexsha": "8e9ec229e5f0754d0f4b9d79ac96a084d75dde67", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 7, "max_forks_repo_forks_event_min_datetime": "2019-04-20T02:25:22.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-04T07:52:35.000Z", "avg_line_length": 52.0133333333, "max_line_length": 133, "alphanum_fraction": 0.4386054858, "num_tokens": 936, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.679178686187839, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.3581421435540733}} {"text": "## This script replicates Shiller 1981 using a slightly different data set\n## The replication code was written by Caraiani and Anghel (forthcoming)\n\nbehavioral_equity_market <- function(data_vintage, path_fig) {\n path_data <- here(\"data/vintages\", data_vintage)\n \n ## First specify the packages of interest\n packages <- c(\"ggplot2\", \"readxl\", \"dplyr\", \"tidyr\", \"dplyr\", \"purrr\", \"stringr\",\n \"Quandl\", \"viridis\", \"ggpmisc\", \"readstata13\", \"imfr\", \"writexl\", \"fredr\")\n \n source(here(\"src/check_packages.r\"))\n check_packages(packages) # Check whether packages are installed already and load them \n \n ## Collect data on S&P 500 prices and dividends from QUANDL\n ## Note: Quandl does not requires an API unless user exceeds 50 calls a day.\n \n curr_year <- as.double(format(Sys.Date(), \"%Y\")) # don't change this\n \n first_years <- c(1871, 1947, 1960, 1980)\n # first_years <- c(1871)\n last_years <- c(1947, 1979, 2009, as.double(format(Sys.Date(), \"%Y\")))\n # last_years <- c(1979)\n \n reg_results <- data.frame(matrix(ncol = 5, nrow = 0))\n reg_columns <- c(\"first year\", \"last year\", \"specification\", \"b\", \"r2\")\n colnames(reg_results) <- reg_columns\n \n for (f in first_years) {\n first_year <- f\n \n for (t in last_years) {\n last_year <- t # can be different from current year\n if (last_year <= first_year) next # skip iteration if last year is smaller than first year\n \n #######################################\n ########### DATA PREP #################\n #######################################\n # Read data first\n div <- readRDS(file = here(path_data, \"sp500_dividends.rds\")) \n price <- readRDS(file = here(path_data, \"sp500_prices.rds\"))\n\n # Prep data: Dividends\n div$month <- as.double(format(div$Date, \"%m\"))\n div$year <- as.double(format(div$Date, \"%Y\"))\n div <- subset(div, (year <= last_year & year >= first_year))\n div <- div[order(div$Date), ]\n div <- div %>% # There may be multiple observations per year - we will choose the first observation of every year \n group_by(year) %>%\n filter(row_number() == 1)\n div$Date <- format(div$Date,\"%Y\")\n div <- div %>% rename(div = Value) %>% select(-c(\"month\", \"year\"))\n\n # Prep data: Prices\n price$month <- as.double(format(price$Date, \"%m\"))\n price$year <- as.double(format(price$Date, \"%Y\"))\n price$day <- as.double(format(price$Date, \"%d\"))\n price <- subset(price, (year <= last_year & year >= first_year))\n price <- price[order(price$Date), ]\n price <- price %>% # There may be multiple observations per year so we need to choose the last observation of every year \n group_by(year) %>%\n filter(row_number() == 1)\n \n price$Date <- format(price$Date,\"%Y\")\n price <- price %>% rename(price = Value)\n price <- price %>% select(-c(\"day\", \"month\", \"year\"))\n\n ## Add interest rates from JST database\n rawdata <- read.dta13(here(path_data, \"JSTdatasetR5.dta\"))\n myvars <- c(\"year\", \"country\", \"cpi\", \n \"stir\", # short-term gov bills\n \"ltrate\" # long-term gov bonds\n )\n rates <- rawdata[rawdata$country == \"USA\", myvars]\n rates <- rates %>% \n rename(Date = year) %>% \n mutate(Date = as.character(Date),\n stir = stir/100,\n ltrate = ltrate/100)\n\n ## Merging and indexing\n df <- left_join(div, price, by = \"Date\")\n df <- left_join(df, rates, by = \"Date\")\n\n df$Date <- as.Date(df$Date, format = \"%Y\")\n df$year <- as.double(format(df$Date, \"%Y\"))\n df <- df[order(df$year), ] # Note: the data must be ordered in increasing order of time for the Shiller algo to work \n\n df <- df %>%\n mutate(div_index = div/div[year == first_year]*100) %>%\n mutate(price_index = price/price[year == first_year]*100) %>%\n mutate(infl = (cpi/lag(cpi, 1) - 1)) %>% # inflation defined as growth in yearly CPI inflation \n mutate(stir_real = (1 + stir) / (1 + infl) - 1) %>% # deflate nominal shot-term interest rates\n mutate(ltrate_real = (1 + ltrate) / (1 + infl) - 1) %>% # deflate nominal long-term interest rates\n mutate(price_div_ratio = price / div,\n div_price_ratio = div / price) %>%\n mutate(price_lead5 = lead(price, n = 5),\n annual_return_5yr = (price_lead5/price)^(1/5) - 1, # real annual returns\n annual_return_5yr_minus_stir = annual_return_5yr - stir_real, \n annual_return_5yr_minus_ltrate = annual_return_5yr - ltrate_real, \n year = as.double(format(Date, \"%Y\")),\n ) %>%\n mutate(return_5yr = (1 + annual_return_5yr)^5 - 1, # real returns over the whole period\n return_5yr_minus_stir = (1 + annual_return_5yr_minus_stir)^5 - 1,\n return_5yr_minus_ltrate = (1 + annual_return_5yr_minus_ltrate)^5 - 1)\n\n \n ## Shiller method of detrending data and constructing PV of dividends\n \n # Compute long run exponential growth rate (last observation - first observation)\n g <- (df[df$year==last_year, \"price\"] / df[df$year==first_year, \"price\"]) ^ (1/(nrow(df)-1)) - 1\n\n # Detrend prices\n df$price_detrended <- df$price\n for (i in 1:nrow(df)) {\n df[i, \"price_detrended\"] <- df[i, \"price_detrended\"] / (1+g)^(i-nrow(df))\n }\n\n # Detrend dividends\n df$div_detrended <- df$div\n for (i in 1:nrow(df)) {\n df[i, \"div_detrended\"] <- df[i, \"div_detrended\"] / (1+g)^(i-nrow(df))\n }\n\n # Compute constant discount rate as the mean yield of stocks over chosen period\n r <- mean(df$div_detrended) / mean(df$price_detrended)\n\n # Set terminal price \n tp <- mean(df$price_detrended)\n\n # Compute fundamental values\n df$p_star <- df$price_detrended\n df[nrow(df),\"p_star\"] <- tp\n for (i in (nrow(df)-1):1) { \n df[i,\"p_star\"] = (df[i+1,\"p_star\"] + df[i,\"div_detrended\"]) / (1 + r)\n }\n \n #######################################\n ########### PLOTTING ##################\n #######################################\n \n ## PLOTTING Shiller graph\n # load the formatting and saving settings from another script\n source(here(\"src/format_plots.r\"))\n source(here(\"src/save_plots.r\"))\n \n if (last_year - first_year <= 60) {\n xticks = 10\n } else {\n xticks = 20\n }\n xlimits <- c(as.double(first_year), as.double(format(Sys.Date(), \"%Y\")))\n \n # Wide to long format (better for ggplot)\n df_tmp <- df %>%\n select(c(\"price_detrended\", \"p_star\", \"year\")) %>%\n pivot_longer(c(\"price_detrended\", \"p_star\"), names_to = \"series\", values_to = \"value\") \n df_tmp$series <- gsub(\"price_detrended\", \"Actual\", df_tmp$series, fixed = TRUE)\n df_tmp$series <- gsub(\"p_star\", \"Expected\", df_tmp$series, fixed = TRUE)\n \n ggplot(data = df_tmp, aes(x = year, y = value)) +\n geom_line(aes(color = series, linetype = series), size = 2) +\n scale_x_continuous(breaks=seq(xlimits[1], xlimits[2], xticks)) +\n labs(y = \"\", x = \"\", title = \"\") + \n format +\n scale_linetype_manual(values = c(\"solid\", \"dotdash\")) +\n scale_color_manual(values = c(purple, green))\n \n # Save\n savefolder <- here(path_fig, \"behavioral_finance\")\n filename <- paste(\"equity_market_\", as.character(first_year), \"_\", as.character(last_year), \".png\", sep = \"\")\n save_plots(filename, savefolder)\n \n ## PLOTTING price to dividend against subsequent 7-year return\n df_tmp <- na.omit(df)\n nth_year <- 5 # Label every nth year\n df_tmp <- df_tmp %>% mutate(year = as.character(year))\n df_tmp$year[seq(1, nrow(df_tmp), nth_year)] <- NA\n formula = y ~ x\n xlimits <- c(0, NA)\n \n ggplot(data = df_tmp, aes(x = div_price_ratio, y = annual_return_5yr)) +\n geom_smooth(method = lm, formula = formula, se = FALSE, color = purple, size = 2) +\n geom_text(aes(label = year), fontface = \"bold\", size = 5, color = green,\n hjust = 0, nudge_x = 0, check_overlap = TRUE) +\n stat_poly_eq(formula = formula,\n aes(label = paste(stat(rr.label), sep = \", \")),\n label.x = \"right\", label.y = \"top\", size = 6, geom = \"label_npc\"\n ) +\n xlim(xlimits) +\n labs(\n x = \"Dividend-to-price ratio\",\n y = \"5-year annual return\",\n ) + \n format \n \n filename <- paste(\"equity_market_pd_return_\", as.character(first_year), \"_\", as.character(last_year), \".png\", sep = \"\")\n save_plots(filename, savefolder)\n \n ggplot(data = df_tmp, aes(x = div_price_ratio, y = annual_return_5yr_minus_stir)) +\n geom_smooth(method = lm, formula = formula, se = FALSE, color = purple, size = 2) +\n geom_text(aes(label = year), fontface = \"bold\", size = 5, color = green,\n hjust = 0, nudge_x = 0, check_overlap = TRUE) +\n stat_poly_eq(formula = formula,\n aes(label = paste(stat(rr.label), sep = \", \")),\n label.x = \"right\", label.y = \"top\", size = 6, geom = \"label_npc\"\n ) +\n xlim(xlimits) +\n labs(\n x = \"Dividend-to-price ratio\",\n y = \"5-year annual return - 3-month Bill yield\",\n ) + \n format \n \n filename <- paste(\"equity_market_pd_return_stir\", as.character(first_year), \"_\", as.character(last_year), \".png\", sep = \"\")\n save_plots(filename, savefolder)\n \n ggplot(data = df_tmp, aes(x = div_price_ratio, y = annual_return_5yr_minus_ltrate)) +\n geom_smooth(method = lm, formula = formula, se = FALSE, color = purple, size = 2) +\n geom_text(aes(label = year), fontface = \"bold\", size = 5, color = green,\n hjust = 0, nudge_x = 0, check_overlap = TRUE) +\n stat_poly_eq(formula = formula,\n aes(label = paste(stat(rr.label), sep = \", \")),\n label.x = \"right\", label.y = \"top\", size = 6, geom = \"label_npc\"\n ) +\n xlim(xlimits) +\n labs(\n x = \"Dividend-to-price ratio\",\n y = \"5-year annual return - 10-year Bond yield\",\n ) + \n format \n \n filename <- paste(\"equity_market_pd_return_ltrate\", as.character(first_year), \"_\", as.character(last_year), \".png\", sep = \"\")\n save_plots(filename, savefolder)\n \n # caption <- paste(\"Data provider: Quandl. Original data source: Standard & Poor's and Robert Shiller. \n # Period: \", as.character(first_year), \" - \", as.character(last_year), \" Note: \n # The 7-year return is calculated as the 7-year growth in prices.\", sep =\"\") \n \n #################################\n ########## REGRESSIONS ##########\n #################################\n \n # model<- lm(annual_return_5yr ~ price_div_ratio, data = df_tmp)\n # r1 <- c(first_year, last_year, as.character(summary(model)$call[2]), summary(model)$coefficients[2,1], summary(model)$r.squared)\n # \n # model<- lm(annual_return_5yr_minus_stir ~ price_div_ratio, data = df_tmp)\n # r2 <- c(first_year, last_year, as.character(summary(model)$call[2]), summary(model)$coefficients[2,1], summary(model)$r.squared)\n # \n # model<- lm(annual_return_5yr_minus_ltrate ~ price_div_ratio, data = df_tmp)\n # r3 <- c(first_year, last_year, as.character(summary(model)$call[2]), summary(model)$coefficients[2,1], summary(model)$r.squared)\n # \n # model<- lm(annual_return_5yr ~ div_price_ratio, data = df_tmp)\n # r4 <- c(first_year, last_year, as.character(summary(model)$call[2]), summary(model)$coefficients[2,1], summary(model)$r.squared)\n # \n # model<- lm(annual_return_5yr_minus_stir ~ div_price_ratio, data = df_tmp)\n # r5 <- c(first_year, last_year, as.character(summary(model)$call[2]), summary(model)$coefficients[2,1], summary(model)$r.squared)\n # \n # model<- lm(annual_return_5yr_minus_ltrate ~ div_price_ratio, data = df_tmp)\n # r6 <- c(first_year, last_year, as.character(summary(model)$call[2]), summary(model)$coefficients[2,1], summary(model)$r.squared)\n # \n # model<- lm(return_5yr ~ div_price_ratio, data = df_tmp)\n # r7 <- c(first_year, last_year, as.character(summary(model)$call[2]), summary(model)$coefficients[2,1], summary(model)$r.squared)\n # \n # model<- lm(return_5yr_minus_stir ~ div_price_ratio, data = df_tmp)\n # r8 <- c(first_year, last_year, as.character(summary(model)$call[2]), summary(model)$coefficients[2,1], summary(model)$r.squared)\n # \n # model<- lm(return_5yr_minus_ltrate ~ div_price_ratio, data = df_tmp)\n # r9 <- c(first_year, last_year, as.character(summary(model)$call[2]), summary(model)$coefficients[2,1], summary(model)$r.squared)\n # \n # reg_results <- do.call(rbind, list(reg_results, r1, r2, r3, r4, r5, r6, r7, r8, r9)) \n # colnames(reg_results) <- reg_columns\n }\n \n }\n\n # write_xlsx(reg_results, \"table/reg_results_cochrane_2011.xlsx\")\n}", "meta": {"hexsha": "074a418190244435db4fb37f01522b6815a998bf", "size": 14871, "ext": "r", "lang": "R", "max_stars_repo_path": "code/lec1/shiller_graph.r", "max_stars_repo_name": "tudorschlanger/macro-finance-lectures", "max_stars_repo_head_hexsha": "fa658fefce90362c0e5db671be39009e14ce6e31", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "code/lec1/shiller_graph.r", "max_issues_repo_name": "tudorschlanger/macro-finance-lectures", "max_issues_repo_head_hexsha": "fa658fefce90362c0e5db671be39009e14ce6e31", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "code/lec1/shiller_graph.r", "max_forks_repo_name": "tudorschlanger/macro-finance-lectures", "max_forks_repo_head_hexsha": "fa658fefce90362c0e5db671be39009e14ce6e31", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 53.6859205776, "max_line_length": 142, "alphanum_fraction": 0.5148947616, "num_tokens": 3594, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5736784220301064, "lm_q2_score": 0.6224593382055109, "lm_q1q2_score": 0.3570914909196419}} {"text": "## Assorted routines for manipulation of\r\n## Zernike polynomials, interferogram analysis,\r\n## and other forms of optical testing\r\n\r\n## Author: M.L. Peck (mlpeck54@gmail.com)\r\n## Language: R (http://www.r-project.org/)\r\n## Copyright (c) 2004-2021, M.L. Peck\r\n\r\n\r\n\r\n\r\n## greyscale\r\n\r\ngrey256 <- gray(seq(0,1,length=256))\r\ngray256 <- grey256\r\n\r\n## A rainbow that may be better than R's rainbow() color palette\r\n\r\nrygcb <- colorRampPalette(c(\"red\", \"yellow\", \"green\", \"cyan\", \"blue\"), space = \"Lab\",\r\n interpolate=\"spline\")\r\n \r\n## Yet another rainbow made up of additive and subtractive primaries\r\n\r\nrygcbm <- colorRampPalette(c(\"red\", \"yellow\", \"green\", \"cyan\", \"blue\", \"magenta\"),\r\n\t\t\tspace=\"Lab\", interpolate=\"spline\")\r\n\r\n\r\n## comparison plot of n wavefront estimates\r\n\r\nplotn <- function(...,\r\n labels=NULL, addContours=FALSE,\r\n wftype=\"net\", col=rygcb(400), qt=c(.01, .99)) {\r\n\tfits <- list(...)\r\n\tnwf <- length(fits)\r\n\twfget <- paste(\"wf\",wftype,sep=\".\")\r\n\twfi <- get(wfget, pos=fits[[1]])\r\n\tnr <- nrow(wfi)\r\n\tnc <- ncol(wfi)\r\n\twfs <- array(0, dim=c(nr,nc,nwf))\r\n\twfs[,,1] <- wfi\r\n\tfor (i in 2:nwf) wfs[,,i] <- get(wfget,pos=fits[[i]])\r\n\trm(fits)\r\n\tif(is.null(labels)) labels=1:nwf\r\n\r\n\trdiff <- matrix(0,nwf*(nwf-1)/2,2)\r\n\tk <- 1\r\n\tfor (i in 1:(nwf-1)) {\r\n\t\tfor (j in (i+1):nwf) {\r\n\t\t\trdiff[k,] <- quantile(wfs[,,i]-wfs[,,j], probs=qt, na.rm=TRUE)\r\n\t\t\tk <- k+1\r\n\t\t}\r\n\t}\r\n\tzlim <- range(rdiff)\r\n\tif (tolower(.Platform$OS.type)==\"windows\") {\r\n windows(width = 5*nwf, height = 5*nwf)\r\n } else {\r\n X11(width = 5*nwf,height = 5*nwf)\r\n }\r\n\tpar(mar=c(0,0,2,0))\r\n\tsplit.screen(figs=c(nwf,nwf))\r\n\tfor (i in 1:nwf) {\r\n\t screen(i)\r\n\t wfi <- wfs[,,i]\r\n\t class(wfi) <- \"pupil\"\r\n\t plot(wfi, col=col, addContours=addContours, eqa=(wftype==\"net\"), axes=FALSE)\r\n\t title(main=paste(labels[i],\"rms=\",format(pupilrms(wfi),digits=3)))\r\n\t}\r\n\tscr <- nwf+1\r\n\tfor (row in 1:(nwf-1)) {\r\n\t screen(scr)\r\n\t plot(0:1,0:1,type=\"n\",axes=FALSE)\r\n\t text(0.5,0.5,labels[row])\r\n\t scr <- scr+row\r\n\t for (i in (row+1):nwf) {\r\n\t\tscreen(scr)\r\n\t\timage(1:nr,1:nc,wfs[,,row]-wfs[,,i],col=grey256,asp=1,axes=FALSE,zlim=zlim,useRaster=TRUE)\r\n\t\ttitle(main=paste(\"rms diff =\",format(pupilrms(wfs[,,row]-wfs[,,i]), digits=3)))\r\n\t\tscr <- scr+1\r\n\t }\r\n\t}\r\n\tclose.screen(all.screens=T)\r\n}\r\n\r\n## plot cross sections through a wavefront map\r\n\r\nplotxs <- function(wf, cp, theta0=0, ylim=NULL, N=4, n=101,\r\n\tcol0=\"black\", col=\"gray\", lty=2) {\r\n theta0 <- theta0*pi/180\r\n ixy <- seq(-1,1,length=n)\r\n theta <- (0:(N-1))*pi/N\r\n ix <- cp$rx*ixy\r\n iy <- cp$ry*ixy\r\n if (is.null(ylim)) ylim <- range(wf, na.rm=TRUE)\r\n plot(range(ixy),ylim, type=\"n\", xlab=\"rho\", ylab=\"Height\")\r\n for (i in 1:N) {\r\n\tiix <- round(cp$xc+cos(theta[i])*ix)\r\n\tiiy <- round(cp$yc+sin(theta[i])*iy)\r\n\tpoints(ixy, diag(wf[iix,iiy]), type=\"l\", col=col, lty=lty)\r\n }\r\n iix <- round(cp$xc+cos(theta0)*ix)\r\n iiy <- round(cp$yc+sin(theta0)*iy)\r\n points(ixy, diag(wf[iix,iiy]), type=\"l\", col=col0, lty=lty)\r\n}\r\n\r\n\r\n\r\n###########\r\n## Various fun stuff\r\n###########\r\n\r\n\r\n## Star test simulator & support routines\r\n\r\n## calculate phase values for wavefront at wavelength lambda\r\n## replaces NA values with 0\r\n\r\nwftophase <- function(X, lambda = 1) {\r\n phi <- exp(2i*pi*X/lambda)\r\n phi[is.na(phi)] <- 0\r\n phi\r\n}\r\n\r\n## puts matrix X into corner of npadded x npadded matrix\r\n## padded with zeroes\r\n\r\npadmatrix <- function(X, npad, fill=0) {\r\n nr <- nrow(X)\r\n nc <- ncol(X)\r\n xpad <- matrix(fill, npad, npad)\r\n xpad[1:nr,1:nc] <- X\r\n xpad\r\n}\r\n\r\n\r\n## extract a matrix from the center of a larger matrix\r\n\r\n\r\nsubmatrix <- function(X,size=255) {\r\n nr <- nrow(X)\r\n X[((nr-size)/2+1):((nr+size)/2),((nr-size)/2+1):((nr+size)/2)]\r\n}\r\n\r\n## shuffle quadrants of a 2d fft around to display as an image\r\n\r\n\r\nfftshift <- function(X) {\r\n nr <- nrow(X)\r\n XS <- matrix(0,nr,nr)\r\n XS[1:(nr/2),1:(nr/2)] <- X[(nr/2+1):nr,(nr/2+1):nr]\r\n XS[(nr/2+1):nr,(nr/2+1):nr] <- X[1:(nr/2),1:(nr/2)]\r\n XS[(nr/2+1):nr,1:(nr/2)] <- X[1:(nr/2),(nr/2+1):nr]\r\n XS[1:(nr/2),(nr/2+1):nr] <- X[(nr/2+1):nr,1:(nr/2)]\r\n XS\r\n}\r\n\r\n## computes & displays fraunhofer diffraction pattern\r\n## & mtf for wavefront described in zernike coefficients zcoef\r\n\r\nstartest <- function(wf=NULL, zcoef=NULL, maxorder=14L, phi=0,\r\n\tlambda = 1, defocus=5, cp=NULL,\r\n\tobstruct=NULL, \r\n\tnpad = 4, \r\n\tgamma=2, psfmag=2, displaymtf=TRUE, displaywf=FALSE) {\r\n\r\n if (tolower(.Platform$OS.type) == \"windows\") {\r\n windows(width=15, height=5) \r\n } else {\r\n x11(width=15,height=5)\r\n }\r\n screens<- split.screen(c(1,3))\r\n\r\n if (is.null(wf)) {\r\n wf <- pupil(zcoef=zcoef, maxorder=maxorder, phi=phi, piston=0)\r\n cp <- cp.default\r\n } else {\r\n if (is.null(cp)) {\r\n stop(\"must specify cp if wf is non-null\")\r\n }\r\n }\r\n nrow <- nrow(wf)\r\n ncol <- ncol(wf)\r\n wf.df <- pupil(zcoef=c(0, 0, 0, 1), maxorder=2, nrow=nrow, ncol=ncol, cp=cp)\r\n if (!is.null(obstruct)) {\r\n wf[is.na(wf.df)] <- NA\r\n }\r\n lx <- round(2*cp$rx)+1\r\n ly <- round(2*cp$ry)+1\r\n npad <- npad * .up2(lx,ly)\r\n\r\n phase <- wftophase(wf,lambda)\r\n up <- Mod(fft(padmatrix(phase,npad)))\r\n up <- up*up\r\n\r\n otf <- fft(up, inverse=TRUE)/npad^2\r\n otf <- otf[1:lx,1:ly]\r\n mtf <- Re(otf)\r\n mtf <- mtf/max(mtf)\r\n freqx <- seq(0,1,length=lx)\r\n freqy <- seq(0,1,length=ly)\r\n mtfideal <- 2/pi*(acos(freqx)-freqx*sqrt(1-freqx^2))\r\n\r\n nrpsf <- max(lx,ly)\r\n psf <- submatrix(fftshift(up),floor(nrpsf/psfmag))\r\n screen(screens[2])\r\n image(psf^(1/gamma),col=grey256,asp=1,bty='n', axes=FALSE, useRaster=TRUE)\r\n mtext(\"0\")\r\n\r\n\r\n if (defocus >5) nrpsf <- 2*nrpsf\r\n if (defocus >15) nrpsf <- npad\r\n\r\n phase <- wftophase(wf - defocus/3.46*lambda*wf.df, lambda)\r\n up <- Mod(fft(padmatrix(phase,npad)))\r\n up <- up*up\r\n psf2 <- submatrix(fftshift(up),nrpsf)\r\n screen(screens[1])\r\n image(psf2^(1/gamma),col=grey256, asp=1,bty='n', axes=FALSE, useRaster=TRUE)\r\n mtext(-defocus)\r\n\r\n phase <- wftophase(wf + defocus/3.46*lambda*wf.df, lambda)\r\n up <- Mod(fft(padmatrix(phase,npad)))\r\n up <- up*up\r\n psf2 <- submatrix(fftshift(up),nrpsf)\r\n screen(screens[3])\r\n image(psf2^(1/gamma),col=grey256,asp=1,bty='n',axes=FALSE, useRaster=TRUE)\r\n mtext(defocus)\r\n close.screen(all.screens=TRUE)\r\n\r\n\r\n if (displaywf) {\r\n if (tolower(.Platform$OS.type) == \"windows\") windows() else x11()\r\n plot(wf/lambda)\r\n }\r\n\r\n if (displaymtf) {\r\n if (tolower(.Platform$OS.type) == \"windows\") windows() else x11()\r\n plot(freqx,mtf[1,],type=\"l\",ylab=\"mtf\",xlab=\"relative frequency\")\r\n title(main='MTF vs. ideal')\r\n lines(freqy,mtf[,1])\r\n lines(freqx,mtfideal, lty=5)\r\n grid()\r\n }\r\n list(psf=psf, otf=otf, mtf=mtf)\r\n}\r\n\r\n## Kolmogorov turbulence\r\n\r\nturbwf <- function(friedratio=1, zlist=makezlist(2,40), reps=1) {\r\n require(mvtnorm)\r\n dimz <- length(zlist$n)\r\n cova <- matrix(0, nrow=dimz, ncol=dimz)\r\n c0 <- friedratio^(5/3)*gamma(14/3)*(4.8*gamma(1.2))^(5/6)*(gamma(11/6))^2/(2^(8/3)*pi)\r\n for (i in 1:dimz) {\r\n for (j in i:dimz) {\r\n if ((zlist$m[i] == zlist$m[j]) && (zlist$t[i] == zlist$t[j])) {\r\n n <- zlist$n[i]\r\n np <- zlist$n[j]\r\n cova[i,j] <- (-1)^((n+np-2*zlist$m[i])/2) * sqrt((n+1)*(np+1)) *\r\n gamma((n+np-5/3)/2)/(gamma((np-n+17/3)/2)*gamma((n-np+17/3)/2)*\r\n gamma((n+np+23/3)/2))\r\n cova[j,i] <- cova[i,j]\r\n }\r\n }\r\n }\r\n cova <- cova * c0/(4*pi^2)\r\n zcoef.turb <- rmvnorm(reps, mean=rep(0,dimz), sigma=cova)\r\n if (reps==1) zcoef.turb <- as.vector(zcoef.turb)\r\n list(zcoef.turb=zcoef.turb, V=cova)\r\n}\r\n\r\n\r\n\r\n## Foucault test simulator\r\n\r\nfoucogram <- function(wf, edgex = 0, phradius = 0, slit=FALSE, pad=4, gamma=1, \r\n map =FALSE, lev=0.5) {\r\n\r\n nr <- nrow(wf)\r\n nc <- ncol(wf)\r\n npad <- pad*nextn(max(nr,nc))\r\n phi<-padmatrix(wftophase(wf),npad)\r\n ca<-fftshift(fft(phi))\r\n u <- npad/2 + 1 + edgex\r\n ca[1:(u-phradius-1),]<-0\r\n ca[u,] <- .5*ca[u,]\r\n if (phradius>0) {\r\n if (slit) {\r\n for (i in 1:phradius) {\r\n f <- .5*(1+i/phradius)\r\n ca[(u+i),] <- f*ca[(u+i),]\r\n ca[(u-i),] <- (1-f)*ca[(u-i),]\r\n }\r\n } else {\r\n for (i in 1:phradius) {\r\n f <- .5 + i*sqrt(phradius^2-i^2)/(pi*phradius^2) + asin(i/phradius)/pi\r\n ca[(u+i),] <- f*ca[(u+i),]\r\n ca[(u-i),] <- (1-f)*ca[(u-i),]\r\n }\r\n }\r\n }\r\n ike <- Mod(fft(ca,inverse=T)[1:nr,1:nc])^2\r\n image(ike^(1/gamma),col=grey256,asp=nc/nr,axes=FALSE, useRaster=TRUE)\r\n if (map) {\r\n zmin <- floor(min(wf, na.rm=TRUE))\r\n zmax <- ceiling(max(wf, na.rm=TRUE))\r\n contour(wf,add=TRUE,levels=seq(zmin,zmax,by=lev),\r\n axes=FALSE,frame.plot=FALSE,col=\"red\")\r\n }\r\n ike/max(ike)\r\n}\r\n\r\n## Synthetic interferogram\r\n\r\n## notes: must have either non-null wf or zcoef. If wf is NULL\r\n## and cp is null make a new wavefront with current defaults\r\n## for matrix size and cp in pupil(), otherwise use the values\r\n## passed here. If wf is non-null zcoef is ignored\r\n## and the correct cp must be passed.\r\n\r\nsynth.interferogram <- function(wf=NULL, zcoef=NULL, maxorder=NULL, \r\n nr=nrow(wf), nc=ncol(wf), cp=NULL, \r\n phi=0, addzc=rep(0,4), fringescale=1, \r\n plots=TRUE) {\r\n if (is.null(wf)) {\r\n if (is.null(cp)) {\r\n wf <- pupil(zcoef=zcoef, maxorder=maxorder, phi=phi, piston=0)+\r\n pupil(zcoef=addzc, maxorder=2)\r\n nr <- nrow(wf)\r\n nc <- ncol(wf)\r\n cp <- cp.default\r\n } else {\r\n wf <- pupil(zcoef=zcoef, maxorder=maxorder, phi=phi, piston=0,\r\n nrow=nr, ncol=nc, cp=cp) +\r\n pupil(zcoef=addzc, maxorder=2, nrow=nr, ncol=nc, cp=cp)\r\n }\r\n } else {\r\n if (is.null(cp)) {\r\n stop(\"must specify a value for cp if wf is non-null\")\r\n }\r\n wf <- wf + pupil(zcoef=addzc, maxorder=2, nrow=nr, ncol=nc, cp=cp)\r\n }\r\n igram <- cos(2*pi*wf/fringescale)\r\n igram[is.na(igram)] <- 0\r\n class(igram) <- c(\"pupil\", class(igram))\r\n if (plots) plot(igram, col=grey256, addContours=FALSE)\r\n igram\r\n}\r\n \r\n \r\n#########\r\n## general utilities\r\n#########\r\n\r\n## crop an array\r\n\r\ncrop <- function(img, cp, npad=20) {\r\n nr <- dim(img)[1]\r\n nc <- dim(img)[2]\r\n xmin <- max(1, round(cp$xc-cp$rx-npad))\r\n xmax <- min(nr, round(cp$xc+cp$rx+npad))\r\n ymin <- max(1, round(cp$yc-cp$ry-npad))\r\n ymax <- min(nc, round(cp$yc+cp$rx+npad))\r\n cp.new <- cp\r\n cp.new$xc <- cp$xc-xmin+1\r\n cp.new$yc <- cp$yc-ymin+1\r\n if (length(dim(img)) > 2) img <- img[xmin:xmax,ymin:ymax,]\r\n else img <- img[xmin:xmax,ymin:ymax]\r\n list(im=img, cp=cp.new)\r\n}\r\n\r\n## general purpose 2D convolution using FFT's.\r\n\r\n## kern is the convolution kernel\r\n\r\nconvolve2d <- function(im, kern) {\r\n\tnr <- nrow(im)\r\n\tnc <- ncol(im)\r\n\tnrp <- nr + nrow(kern) - 1\r\n\tncp <- nc + ncol(kern) - 1\r\n\txs <- nrow(kern) %/% 2 + nrow(kern) %% 2\r\n\tys <- ncol(kern) %/% 2 + ncol(kern) %% 2\r\n\tnpad <- nextn(max(nrp, ncp))\r\n\tkern <- padmatrix(kern, npad=npad)\r\n\tim <- padmatrix(im, npad=npad)\r\n\tim.f <- Re(fft(fft(kern)*fft(im), inv=T))\r\n\tim.f <- im.f[xs:(nr+xs-1),ys:(nc+ys-1)]/(npad^2)\r\n\treturn(im.f)\r\n}\r\n\r\n\r\n## Gaussian blur. fw is the standard deviation\r\n## of the gaussian convolution kernel, in pixels.\r\n\r\ngblur <- function(X, fw = 0, details=FALSE) {\r\n if (fw == 0) return(X)\r\n XP <- X\r\n XP[is.na(XP)] <- 0\r\n nr <- nrow(X)\r\n nc <- ncol(X)\r\n ksize <- max(ceiling(4 * fw), 3)\r\n if ((ksize %% 2) == 0) ksize <- ksize+1\r\n xc <- (ksize %/% 2) + 1\r\n xs <- ((1:ksize)-xc)/fw\r\n gkern <- outer(xs, xs, function(x,y) (x^2+y^2))\r\n gkern <- exp(-gkern/2)\r\n gkern <- round(gkern/min(gkern))\r\n npad <- nextn(max(nr,nc)+ksize-1)\r\n XP <- padmatrix(XP, npad)\r\n kernp <- padmatrix(gkern, npad)\r\n XP <- Re(fft(fft(XP)*fft(kernp), inv=TRUE))/(npad^2)/sum(gkern)\r\n XP <- XP[xc:(nr+xc-1), xc:(nc+xc-1)]\r\n XP[is.na(X)] <- NA\r\n if (details) \r\n\t return(list(gkern=gkern, X=XP))\r\n else return(XP)\r\n}\r\n \r\n\r\n\r\n## Plot a complex matrix. \r\n## Maybe make cmat a class, so this becomes default plot routine?\r\n\r\nplot.cmat <- function(X, fn=\"Mod\", col=grey256, cp=NULL, zoom=1, gamma=1, ...) {\r\n\t ## define some possibly useful functions. Note Mod2 produces power spectrum\r\n\t \r\n\tlogMod <- function(X) log(1+Mod(X))\r\n\tMod2 <- function(X) Mod(X)^2\r\n\tlogMod2 <- function(X) log(Mod2(X))\r\n\tnr <- nrow(X)\r\n\tnc <- ncol(X)\r\n\txs <- seq(-nr/2,nr/2-1,length=nr)\r\n\tys <- seq(-nc/2,nc/2-1,length=nc)\r\n\tif (!is.null(cp)) {\r\n\t\txs <- (cp$rx/nr)*xs\r\n\t\tys <- (cp$ry/nc)*ys\r\n\t}\r\n\txsub <- max(1, floor(1+nr/2*(1-1/zoom))) : min(nr, ceiling(nr/2*(1+1/zoom)))\r\n\tysub <- max(1, floor(1+nc/2*(1-1/zoom))) : min(nc, ceiling(nc/2*(1+1/zoom)))\r\n\timage(xs[xsub], ys[ysub], (eval(call(fn, X))[xsub,ysub])^(1/gamma), \r\n\t col=col, asp=1, xlab=\"k_x\", ylab=\"k_y\", useRaster=TRUE, ...)\r\n}\r\n\r\n\r\npick.sidelobe <- function(imagedata, logm=FALSE, gamma=3) {\r\n\timagedata <- imagedata - mean(imagedata)\r\n\tnpad <- nextn(max(nrow(imagedata), ncol(imagedata)))\r\n\tim <- padmatrix(imagedata, npad=npad, fill=0)\r\n\tif (logm) fn <- \"logMod2\" else fn <- \"Mod\"\r\n\tim.fft <- fftshift(fft(im))\r\n\tplot.cmat(im.fft, fn=fn, gamma=gamma)\r\n\tcat(\"Click on the desired sidelobe peak\\n\")\r\n\tpeak <- locator(n=1, type=\"p\", col=\"red\")\r\n\tcat(\"Click on background filter size\\n\")\r\n\tedge <- locator(n=1, type=\"n\")\r\n\thw <- round(sqrt((edge$x)^2+(edge$y)^2))\r\n\tsymbols(0, 0, circles=hw, inches=FALSE, add=TRUE, fg=\"red\")\r\n\treturn(list(sl=c(round(peak$x), round(peak$y)), filter=hw))\r\n}\r\n\r\n\r\n## simple utility returns Euclidean length of a vector\r\n\r\nhypot <- function(x) sqrt(crossprod(x))\r\n\r\n## Zernike moments\r\n\r\nzmoments <- function(zcoef, maxorder=14) {\r\n zcoef <- zcoef[-(1:3)]\r\n zlist <- makezlist(4, maxorder)\r\n nz <- length(zlist$n)\r\n sumstats <- NULL\r\n i <- 1\r\n repeat {\r\n if (i > nz) break\r\n if (zlist$m[i] == 0) {\r\n sumstats <- rbind(sumstats, c(zlist$n[i], zlist$m[i], zcoef[i]))\r\n i <- i+1\r\n }\r\n else {\r\n sumstats <- rbind(sumstats, c(zlist$n[i], zlist$m[i], hypot(zcoef[i:(i+1)])))\r\n i <- i+2\r\n }\r\n }\r\n sumstats <- data.frame(sumstats)\r\n names(sumstats) <- c(\"n\", \"m\", \"value\")\r\n return(sumstats)\r\n}\r\n\r\n## these two functions provide rudimentary project management. The first adds\r\n## Zernike coefficients and rotation angles from one or more fits to a matrix.\r\n## The second separates polished in from instrumental aberrations (if possible)\r\n\r\naddfit <- function(..., th=0, zcm=NULL, theta=numeric(0)) {\r\n fits <- list(...)\r\n nt <- length(fits)\r\n if (length(th)==1 && nt>1) th=rep(th, nt)\r\n theta <- c(theta, th*pi/180)\r\n nz <- length(fits[[1]]$zcoef.net)\r\n for (i in 1:nt) {\r\n zcm <- cbind(zcm, fits[[i]]$zcoef.net[4:nz])\r\n }\r\n list(zcm=zcm, theta=theta)\r\n}\r\n\r\nseparate.wf <- function(zcm, theta, maxorder=14) {\r\n \r\n nt <- length(theta)\r\n zlist <- makezlist(4, maxorder)\r\n nz <- length(zlist$n)\r\n zcb <- matrix(0, nz, 4)\r\n sumstats <- NULL\r\n cx <- c(rep(1,nt),rep(0,nt))\r\n cy <- c(rep(0,nt),rep(1,nt))\r\n i <- 1\r\n repeat {\r\n if (i > nz) break\r\n if (zlist$m[i] == 0) {\r\n zcb[i,1] <- mean(zcm[i,])\r\n zcb[i,3] <- sd(zcm[i,])/sqrt(nt)\r\n sumstats <- rbind(sumstats, c(zlist$n[i], zlist$m[i], zcb[i,1],\r\n NA, zcb[i, 3], rep(NA, 4)))\r\n i <- i+1\r\n } else {\r\n y <- c(zcm[i,],zcm[i+1,])\r\n rx <- c(cos(zlist$m[i]*theta),sin(zlist$m[i]*theta))\r\n ry <- c(-sin(zlist$m[i]*theta),cos(zlist$m[i]*theta))\r\n lsm <- lm(y ~ -1+rx+ry+cx+cy)\r\n cc <- coef(summary(lsm))[,1:2]\r\n zcb[i:(i+1),1] <- cc[1:2,1]\r\n zcb[i:(i+1),3] <- cc[1:2,2]\r\n if (nrow(cc)==4) {\r\n zcb[i:(i+1),2] <- cc[3:4,1]\r\n zcb[i:(i+1),4] <- cc[3:4,2]\r\n }\r\n lsm <- summary(lsm)\r\n sumstats <- rbind(sumstats,c(zlist$n[i],zlist$m[i],\r\n hypot(zcb[i:(i+1),1]), hypot(zcb[i:(i+1),2]),\r\n lsm$sigma, lsm$r.squared,lsm$fstatistic))\r\n i <- i+2\r\n }\r\n }\r\n zcb[is.na(zcb)] <- 0\r\n colnames(zcb) <- c(\"zc_mirror\", \"zc_inst\", \"se_zc_mirror\", \"se_zc_inst\")\r\n colnames(sumstats)[1:7] <- c(\"n\",\"m\",\"rms_mirror\", \"rms_inst\", \"sigma\",\"R2\", \"F\")\r\n wf.mirror <- pupil.arb(zcoef=zcb[,1],zlist=zlist)\r\n wf.inst <- pupil.arb(zcoef=zcb[,2], zlist=zlist)\r\n list(zcb=data.frame(zcb),sumstats=data.frame(sumstats),\r\n wf.mirror=wf.mirror, wf.inst=wf.inst)\r\n}\r\n", "meta": {"hexsha": "8f28f5e4e6559d23e79af0c9433e50ead6b02374", "size": 17104, "ext": "r", "lang": "R", "max_stars_repo_path": "R/zernike_misc.r", "max_stars_repo_name": "mlpeck/zernike", "max_stars_repo_head_hexsha": "553a956417c34847b80a179a3f6922d71120061d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 4, "max_stars_repo_stars_event_min_datetime": "2019-05-15T09:28:48.000Z", "max_stars_repo_stars_event_max_datetime": "2021-06-16T17:28:29.000Z", "max_issues_repo_path": "R/zernike_misc.r", "max_issues_repo_name": "mlpeck/zernike", "max_issues_repo_head_hexsha": "553a956417c34847b80a179a3f6922d71120061d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/zernike_misc.r", "max_forks_repo_name": "mlpeck/zernike", "max_forks_repo_head_hexsha": "553a956417c34847b80a179a3f6922d71120061d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2019-01-17T13:30:49.000Z", "max_forks_repo_forks_event_max_datetime": "2019-01-17T13:30:49.000Z", "avg_line_length": 31.0981818182, "max_line_length": 96, "alphanum_fraction": 0.5323316183, "num_tokens": 5944, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5389832206876841, "lm_q2_score": 0.6619228691808011, "lm_q1q2_score": 0.3567653198779008}} {"text": "################################################################################################\r\n# This code uses myExchangeFileH1 from ReadExchangeFileExample_WKRDBEST2 (Author:David Currie) ###\r\n## This data is dummy data for H1 VS, FT, FO, SS, SA, FM and BV.\r\n## This code does not present anything new. It was an opportunity for me to get to use RDBES format and play around with ratio and inclusion probabilities estimation.\r\n## Ana Ribeiro Santos\r\n########################################################################################\r\n\r\nlibrary(dplyr)\r\n\r\n#load the data\r\nsource (\"ReadExchangeFileExample_WKRDBEST2.r\")\r\n#lst(myExchangeFileH1)\r\n\r\n# Because the data did not have sampled weight or total sample weight I had to estimated.\r\n#add species name to FM table\r\nmyExchangeFileH1$FM$Species <- myExchangeFileH1$SA$SAspeciesCode[match(myExchangeFileH1$FM$SAid,myExchangeFileH1$SA$SAid)]\r\n#head(myExchangeFileH1$FM)\r\n\r\n#dim(myExchangeFileH1$FM)\r\n#For this example we are goin to select just one species = 1015724 = Leuciscus aspius.\r\nmyExchangeFileH1$FM <- myExchangeFileH1$FM [myExchangeFileH1$FM$Species ==\"1015724\",]\r\n\r\n#calculate the weight per length. a and b paramters from Fisbase\r\na <- 0.01389\r\nb <- 3\r\n\r\nmyExchangeFileH1$FM$Wt.at.len_g <- with (myExchangeFileH1$FM, ((as.numeric(FMclass)/10)^ b) * a) # this gives in grams, equation expected CM not MM hence divide by 10\r\n\r\n#calculate the weight for each SAid (Sample ID)\r\nsample_wght_SAid <- myExchangeFileH1$FM %>%\r\n group_by(SAid) %>%\r\n summarise (., SAsampleWeightLive_est = round (sum (Wt.at.len_g), 0)) %>% as.data.frame()\r\n\r\n# merge it with SA table\r\nmyExchangeFileH1$SA <- merge (myExchangeFileH1$SA, sample_wght_SAid)\r\n#head(myExchangeFileH1$SA)\r\n\r\n#Calculate the totalweightlive based on the ratio_SA\r\nmyExchangeFileH1$SA$ratio_SA <- ifelse (is.na (myExchangeFileH1$SA$SAsampleWeightLive), with (myExchangeFileH1$SA, as.numeric (SAnumberTotal) / as.numeric (SAnumberSampled)),\r\n with (myExchangeFileH1$SA, as.numeric (SAtotalWeightLive) / as.numeric (SAsampleWeightLive)))\r\n\r\nmyExchangeFileH1$SA$SAtotalWeightLive_est <- with (myExchangeFileH1$SA, SAsampleWeightLive_est * ratio_SA)\r\n\r\n##########################################################################################################################################################\r\n# uses myExchnageFileH1 data and assumes simple random sampling within stages\r\n# trips within domains (quarter, area and gear) and ages within lengths.\r\n# In the code below, the hierarchy is as follows in order: VS, FT, \"FO\",\"SS\",\"SA\",\"FM\",\"BV\"\r\n\r\n\r\n# set up the population totals\r\npopDat <- as.data.frame(matrix(c(16,39,86,54, 32, 29, 1464760,3937180,6831707, 2876490, 3487500, 2345431),byrow=F,nrow=6,ncol=2))\r\nnames(popDat) <- c(\"tripNum\",\"liveWt\")\r\nrownames(popDat) <- c(\"Q2 27 GND\", \"Q3 27 DRB\", \"Q3 27 FPO\", \"Q4 27 FPO\", \"Q4 27 FYK\", \"Q4 27 GNS\")\r\n\r\n# calculate inclusion probabilities assuming SRS within strata\r\nmyExchangeFileH1$VS$VSincProb <- as.numeric (myExchangeFileH1$VS$VSnumberSampled)/ as.numeric (myExchangeFileH1$VS$VSnumberTotal)\r\nmyExchangeFileH1$BV$BVincProb <- as.numeric (myExchangeFileH1$BV$BVnumberSampled)/ as.numeric (myExchangeFileH1$BV$BVnumberTotal)\r\nmyExchangeFileH1$FM$FMincProb <- 1\r\nmyExchangeFileH1$SA$SAincProb <- as.numeric (myExchangeFileH1$SA$SAnumberSampled)/as.numeric (myExchangeFileH1$SA$SAnumberTotal) \r\nmyExchangeFileH1$SS$SSincProb <- as.numeric (myExchangeFileH1$SS$SSnumberSampled)/as.numeric (myExchangeFileH1$SS$SSnumberTotal) \r\nmyExchangeFileH1$FO$FOincProb <- as.numeric (myExchangeFileH1$FO$FOnumberSampled)/as.numeric (myExchangeFileH1$FO$FOnumberTotal) \r\nmyExchangeFileH1$FT$FTincProb <- as.numeric (myExchangeFileH1$FT$FTnumberSampled)/as.numeric (myExchangeFileH1$FT$FTnumberTotal) \r\n\r\n# caclulate quarter from date, and then make a domain of quarter combined with area\r\n# allocate domains to FM & BV as well\r\nmyExchangeFileH1$SA$FTid <- myExchangeFileH1$SS$FTid[match(myExchangeFileH1$SA$SSid,myExchangeFileH1$SS$SSid)]\r\nmyExchangeFileH1$SS$date <- myExchangeFileH1$FO$FOendDate[match(myExchangeFileH1$SS$FOid,myExchangeFileH1$FO$FOid)]\r\nmyExchangeFileH1$SA$date <- myExchangeFileH1$SS$date[match(myExchangeFileH1$SA$SSid,myExchangeFileH1$SS$SSid)]\r\nmyExchangeFileH1$SA$quarter <- paste(\"Q\",(as.numeric(substr(myExchangeFileH1$SA$date,6,7))-1) %/% 3 + 1,sep=\"\")\r\nmyExchangeFileH1$SA$domain <- paste(myExchangeFileH1$SA$quarter,myExchangeFileH1$SA$SAarea, myExchangeFileH1$SA$SAgear)\r\nmyExchangeFileH1$FM$domain <- myExchangeFileH1$SA$domain[match(myExchangeFileH1$FM$SAid,myExchangeFileH1$SA$SAid)]\r\nmyExchangeFileH1$BV$domain <- myExchangeFileH1$FM$domain[match(myExchangeFileH1$BV$FMid,myExchangeFileH1$FM$FMid)]\r\nmyExchangeFileH1$BV$numAtUnit <- 1\r\n\r\n# add spp to FM\r\nmyExchangeFileH1$FM$spp <- myExchangeFileH1$SA$SAspeciesCode[match(myExchangeFileH1$FM$SAid,myExchangeFileH1$SA$SAid)]\r\n\r\n# -----------------------------------------------------------------------\r\n# a function to calculate inclusion probabilities for the units at the final stage\r\n# of sampling given all the inclusion probabilities for the other stages\r\n# -----------------------------------------------------------------------\r\ngetIncProb <- function(RDB,stages){\r\n nStages <- length(stages)\r\n if (any(stages %in% c(\"FM\"))) {\r\n RDB[[\"FM\"]][[\"FMincProb\"]] <- 1\r\n }\r\n RDB[[stages[[1]]]][[\"incProb\"]] <- RDB[[stages[[1]]]][[paste(stages[[1]],\"incProb\",sep=\"\")]]\r\n for (i in 2:(nStages)) {\r\n indx <- RDB[[stages[[i]]]][[paste(stages[[i-1]],\"id\",sep=\"\")]]\r\n indxPrev <- RDB[[stages[[i-1]]]][[paste(stages[[i-1]],\"id\",sep=\"\")]]\r\n RDB[[stages[[i]]]][[\"incProbPrev\"]] <- RDB[[stages[[i-1]]]][[paste(\"incProb\",sep=\"\")]][match(indx,indxPrev)]\r\n RDB[[stages[[i]]]][[\"incProb\"]] <- RDB[[stages[[i]]]][[\"incProbPrev\"]]*RDB[[stages[[i]]]][[paste(stages[[i]],\"incProb\",sep=\"\")]]\r\n }\r\n return(RDB)\r\n}\r\n\r\n\r\n# -----------------------------------------------------------------------\r\n# Number-at-Length\r\n# -----------------------------------------------------------------------\r\n# set up the stages in the sampling design used in the estimation\r\n#stages <- list(\"FT\",\"FO\", \"SS\",\"SA\",\"FM\")\r\nstages <- list(\"VS\", \"FT\",\"FO\", \"SS\",\"SA\",\"FM\")\r\n#stages <- list(\"LE\",\"SS\",\"SA\",\"FM\")\r\n\r\n# calculate the inclusion probabilities by length class given the other inclusion probabilities \r\n# in the higher stages\r\ntest <- getIncProb(myExchangeFileH1,stages)\r\n\r\n# calculate a Horvitz Thompson estimate for total numbers at length by domain\r\n# assuming srs within the domain - this is valid for the RDBshare data\r\nestL <- tapply(as.numeric(test$FM$FMnumberAtUnit)/test$FM$incProb,list(test$FM$FMclass,test$FM$domain),sum)\r\n\r\n#estL <- test$FM %>%\r\n# group_by(FMclass, domain, spp) %>%\r\n# summarise (., est.L = sum (as.numeric (FMnumberAtUnit)/incProb))\r\n\r\n# calculate a HT estimate for total landed weight using the sampled landed weights\r\n# assuming srs etc as before\r\nestX <- tapply(test$SA$SAtotalWeightLive_est/test$SA$incProbPrev,list(test$SA$domain),sum)/1e3\r\n\r\n# get the relevant population totals\r\npopX <- popDat[match(names(estX),rownames(popDat)),\"liveWt\"]\r\n\r\n# calculate the ratio estimates for numbers at length\r\nestLR <- estL*matrix(rep(popX/estX,dim(estL)[1]),byrow=T,ncol=dim(estL)[2])\r\n\r\n\r\n# compare the estLR with the ratio estimation using the ratio between the sum total sampled weight and the landings in the domain\r\ntest <- myExchangeFileH1\r\nsumX <- tapply(myExchangeFileH1$SA$SAtotalWeightLive_est,list(myExchangeFileH1$SA$domain),sum) # sum te total sampled weight for each domain\r\ntestLR <- estL*matrix(rep(popX/sumX,dim(estL)[1]),byrow=T,ncol=dim(estL)[2]) # multiply the number at length by the ratio between landings and sampled weight\r\n\r\ntestLR\r\nestLR\r\n## They are super different!!! So im wondering if Im doing something wrong here!! The fact that Im working with made up data does not help at all!!\r\n\r\n########################################################################################################################################\r\n# JUST to test if using a different approach from Liz's code and function we would get the same number at length up to Vessel selection'\r\n#############################################################################################################################################\r\nVSinfo <- myExchangeFileH1$VS %>% transmute(VSid,SDid,\r\n VSincProb)%>%distinct()\r\n\r\nFTinfo <-myExchangeFileH1$FT%>%transmute(FTid, VSid, FTincProb )%>%distinct()\r\n\r\n\r\nFOinfo<-myExchangeFileH1$FO%>%transmute(FOid,FTid, time=paste(\"Q\",(as.numeric(substr(myExchangeFileH1$FO$FOendDate,6,7))-1) %/% 3 + 1,sep=\"\"), \r\n metier=FOgear, space=FOarea, FOincProb)%>%distinct()\r\nFOinfo$domain <- paste (FOinfo$time, FOinfo$space, FOinfo$metier) \r\n\r\nSSinfo<-myExchangeFileH1$SS%>%transmute(SSid, FOid, SSincProb)%>%distinct()\r\n#SAinfo<-myExchangeFileH1$SA%>%transmute(SAid,SSid,spp=SAspeciesCode,\r\n# wsamp=SAsampleWeightMeasured,wsamptot=SAtotalWeightMeasured)%>%distinct()\r\n\r\nSAinfo<- myExchangeFileH1$SA%>%transmute(SAid,SSid,spp=SAspeciesCode,SAincProb)%>%distinct()\r\n\r\n\r\nFMinfo<-myExchangeFileH1$FM%>%transmute(FMid,SAid,len=FMclass,n=as.numeric(FMnumberAtUnit), FMincProb)\r\n\r\nsamp_est_stratum_incPro <-FMinfo%>% left_join (SAinfo)%>%left_join(SSinfo)%>%left_join(FOinfo)%>%left_join(FTinfo)%>% left_join(VSinfo) %>%\r\n group_by(domain, spp, len, n) %>%\r\n summarise (., final_prob = FMincProb * SAincProb * SSincProb * FOincProb * FTincProb * VSincProb) %>% \r\n ungroup() %>%\r\n group_by(domain, spp, len) %>%\r\n summarise (., est.n = sum(n / final_prob))\r\n\r\n\r\n\r\n\r\n", "meta": {"hexsha": "7b1fe3e71557dcc5c041a164f18de1bfc69e8f6c", "size": 9706, "ext": "r", "lang": "R", "max_stars_repo_path": "Subgroup1/code/RDBES_EST_IncPRob&Ratio_ARibeiroSantos.r", "max_stars_repo_name": "AnaRibeiroSantos/WKRATIO", "max_stars_repo_head_hexsha": "bc84a8d70f1712cc74fdda3f0b94d7275f11289f", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Subgroup1/code/RDBES_EST_IncPRob&Ratio_ARibeiroSantos.r", "max_issues_repo_name": "AnaRibeiroSantos/WKRATIO", "max_issues_repo_head_hexsha": "bc84a8d70f1712cc74fdda3f0b94d7275f11289f", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Subgroup1/code/RDBES_EST_IncPRob&Ratio_ARibeiroSantos.r", "max_forks_repo_name": "AnaRibeiroSantos/WKRATIO", "max_forks_repo_head_hexsha": "bc84a8d70f1712cc74fdda3f0b94d7275f11289f", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 57.0941176471, "max_line_length": 175, "alphanum_fraction": 0.6551617556, "num_tokens": 2829, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6334102636778403, "lm_q2_score": 0.5621765008857981, "lm_q1q2_score": 0.3560883656595589}} {"text": "\n######################\n############FRAILTY INDEX CALCULATION\n\nsetwd(\"P:/2019 0970 151 000/User Data/Faraz-Export IDAVE folders\")\nlibrary(tidyverse)\nlibrary(icd)\ndf <- read.csv(\"./datasets/New/NACRASCIHI_2_dupRemoved.csv\")\n\ntabna <- function(x){table(x, useNA = \"ifany\")}\n\n\nic <- df %>% select(ID, days_to_lefteddate, dx10code1:dx10code10, alc_status)%>%\nmutate(IDm = paste(ID, days_to_lefteddate, sep=\"_\"))\n\ncodes <- read.csv(\"./ICD10 codes/frailty_score2.csv\")\n\n# codes <- c(\"F00\", \"G81\",\"G30\", \"I69\", \"R29\", \"N39\", \"F05\", \"W19\",\"S00\",\n# \"R31\", \"B96\", \"R41\", \"R26\", \"I67\", \"R56\", \"R40\", \"T83\", \"S06\",\n# \"S42\", \"E87\", \"M25\", \"E86\", \"R54\", \"Z50\", \"F03\", \"W18\", \"Z75\", \"F01\",\n# \"S80\", \"L03\", \"H54\", \"E53\", \"Z60\", \"G20\", \"R55\", \"S22\", \"K59\", \"N17\",\n# \"L89\", \"Z22\", \"B95\", \"L97\", \"R44\", \"K26\", \"I95\", \"N19\", \"A41\", \"Z87\", \n# \"J96\", \"X59\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\",\n# \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\", \"\")\n\n# points <- c(7.1, 4.4, 4, 3.7, 3.6, 3.2, 3.2, 3.2, 3.2, \n# 3.0, 2.9, 2.7, 2.6, 2.6, 2.6, 2.5, 2.4, 2.4,\n# 2.3,2.3,2.3,2.3, 2.2, 2.1, 2.1, 2.1, 2.0, 2.0,\n# 2.0,2.0,1.9,1.9,1.8,1.8,1.8,1.8,1.8,1.8,\n# rep(1.7,3), rep(1.6, 6), 1.5,\n# rep(1.5, 4), rep(1.4, 6),\n\n# ) \n\nfor (i in 1:nrow(codes)){\n\tid_ls <- ic %>% filter_at(vars(dx10code1:dx10code10),\n\t any_vars(substr(.,1,3) == codes$ICD.Code[i])) %>%\n\tselect(IDm , dx10code1:dx10code10) %>% .$IDm \n\t\n\tvar_name <- paste0(\"frail_\",as.character(codes$ICD.Code[i])) #dynamic name in mutate\n\t\n\tic <- ic %>% mutate(!!var_name := ifelse(IDm %in% id_ls, 1, 0))\n}\n\n\n# for (i in 1:nrow(codes)){\n\t# var_name <- paste0(\"frail_\",as.character(codes$ICD.Code[i])) #dynamic name in mutate\n\n\t# ic2 <- ic %>%\n\t# mutate_at(vars(dx10code1:dx10coSde10), ~substr(.,1,3)) %>%\n\t# mutate(!!var_name := ifelse(any(vars(dx10code1:dx10code10) %in% codes$ICD.Code[i]), 1, 0))\n\t\n# }\n##Occurences are low usually\nic %>% select(frail_F00:frail_R50) %>% colSums / nrow(ic) * 100 %>% round(digits=2)\n\nmat <- as.matrix(ic %>% select(frail_F00:frail_R50))\n\nscores <- mat %*% codes$coef \n####Check Safety\nscores[1:5]\nic[1,] %>% select(frail_F00:frail_R50) %>% select_if(.==1)\n############\nic$frailty_score <- scores\nsummary(ic$frailty_score)\n\nic %>% select(IDm, frailty_score) %>% write.csv(\"./ICD10 codes/frailty_index.csv\", row.names = F)", "meta": {"hexsha": "9a7d27c1419ae96abcfbba7dc49fde6c6025a8df", "size": 2260, "ext": "r", "lang": "R", "max_stars_repo_path": "ICD10 codes/Frailty_IndexCalculation.r", "max_stars_repo_name": "farazahmadi/machine-learning-prediction-of-alternate-level-of-care", "max_stars_repo_head_hexsha": "7957364c0f263d2e80325643d1118e9b47ef3754", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "ICD10 codes/Frailty_IndexCalculation.r", "max_issues_repo_name": "farazahmadi/machine-learning-prediction-of-alternate-level-of-care", "max_issues_repo_head_hexsha": "7957364c0f263d2e80325643d1118e9b47ef3754", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "ICD10 codes/Frailty_IndexCalculation.r", "max_forks_repo_name": "farazahmadi/machine-learning-prediction-of-alternate-level-of-care", "max_forks_repo_head_hexsha": "7957364c0f263d2e80325643d1118e9b47ef3754", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.7313432836, "max_line_length": 97, "alphanum_fraction": 0.5646017699, "num_tokens": 995, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6548947290421275, "lm_q2_score": 0.5428632831725052, "lm_q1q2_score": 0.35551830274017754}} {"text": "\n#required packages\nlibrary(\"openxlsx\")\nlibrary(\"stringr\")\nlibrary(ComplexHeatmap)\nlibrary(circlize)\nlibrary(colorspace)\nlibrary(GetoptLong)\nlibrary(ggplot2)\nlibrary(gplots)\nlibrary(survival)\nrequire(\"survival\")\n# install.packages(\"svglite\")\nlibrary(survminer)\nlibrary(reticulate)\n\n\n#set the project path\nproject_path = \"./project/\"\n\n#load patient data (include survival info)\nstudy_cohort = read.xlsx(paste(project_path, \"data/tcga/study_cohort.xlsx\",sep=\"\"), sheet = 1, colNames = TRUE)\nentire_cohort = read.xlsx(paste(project_path, \"data/tcga/entire_cohort.xlsx\",sep=\"\"), sheet = 1, colNames = TRUE)\n\nlength(rownames(study_cohort))\n\nlength(rownames(entire_cohort))\n\nmedian(entire_cohort$ENSG00000206567.8)\n\n#To build a risk score system based on lncRNA signature, we first estimate the coef of the signature\nfit = coxph(Surv(OS, Censor) ~ \n\nENSG00000187185.4+\nENSG00000259641.4+\nENSG00000218510.5 + \nENSG00000257989.1+\nENSG00000206567.8\n, data=study_cohort)\n\n# summary(fit)\n\nHR <- exp(coef(fit))\nCI <- exp(confint(fit))\nP <- round(coef(summary(fit))[,5],8)\nCOEF <- coef(fit)\n\ncolnames(CI) <- c(\"Lower\", \"Higher\")\n\ntable2 <- as.data.frame(cbind(HR, CI,COEF, P))\ntable2\n\n#calculate the risk score based on expression and coef of the signature\n#use coef (estimated in the study cohort) in above table\nentire_cohort$risk_lnc = (\n entire_cohort$ENSG00000187185.4 * table2[1,4] +\n entire_cohort$ENSG00000259641.4 * table2[2,4]+\n entire_cohort$ENSG00000218510.5 * table2[3,4] +\n entire_cohort$ENSG00000257989.1 * table2[4,4] +\n entire_cohort$ENSG00000206567.8 * table2[5,4] )\n\n#calculate hazard ratio\nfit1 = coxph(Surv(OS, Censor) ~ \n\nrisk_lnc\n, data=entire_cohort)\n\n# summary(fit)\n\nHR <- exp(coef(fit1))\nCI <- exp(confint(fit1))\nP <- coef(summary(fit1))[,5]\nCOEF <- coef(fit1)\n\ncolnames(CI) <- c(\"Lower\", \"Higher\")\n\ntable22 <- as.data.frame(cbind(HR, CI,COEF, P))\ntable22\n\n#calculate the time-dependent roc (lncrna signature on entire tcga cohort)\nlibrary(timeROC)\nROC<-timeROC(T=entire_cohort$OS,# survival time\n\ndelta=entire_cohort$Censor,# results, alive or death\n\nmarker=entire_cohort$risk_lnc,# variables\n\ncause=1,\n\nweighting=\"marginal\",\n\ntimes=c(365*3, 365*5, 365*10),# time, survival 3,5,10 years\n\nROC = TRUE,\n\niid = TRUE)\nROC\n\n#the time-dependent roc/auc shown above result and confidence interval shown below\n#the lncrna signature performance on entire TCGA dataset\nconfint(ROC)$CB_AUC\n\n#To build a risk score system based on lncRNA signature + 3 clinical factors, \n#we first estimate the coef of the signature and 3 clinical factors\n\nfit = coxph(Surv(OS, Censor) ~ stage + gender + age_at_diagnosis +\n\nENSG00000187185.4+\nENSG00000259641.4+\nENSG00000218510.5 + \nENSG00000257989.1+\nENSG00000206567.8\n, data=study_cohort)\n\n\n# summary(fit)\n\nHR <- exp(coef(fit))\nCI <- exp(confint(fit))\nP <- round(coef(summary(fit))[,5],8)\nCOEF <- coef(fit)\n\ncolnames(CI) <- c(\"Lower\", \"Higher\")\n\ntable2 <- as.data.frame(cbind(HR, CI,COEF, P))\ntable2\n\n#calculate the risk score based on expression and coef of the signature and 3 clinical factors\n#use coef (estimated in the study cohort) in above table\nentire_cohort$risk_lncClinical = (\n entire_cohort$stage * table2[1,4]+\n entire_cohort$gender * table2[2,4]+\n entire_cohort$age_at_diagnosis * table2[3,4] +\n entire_cohort$ENSG00000187185.4 * table2[4,4] +\n entire_cohort$ENSG00000259641.4 * table2[5,4]+\n entire_cohort$ENSG00000218510.5 * table2[6,4] +\n entire_cohort$ENSG00000257989.1 * table2[7,4] +\n entire_cohort$ENSG00000206567.8 * table2[8,4] )\n\n#calculate the time-dependent roc (lncrna signature + 3 clinical factors on entire cohort)\nlibrary(timeROC)\nROCAll<-timeROC(T=entire_cohort$OS,# survival time\n\ndelta=entire_cohort$Censor,# results, alive or death\n\nmarker=entire_cohort$risk_lncClinical,\n\ncause=1,# positive results\n\nweighting=\"marginal\",\n\ntimes=c(365*3, 365*5, 365*10),# time, survival 3,5,10 years\n\nROC = TRUE,\n\niid = TRUE)\nROCAll\n\n#the time-dependent roc/auc is shown above and confidence interval shown below\n#the lncrna signature + 3 clinical factors performance on entire dataset\nconfint(ROCAll)$CB_AUC\n\ntitle = paste(project_path,\"results/tcga_time-dependent-roc\", \".pdf\", sep=\"\")\n\n# pdf(title)\n\n#(95% CI: 0.6328-0.6835), lncrna, 5 years\n#(95% CI: 0.6771-0.7596), lncrna + 3 clinical factors, 10 years\n\n#plot the time-dependent roc\nplot(ROC,time=365*3,col = \"red\", lty=2,add =FALSE, title=\"\")\nplot(ROC,time=365*5,col = \"red\",lwd=2, add =TRUE)\nplot(ROC,time=365*10,col = \"red\",lty=3, add =TRUE)\n\nplot(ROCAll,time=365*3,col = \"blue\",lty=2,add =TRUE)\nplot(ROCAll,time=365*5,col = \"blue\",lty=3,add =TRUE)\nplot(ROCAll,time=365*10,col = \"blue\",lwd=2,add =TRUE)\nlegend(\"bottomright\", c(\"5-lncRNA at 3 years (AUC = 0.64)\",\"5-lncRNA at 5 years (AUC = 0.66)\",\"5-lncRNA at 10 years (AUC = 0.63)\", \"5-lncRNA + 3 clinical factors at 3 years (AUC= 0.68)\",\"5-lncRNA + 3 clinical factors at 5 years (AUC= 0.67)\", \"5-lncRNA + 3 clinical factors 10 years (AUC= 0.72)\"), lty=c(2,1,3,2,3,1), lwd=c(1,2,1,1,1,2), col = c(\"red\",\"red\",\"red\",\"blue\",\"blue\", \"blue\"), bty=\"n\")\n\n# dev.off()\n\n#calculate the median risk score (lncrna signature)\nmediam_risk_score = median(as.numeric(as.vector(entire_cohort$risk_lnc)))\nentire_cohort$risk_cluster <- 1\nentire_cohort$risk_cluster[which(entire_cohort$risk_lnc <= mediam_risk_score)] <- 0 \nmediam_risk_score\n\n#calculate the surviva different of the high- and low-risk score groups (lncrna signature)\nsurvdiff(Surv(OS, Censor) ~risk_cluster, data = entire_cohort)\n\n#plot the survival difference\nlibrary(survival)\nrequire(\"survival\")\n# install.packages(\"svglite\")\nlibrary(survminer)\n\ndif = survdiff(Surv(OS, Censor) ~risk_cluster, data = entire_cohort)\npv = pchisq(dif$chisq, length(dif$n)-1, lower.tail = FALSE)\npv = formatC(pv, format = \"e\", digits = 2) \nret = c(\"Log-rank\\r\\np = \",pv)\npvalue=paste(ret[1],ret[2], sep=\"\")\n\nfit<- survfit(Surv(OS, Censor) ~ risk_cluster, data = entire_cohort)\n\np <- ggsurvplot(fit, data=entire_cohort,risk.table = TRUE,tables.theme = theme_cleantable(),palette = c(\"#E7B890\", \"#2E9FCF\"), ggtheme = theme_bw(),surv.median.line = \"hv\",legend.title = \"Risk Score\", legend.labs = c(\"Low\", \"High\"), xlab='Time (days)', conf.int = TRUE,pval = pvalue,pval.method=TRUE,conf.int.style='ribbon', conf.int.alpha=0.1)\n \np = p + theme_survminer( font.main = c(16, \"bold\", \"darkblue\"), font.submain = c(15, \"bold\", \"purple\"), font.caption = c(14, \"plain\", \"orange\"), font.x = c(14, \"bold\"), font.y = c(14, \"bold\"), font.tickslab = c(12, \"plain\") )\n\np\n\n#save the results\ntitle = paste(project_path, \"results/RiskScore-Survival-TCGA.tiff\", sep=\"\")\ntiff(title, width=480*7, height=480*7, units=\"px\", res=96*6, compression = \"lzw\")\nprint(p, newpage = FALSE)\ndev.off()\n\n# let's see the median survival time between high- and low-risk groups\n# risk_cluster=0, low-risk score group (low risk), longer survival time\n#risk_cluster=1, high-risk score group (high risk), shorter survival time\nprint(fit)\n\n#we need to drop patients without age_at_diagnosis or OS info\nvalidPatients = entire_cohort[!is.na(entire_cohort$OS),]\nvalidPatients = validPatients[!is.na(validPatients$age_at_diagnosis),]\nmediam_risk_score_lncClinical = median(as.numeric(as.vector(validPatients$risk_lncClinical)))\n#stratified into two groups based on median risk score\nvalidPatients$risk_cluster1 <- 1\nvalidPatients$risk_cluster1[which(validPatients$risk_lncClinical <= mediam_risk_score_lncClinical)] <- 0 \nmediam_risk_score_lncClinical\n\n#calculate the survival difference\n#risk_cluster1=0, low-risk score group (low risk), longer survival time\n#risk_cluster1=1, high-risk score group (high risk), shorter survival time\nfit<- survfit(Surv(OS, Censor) ~ risk_cluster1, data = validPatients)\nfit\n\ndif = survdiff(Surv(OS, Censor) ~risk_cluster1, data = validPatients)\npv = pchisq(dif$chisq, length(dif$n)-1, lower.tail = FALSE)\npv = formatC(pv, format = \"e\", digits = 2) \npv # p-value\n", "meta": {"hexsha": "1369dcbe9c05e84a56317dcf5d096525ed6f7df0", "size": 7911, "ext": "r", "lang": "R", "max_stars_repo_path": "LncRNASurivival-TCGA.r", "max_stars_repo_name": "guoqingbao/PanCancerLncRNA", "max_stars_repo_head_hexsha": "297eca20d1d3e9f97f7df1811f009c8942e1bc0a", "max_stars_repo_licenses": ["Apache-2.0"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2021-01-25T09:38:13.000Z", "max_stars_repo_stars_event_max_datetime": "2021-12-11T02:12:33.000Z", "max_issues_repo_path": "LncRNASurivival-TCGA.r", "max_issues_repo_name": "guoqingbao/PanCancerLncRNA", "max_issues_repo_head_hexsha": "297eca20d1d3e9f97f7df1811f009c8942e1bc0a", "max_issues_repo_licenses": ["Apache-2.0"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "LncRNASurivival-TCGA.r", "max_forks_repo_name": "guoqingbao/PanCancerLncRNA", "max_forks_repo_head_hexsha": "297eca20d1d3e9f97f7df1811f009c8942e1bc0a", "max_forks_repo_licenses": ["Apache-2.0"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2021-02-14T04:42:00.000Z", "max_forks_repo_forks_event_max_datetime": "2021-02-14T04:42:00.000Z", "avg_line_length": 32.8257261411, "max_line_length": 395, "alphanum_fraction": 0.7272152699, "num_tokens": 2651, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6688802603710086, "lm_q2_score": 0.5312093733737562, "lm_q1q2_score": 0.35531546397375835}} {"text": "#!/usr/bin/env Rscript\n#\tBuilding a statistical model for predicting sediment reworking from fraction of preserved bar structures.\n#\tEric Barefoot\n#\tOct 2019\n\n# load packages\n\nlibrary(tidyverse)\nlibrary(here)\nlibrary(broom)\nlibrary(lme4)\nif (interactive()) {\n require(colorout)\n}\n\n# load data\n\nchamb_data = readRDS(file = here('data','derived_data', 'chamberlin_model_data.rds'))\n\n# for helpfulness later - plot up the data with factors, etc\n# factors are that the model results were generated by either:\n # (1) compensational avulsions or\n # (2) random avulsions.\n# The other factors shown are sets of experiments with the same input overbank/channel material ratio (\"input ratio\")\n# This is a strong controlling factor, and is also mapped to a frac_input continuous variable. \n\n# chamb_data %>%\n# ggplot(., aes(x = frac_elems, y = frac_supply)) + \n# geom_point(aes(color = exp_set, shape = model)) \n\n# We are interested in finding the best predictive model for these data. \n# Let's try out some. \n\n# null\n# fixed-effects model with\n# fixed effects on % fully preserved structures\n\nfixed_model_null = lm(frac_supply ~ frac_elems, data = chamb_data)\n\n# fixed-effects model with\n# fixed effects on % fully preserved structures\n# fixed effects on input ratio\n\nfixed_model_input = lm(frac_supply ~ frac_elems + frac_input, data = chamb_data)\n\n# fixed-effects model with\n# fixed effects on % fully preserved structures\n# fixed effects on input ratio\n# also interactions between two predictors.\n\nfixed_model_input_interactions = lm(frac_supply ~ frac_elems*frac_input, data = chamb_data)\n\n# AIC(fixed_model_null, fixed_model_input, fixed_model_input_interactions)\n\n# mixed-effects model with\n# fixed effects on % fully preserved structures\n# random effects on experiment set (proxy for input ratio) mean\n\nmixed_model_int_expSet = lmer(frac_supply ~ frac_elems + (1|exp_set), data = chamb_data)\n\n# mixed-effects model with\n# fixed effects on % fully preserved structures\n# random effects on experiment set (proxy for input ratio) mean\n# random effects on avulsion type mean\n\nmixed_model_int_expSet_avulType = lmer(frac_supply ~ frac_elems + (1|exp_set) + (1|model), data = chamb_data)\n\n# mixed-effects model with \n# fixed effects on % fully preserved structures\n# random effects on experiment set (proxy for input ratio) mean and slope\n\nmixed_model_slp_expSet = lmer(frac_supply ~ frac_elems + (1 + frac_elems|exp_set), data = chamb_data, REML = FALSE, control = lmerControl(optimizer = 'Nelder_Mead'))\n\n# mixed-effects model with\n# fixed effects on % fully preserved structures\n# random effects on experiment set (proxy for input ratio) mean and slope\n# random effects on avulsion type mean and slope\n\nmixed_model_slp_expSet_avulType = lmer(frac_supply ~ frac_elems + (1+frac_elems|exp_set) + (1+frac_elems|model), data = chamb_data, REML = FALSE)\n\n# mixed-effects model with \n# fixed effects on % fully preserved structures\n# fixed effects on input ratio\n# random effects on experiment set (proxy for input ratio) mean and slope\n# random effects on avulsion type mean and slope\n\nmixed_model_input_slp_expSet_avulType = lmer(frac_supply ~ frac_elems + frac_input + (1+frac_elems|model), data = chamb_data, REML = FALSE)\n\n# So after doing all of those models, we need to evaluate them. \n\nmodels_aic = AIC(fixed_model_null, fixed_model_input, mixed_model_int_expSet, mixed_model_int_expSet_avulType, mixed_model_slp_expSet, mixed_model_slp_expSet_avulType, mixed_model_input_slp_expSet_avulType)\n\n# based on this, it looks like the best model is really the simplest fixed-effects model with the input ratio included. \n# That effect seems to be pretty important! Since we have NO way of constraining that in the ancient, the best route forward is determine the sensitivity of the analysis to overbank vs channel deposition and work that in somehow.\n\n# for fun, plot this model on the data.\n\n# chamb_data_pred = chamb_data %>% mutate(pred_supply = predict(fixed_model_input_interactions))\n# \n# ggplot(data = chamb_data_pred) + \n# geom_point(aes(x = frac_elems, y = frac_supply, color = frac_input, shape = model)) + \n# geom_point(aes(x = frac_elems, y = pred_supply), color = 'red3')\n\n# export the best model as a derived data product. \n\nsaveRDS(fixed_model_input_interactions, file = here('data','derived_data', 'chamberlin_stat_model.rds'))\n", "meta": {"hexsha": "47d3c0939480e16e48f3b710427d3d802a2e2124", "size": 4339, "ext": "r", "lang": "R", "max_stars_repo_path": "analysis/analyzing_reworking/make_stat_model_chamberlin.r", "max_stars_repo_name": "ericbarefoot/barefoot_fluvial_reworking_manuscript_2020", "max_stars_repo_head_hexsha": "379d70bafcdc624064b052b8b7e86dd05ffff076", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "analysis/analyzing_reworking/make_stat_model_chamberlin.r", "max_issues_repo_name": "ericbarefoot/barefoot_fluvial_reworking_manuscript_2020", "max_issues_repo_head_hexsha": "379d70bafcdc624064b052b8b7e86dd05ffff076", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "analysis/analyzing_reworking/make_stat_model_chamberlin.r", "max_forks_repo_name": "ericbarefoot/barefoot_fluvial_reworking_manuscript_2020", "max_forks_repo_head_hexsha": "379d70bafcdc624064b052b8b7e86dd05ffff076", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.5514018692, "max_line_length": 229, "alphanum_fraction": 0.7734501037, "num_tokens": 1072, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.658417487156366, "lm_q2_score": 0.5389832206876841, "lm_q1q2_score": 0.3548759777846301}} {"text": "#' Choose initial parameters for direct effects on X and Y\n#'\n#' @param nsnp_x nsnp_x\n#' @param var_gx.x var_gx.x\n#' @param var_x.y var_x.y\n#' @param var_gx.y var_gx.y=0\n#' @param nsnp_y nsnp_y=0\n#' @param var_gy.y var_gy.y=0\n#' @param mu_gx.y mu_gx.y=0\n#' @param var_gy.x var_gy.x=0\n#' @param mu_gy.x mu_gy.x=0\n#' @param prop_gy.x prop_gy.x=1\n#' @param prop_gx.y prop_gx.y=1\n#'\n#' @export\n#' @return List of model parameters\ninit_parameters <- function(nsnp_x, var_gx.x, var_x.y, var_gx.y=0, nsnp_y=0, var_gy.y=0, mu_gx.y=0, var_gy.x=0, mu_gy.x=0, prop_gy.x=1, prop_gx.y=1)\n{\n\tparameters <- list(\n\t\t# Causal effect\n\t\tvar_x.y = var_x.y,\n\n\t\t# Direct effects on x\n\t\tnsnp_x = nsnp_x,\n\t\tvar_gx.x = var_gx.x,\n\t\tvar_gx.y = var_gx.y,\n\t\tmu_gx.y = mu_gx.y,\n\t\tprop_gx.y = prop_gx.y,\n\n\t\tnsnp_y = nsnp_y,\n\t\tvar_gy.y = var_gy.y,\n\t\tvar_gy.x = var_gy.x,\n\t\tmu_gy.x = mu_gy.x,\n\t\tprop_gy.x = prop_gy.x,\n\t\tu = list()\n\t)\n\treturn(parameters)\n}\n\n#' Add confounder variables and their instruments\n#'\n#' @param parameters Output from \\code{init_parameters}\n#' @param nsnp_u nsnp_u\n#' @param var_u.x var_u.x\n#' @param var_u.y var_u.y\n#' @param var_gu.u var_gu.u\n#'\n#' @export\n#' @return List of model parameters\nadd_u <- function(parameters, nsnp_u, var_u.x, var_u.y, var_gu.u)\n{\n\tnom <- \"u\"\n\tif(var_u.x == 0 & var_u.y != 0) nom <- \"b\"\n\tif(var_u.x != 0 & var_u.y == 0) nom <- \"a\"\n\ti <- length(parameters$u) + 1\n\tparameters$u[[i]] <- list(\n\t\tnsnp_u = nsnp_u,\n\t\tvar_u.x = var_u.x,\n\t\tvar_u.y = var_u.y,\n\t\tvar_gu.u = var_gu.u,\n\t\tname_u = nom\n\t)\n\treturn(parameters)\n}\n\n#' Sample the actual effects based on initial parameters\n#'\n#' @param parameters Output from \\code{init_parameters} or \\code{add_u}\n#'\n#' @export\n#' @return List of effect parameters\nsample_system_effects <- function(parameters)\n{\n\tnu <- length(parameters$u)\n\tif(nu > 0)\n\t{\n\t\tfor(i in 1:nu)\n\t\t{\n\t\t\tparameters$u[[i]]$eff_gu.u <- choose_effects(parameters$u[[i]]$nsnp_u, parameters$u[[i]]$var_gu.u)\n\t\t\tparameters$u[[i]]$eff_u.x <- choose_effects(1, parameters$u[[i]]$var_u.x)\n\t\t\tparameters$u[[i]]$eff_u.y <- choose_effects(1, parameters$u[[i]]$var_u.y)\n\t\t}\n\t}\n\n\t# Make genetic effects for x instruments\n\tparameters$eff_gx.x <- choose_effects(parameters$nsnp_x, parameters$var_gx.x)\n\n\t# Make genetic effects for y instruments\n\tparameters$eff_gy.y <- choose_effects(parameters$nsnp_y, parameters$var_gy.y)\n\n\n\t# Create pleiotropic effects for some proportion of the effects\n\t# X-Y\n\tnchoose <- round(parameters$nsnp_x * parameters$prop_gx.y)\n\tind <- sample(1:parameters$nsnp_x, nchoose, replace=FALSE)\n\tparameters$eff_gx.y <- rep(0, parameters$nsnp_x)\n\tif(nchoose > 0)\n\t{\n\t\tparameters$eff_gx.y[ind] <- choose_effects(nchoose, parameters$var_gx.y, mua=parameters$mu_gx.y)\n\t}\n\n\t# Create pleiotropic effects for some proportion of the effects\n\t# Y-X\n\tnchoose <- round(parameters$nsnp_y * parameters$prop_gy.x)\n\tind <- sample(1:parameters$nsnp_y, nchoose, replace=FALSE)\n\tparameters$eff_gy.x <- rep(0, parameters$nsnp_y)\n\tif(nchoose > 0)\n\t{\n\t\tparameters$eff_gy.x[ind] <- choose_effects(nchoose, parameters$var_gy.x, mua=parameters$mu_gy.x)\n\t}\n\n\tparameters$eff_u.x <- sapply(parameters$u, function(x) choose_effects(1, x$var_u.x))\n\tparameters$eff_u.y <- sapply(parameters$u, function(x) choose_effects(1, x$var_u.y))\n\tparameters$eff_x.y <- sqrt(parameters$var_x.y)\n\n\treturn(parameters)\n}\n\n\n#' Simulate individual level data from initial parameters\n#'\n#' @param parameters Output from \\code{init_parameters} or \\code{add_u}\n#' @param nid Sample size to generate\n#'\n#' @export\n#' @return List of matrices and vectors that represent individual level data\nsimulate_population <- function(parameters, nid)\n{\n\tGx <- matrix(rbinom(parameters$nsnp_x * nid, 2, 0.5), nid, parameters$nsnp_x)\n\n\tGy <- matrix(rbinom(parameters$nsnp_y * nid, 2, 0.5), nid, parameters$nsnp_y)\n\n\tU <- lapply(parameters$u, function(param)\n\t{\n\t\tG <- matrix(rbinom(param$nsnp_u * nid, 2, 0.5), nid, param$nsnp_u)\n\t\tu <- make_phen(param$eff_gu.u, G)\n\t\treturn(list(p=u, G=G, nom=param$name_u))\n\t})\n\n\n\tbx <- parameters$eff_gx.x\n\tby <- parameters$eff_gx.y\n\n\tGt <- Gx\n\tif(parameters$nsnp_y > 0)\n\t{\n\t\tbx <- c(bx, parameters$eff_gy.x)\n\t\tby <- c(by, parameters$eff_gy.y)\n\t\tGt <- cbind(Gt, Gy)\n\t}\n\n\tif(length(parameters$u) > 0)\n\t{\n\t\tbx <- c(bx, sapply(parameters$u, function(x) x$eff_u.x))\n\t\tby <- c(by, sapply(parameters$u, function(x) x$eff_u.y))\n\t\tGt <- cbind(Gt, do.call(cbind, lapply(U, function(x) x$p)))\n\t}\n\tby <- c(by, parameters$eff_x.y)\n\n\tx <- make_phen(bx, Gt)\n\ty <- make_phen(by, cbind(Gt, x))\n\n\treturn(list(\n\t\ty=y,\n\t\tx=x,\n\t\tGx=Gx,\n\t\tGy=Gy,\n\t\tU=U\n\t))\n\n}\n\n\n#' Estimate the effects of all SNPs on all phenotypes\n#'\n#' @param sim Output from \\code{simulate_population}\n#'\n#' @export\n#' @return Lists of SNP-trait effect estimates\nestimate_system_effects <- function(sim)\n{\n\t# Get effects of all X SNPs\n\n\tl <- list()\n\n\tgx.x <- gwas(sim$x, sim$Gx)\n\tgx.x$inst <- \"x\"\n\tgx.x$snp <- paste0(1:nrow(gx.x), \"x\")\n\t\n\tgx.y <- gwas(sim$y, sim$Gx)\n\tgx.y$inst <- \"x\"\n\tgx.y$snp <- paste0(1:nrow(gx.y), \"x\")\n\n\tgx <- gx.x\n\tgy <- gx.y\n\n\t# Get effects of all SNPs on Y\n\n\tif(ncol(sim$Gy) > 0)\n\t{\n\t\tgy.x <- gwas(sim$x, sim$Gy)\n\t\tgy.x$inst <- \"y\"\n\t\tgy.x$snp <- paste0(1:nrow(gy.x), \"y\")\n\t\tgx <- rbind(gx, gy.x)\n\n\t\tgy.y <- gwas(sim$y, sim$Gy)\n\t\tgy.y$inst <- \"y\"\n\t\tgy.y$snp <- paste0(1:nrow(gy.y), \"y\")\n\t\tgy <- rbind(gy, gy.y)\n\t}\n\n\tnconf <- length(sim$U)\n\tif(nconf > 0)\n\t{\n\t\tgu.x <- list()\n\t\tgu.y <- list()\n\t\tgx.u <- list()\n\t\tgy.u <- list()\n\t\tgu.u <- list()\n\t\tfor(i in 1:nconf)\n\t\t{\n\t\t\tgu.u[[i]] <- gwas(sim$U[[i]]$p, sim$U[[i]]$G)\n\t\t\tgu.u[[i]]$inst <- paste0(\"u\", i)\n\t\t\tgu.u[[i]]$snp <- paste0(1:nrow(gu.u[[i]]), gu.u[[i]]$inst)\n\n\t\t\tgu.x[[i]] <- gwas(sim$x, sim$U[[i]]$G)\n\t\t\tgu.x[[i]]$inst <- paste0(\"u\", i)\n\t\t\tgu.x[[i]]$snp <- paste0(1:nrow(gu.x[[i]]), gu.x[[i]]$inst)\n\n\t\t\tgx.u[[i]] <- gwas(sim$U[[i]]$p, sim$Gx)\n\t\t\tgx.u[[i]]$inst <- \"x\"\n\t\t\tgx.u[[i]]$snp <- paste0(1:nrow(gx.u[[i]]), gx.u[[i]]$inst)\n\n\t\t\tgu.y[[i]] <- gwas(sim$y, sim$U[[i]]$G)\n\t\t\tgu.y[[i]]$inst <- paste0(\"u\", i)\n\t\t\tgu.y[[i]]$snp <- paste0(1:nrow(gu.y[[i]]), gu.y[[i]]$inst)\n\n\t\t\tif(ncol(sim$Gy) > 0)\n\t\t\t{\n\t\t\t\tgy.u[[i]] <- gwas(sim$U[[i]]$p, sim$Gy)\n\t\t\t\tgy.u[[i]]$inst <- \"y\"\n\t\t\t\tgy.u[[i]]$snp <- paste0(1:nrow(gy.u[[i]]), gy.u[[i]]$inst)\n\t\t\t}\n\t\t}\n\t\tgx <- rbind(gx, dplyr::bind_rows(gu.x))\n\t\tgy <- rbind(gy, dplyr::bind_rows(gu.y))\n\t\tgu <- list()\n\t\tfor(i in 1:nconf)\n\t\t{\n\t\t\tif(ncol(sim$Gy) > 0)\n\t\t\t{\n\t\t\t\tgu[[i]] <- rbind(gx.u[[i]], gy.u[[i]], gu.u[[i]])\n\t\t\t} else {\n\t\t\t\tgu[[i]] <- rbind(gx.u[[i]], gu.u[[i]])\n\t\t\t}\n\t\t}\n\t\tnames(gu) <- paste0(\"u\", 1:nconf)\n\t\tl <- gu\n\t}\n\tl$x <- gx\n\tl$y <- gy\n\treturn(l)\n}\n\n\n\n\n#' Wrapper for simulation pipeline\n#'\n#' Based on the parameters specified this function will call \\code{init_parameters}, \\code{add_u}, \\code{sample_system_effects}, \\code{simulate_population} and \\code{estimate_system_effects}. A separate population is generated for each phenotype (x, y and each of u) to allow 2SMR and PRS analyses\n#'\n#' @param nidx number of individuals for x\n#' @param nidy number of individuals for y\n#' @param nidu Default=0 If 0 then don't simulate separate populations for the u variables\n#' @param nu Default=0 Number of confounders influencing x and y\n#' @param na Default=0 Number of traits upstream of x\n#' @param nb Default=0 Number of traits upstream of y\n#' @param var_x.y var in y explained by x\n#' @param nsnp_x nsnp influencing x\n#' @param var_gx.x variance in x explained by instruments for x\n#' @param var_gx.y Default=0 \n#' @param mu_gx.y Default=0 \n#' @param prop_gx.y Default=1 \n#' @param nsnp_y Default=0 \n#' @param var_gy.y Default=0 \n#' @param var_gy.x Default=0 \n#' @param mu_gy.x Default=0 \n#' @param prop_gy.x Default=1 \n#'\n#' @export\n#' @return List of effects across system\ncreate_system <- function(nidx, nidy, nidu=0, nu=0, na=0, nb=0, var_x.y, nsnp_x, var_gx.x, var_gx.y=0, mu_gx.y=0, prop_gx.y=1, nsnp_y=0, var_gy.y=0, var_gy.x=0, mu_gy.x=0, prop_gy.x=1)\n{\n\tparameters <- init_parameters(nsnp_x=nsnp_x, nsnp_y=nsnp_y, var_gx.x=var_gx.x, var_gy.y=var_gy.y, var_x.y=var_x.y, var_gx.y=var_gx.y, mu_gx.y=mu_gx.y, prop_gx.y=prop_gx.y, var_gy.x=var_gy.x, mu_gy.x=mu_gy.x, prop_gy.x=prop_gy.x)\n\tif(nu > 0)\n\t{\n\t\tfor(i in 1:nu)\n\t\t{\n\t\t\tparameters <- add_u(\n\t\t\t\tparameters, \n\t\t\t\tnsnp_u=sample(5:30, 1), \n\t\t\t\tvar_u.x=stats::runif(1, min=0.01, max=0.1), \n\t\t\t\tvar_u.y=stats::runif(1, min=0.01, max=0.1), \n\t\t\t\tvar_gu.u=stats::runif(1, min=0.02, 0.2)\n\t\t\t)\n\t\t}\n\t}\n\tif(na > 0)\n\t{\n\t\tfor(i in 1:na)\n\t\t{\n\t\t\tparameters <- add_u(\n\t\t\t\tparameters, \n\t\t\t\tnsnp_u=sample(5:30, 1), \n\t\t\t\tvar_u.x=stats::runif(1, min=0.01, max=0.1), \n\t\t\t\tvar_u.y=0,\n\t\t\t\tvar_gu.u=stats::runif(1, min=0.02, 0.2)\n\t\t\t)\n\t\t}\n\t}\n\tif(nb > 0)\n\t{\n\t\tfor(i in 1:nb)\n\t\t{\n\t\t\tparameters <- add_u(\n\t\t\t\tparameters, \n\t\t\t\tnsnp_u=sample(5:30, 1), \n\t\t\t\tvar_u.x=0,\n\t\t\t\tvar_u.y=stats::runif(1, min=0.01, max=0.1),\n\t\t\t\tvar_gu.u=stats::runif(1, min=0.02, 0.2)\n\t\t\t)\n\t\t}\n\t}\n\n\tparameters <- sample_system_effects(parameters)\n\n\tmessage(\"X\")\n\tpop <- simulate_population(parameters, nidx)\n\tx <- estimate_system_effects(pop)\n\n\tmessage(\"Y\")\n\tpop <- simulate_population(parameters, nidy)\n\ty <- estimate_system_effects(pop)\n\n\tout <- list(x=x, y=y, parameters=parameters)\n\n\tif(nidu > 0)\n\t{\n\t\tu <- list()\n\t\tif(nu > 0)\n\t\t{\n\t\t\tfor(i in 1:nu)\n\t\t\t{\n\t\t\t\tmessage(\"U: \", i, \" of \", nu)\n\t\t\t\tpop <- simulate_population(parameters, nidu)\n\t\t\t\tu[[i]] <- estimate_system_effects(pop)\n\t\t\t}\n\t\t}\n\n\t\ta <- list()\n\t\tif(na > 0)\n\t\t{\n\t\t\tfor(i in 1:na)\n\t\t\t{\n\t\t\t\tmessage(\"A: \", i, \" of \", na)\n\t\t\t\tpop <- simulate_population(parameters, nidu)\n\t\t\t\ta[[i]] <- estimate_system_effects(pop)\n\t\t\t}\n\t\t}\n\n\t\tb <- list()\n\t\tif(nb > 0)\n\t\t{\n\t\t\tfor(i in 1:nb)\n\t\t\t{\n\t\t\t\tmessage(\"B: \", i, \" of \", nb)\n\t\t\t\tpop <- simulate_population(parameters, nidu)\n\t\t\t\tb[[i]] <- estimate_system_effects(pop)\n\t\t\t}\n\t\t}\n\t\tu <- c(u, a, b)\n\t\tnames(u) <- paste0(\"u\", 1:length(u))\n\t\tout$u <- u\n\t}\n\treturn(out)\n}\n\n\n#' Apply MR tests to system\n#'\n#'\n#' @param ss Output from create_syste,\n#' @param id string denoting simulation ID\n#'\n#' @export\n#' @return List\ntest_system <- function(ss, id=\"test\")\n{\n\tout <- list()\n\n\tdx <- merge_exp_out(ss$x$x, ss$y$y)\n\tdx$exposure <- paste0(\"X:\", id)\n\tdx$outcome <- paste0(\"Y:\", id)\n\tdx$id.exposure <- paste0(\"X:\", id)\n\tdx$id.outcome <- paste0(\"Y:\", id)\n\n\tdy <- merge_exp_out(ss$y$y, ss$x$x)\n\tdy$exposure <- paste0(\"Y:\", id)\n\tdy$outcome <- paste0(\"X:\", id)\n\tdy$id.exposure <- paste0(\"Y:\", id)\n\tdy$id.outcome <- paste0(\"X:\", id)\n\n\t# Oracle\n\tox <- subset(dx, grepl(\"x\", SNP))\n\tout$ox <- try(TwoSampleMR::mr_wrapper(ox)[[1]])\n\toy <- subset(dy, grepl(\"y\", SNP))\n\tout$oy <- try(TwoSampleMR::mr_wrapper(oy)[[1]])\n\n\t# Empirical\n\tex <- subset(dx, pval.exposure < 5e-8)\n\tout$ex <- try(TwoSampleMR::mr_wrapper(ex)[[1]])\n\tey <- subset(dy, pval.exposure < 5e-8)\n\tout$ey <- try(TwoSampleMR::mr_wrapper(ey)[[1]])\n\n\tparam <- expand.grid(\n\t\thypothesis = c(\"x\", \"y\"), \n\t\tselection = c(\"e\", \"o\"),\n\t\ttype = c(\"valid\", \"reverse\", \"confounder\")\n\t)\n\to <- list()\n\tfor(i in 1:nrow(param))\n\t{\n\t\to[[i]] <- dplyr::tibble(\n\t\t\thypothesis = param$hypothesis[i],\n\t\t\tselection = param$selection[i],\n\t\t\ttype = param$type[i],\n\t\t\tmeasure = c(\"nofilter\", \"outlier\", \"steiger\", \"both\"),\n\t\t\tcounts = get_counts(\n\t\t\t\tparam$type[i], \n\t\t\t\tparam$hypothesis[i],\n\t\t\t\tget(paste0(param$selection[i], param$hypothesis[i])), \n\t\t\t\tout[[paste0(param$selection[i], param$hypothesis[i])]]\n\t\t\t)\n\t\t)\n\t}\n\n\tout$instrument_validity <- dplyr::bind_rows(o) %>% dplyr::group_by(hypothesis, selection, type) %>% dplyr::mutate(n=dplyr::first(counts), pcounts=counts/n)\n\tout$instrument_validity$id <- id\n\n\t# Best model\n\tout$ex$estimates <- best_model(out$ex$estimates, ss$parameters$eff_x.y)\n\tout$ox$estimates <- best_model(out$ox$estimates, 0)\n\n\treturn(out)\n}\n\nget_counts <- function(type, hyp, dat, res)\n{\n\tif(type == \"valid\")\n\t{\n\t\tnode = hyp\n\t} else if(type == \"reverse\") {\n\t\tnode = ifelse(hyp==\"x\", \"y\", \"x\")\n\t} else {\n\t\tnode = \"u\"\n\t}\n\tc(\n\t\tnrow(res$snps_retained %>% subset(grepl(node, SNP))),\n\t\tnrow(subset(res$snps_retained, outlier) %>% subset(grepl(node, SNP))),\n\t\tnrow(subset(res$snps_retained, steiger) %>% subset(grepl(node, SNP))),\n\t\tnrow(subset(res$snps_retained, both) %>% subset(grepl(node, SNP)))\n\t)\n}\n\nbest_model <- function(res, bxy)\n{\n\tres$beta_correct <- res$ci_low <= bxy & res$ci_upp >= bxy\n\tres$beta_best <- FALSE\n\tres$beta_best[which.min(abs(res$b - bxy))] <- TRUE\n\tres$pval_sig <- res$pval < 0.05\n\tres$pval_lowest <- FALSE\n\tres$pval_lowest[which.min(res$pval)] <- TRUE\n\tres$pval_highest <- FALSE\n\tres$pval_highest[which.max(res$pval)] <- TRUE\n\treturn(res)\n}\n", "meta": {"hexsha": "4470721bdf9c798f6e731b0ecf000c627d1bbadf", "size": 12401, "ext": "r", "lang": "R", "max_stars_repo_path": "R/mr_system.r", "max_stars_repo_name": "explodecomputer/simulateGP", "max_stars_repo_head_hexsha": "9dd10532644f9ddb1ce5067d253f473fe4aaeb92", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 1, "max_stars_repo_stars_event_min_datetime": "2021-11-05T16:58:46.000Z", "max_stars_repo_stars_event_max_datetime": "2021-11-05T16:58:46.000Z", "max_issues_repo_path": "R/mr_system.r", "max_issues_repo_name": "aeaswar81/simulateGP", "max_issues_repo_head_hexsha": "9dd10532644f9ddb1ce5067d253f473fe4aaeb92", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2020-10-20T16:14:15.000Z", "max_issues_repo_issues_event_max_datetime": "2020-10-20T16:14:15.000Z", "max_forks_repo_path": "R/mr_system.r", "max_forks_repo_name": "aeaswar81/simulateGP", "max_forks_repo_head_hexsha": "9dd10532644f9ddb1ce5067d253f473fe4aaeb92", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2021-03-10T19:27:35.000Z", "max_forks_repo_forks_event_max_datetime": "2021-11-05T16:59:02.000Z", "avg_line_length": 25.4640657084, "max_line_length": 297, "alphanum_fraction": 0.6285783405, "num_tokens": 4583, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6723317123102956, "lm_q2_score": 0.5273165233795671, "lm_q1q2_score": 0.35453162109329645}} {"text": "###########################################################################################\n### Table 3 simulation (linear)\n###########################################################################################\neachCase <- function(case,eff=0)\n sapply(c('sh','ik','cft'),\n function(method) c(bias=case[paste0(method,'.est')]-eff,\n cover=case[paste0(method,'.CIl')]<=eff &\n case[paste0(method,'.CIh')]>=eff,\n width=case[paste0(method,'.CIh')]-\n case[paste0(method,'.CIl')])\n )\n\nlevTabCI <- function(res,eff=0){\n out <- NULL\n for(n in c(50,250,2500))\n for(err in c('norm','t')){\n run <- res[[paste(n,eff,err,sep='_')]]\n row <- NULL\n for(meth in c('cft','sh','ik'))\n row <- c(row,\n if(is.list(run))\n mean(sapply(run,function(x) x[paste0(meth,'.p')])<0.05,na.rm=TRUE)\n else mean(run[paste0(meth,'.p'),]<0.05))\n\n out <- rbind(out,row)\n rownames(out)[nrow(out)] <- paste(err,n)\n }\n colnames(out) <- c('cft','sh','ik')\n out\n}\n\ndisplayCIsimHet <- function(res,tau=0,caption='',label=''){\n ## omit cases where one of the methods (ours?) didn't converge, gave NA\n res <- lapply(res,function(x) t(x[,apply(x,2,function(cc) !any(is.na(cc)))]))\n\n res <- res[grep(paste0('_tau',tau,'W'),names(res),fixed=TRUE)]\n res <- res[grepl('Wnone|Wt',names(res))]\n\n\n tab0 <- lapply(res,function(x)\n apply(sapply(1:nrow(x),function(i) eachCase(x[i,],eff=tau),simplify='array'),\n 1:2,mean))\n\n tab0 <- lapply(tab0,function(xx){\n out <- rbind(sprintf(\"%.2f\",round(xx[1,],2)),sprintf(\"%i\",as.integer(round(xx[2,]*100))),sprintf(\"%.2f\",round(xx[3,],2)))\n dimnames(out) <- dimnames(xx)\n out})\n\n cat('\n\\\\begin{table}\n\\\\footnotesize\n\\\\begin{tabular}{ccc|ccc|ccc|ccc}\n\\\\hline\n\n&&& \\\\multicolumn{ 3 }{c}{Permutation}&\\\\multicolumn{ 3 }{c}{\\`\\`Limitless\\'\\'}&\\\\multicolumn{ 3 }{c}{Local OLS}\\\\\\\\\n$n$& Effect& Error &', paste(rep(c('Bias','Cover.','Width'),3),collapse='&'),'\\\\\\\\\n\\\\hline \\n')\n for(n in c(50,250,2500))\n# for(err in c('norm','t')){\n for(rr in c('n0','t0','tt')){\n row <- NULL\n err <- ifelse(rr=='n0','norm','t')\n eff <- ifelse(rr=='tt','$t_3$',0)\n for(meth in c('cft','sh','ik'))\n row <- c(row,tab0[[paste0(n,'_err',err,'_tau',tau,'W',ifelse(rr=='tt','t','none'))]][,meth])\n if(err=='norm'){\n cat('\\\\hline \\n')\n cat('\\\\multirow{3}{*}{',n,'} &0& $\\\\mathcal{N}(0,1)$ &')\n } else cat(' & ',eff,'& $t_3$ &')\n cat(paste(row,collapse='&'),'\\\\\\\\ \\n')\n }\n cat('\\\\hline\n\\\\end{tabular}\n \\\\caption{',caption,'}\n \\\\label{',label,'}\\n',sep='')\n cat('\\\\end{table}\\n')\n}\n\ndispAllSimp <- function(res){\n res <- sapply(res,function(x) t(x[,apply(x,2,function(cc) !any(is.na(cc)))]),simplify=FALSE)\n tab0 <- lapply(names(res),function(nn){\n x <- res[[nn]]\n tau <- ifelse(grepl('tau0.2',nn,fixed=TRUE),0.2,0)\n apply(sapply(1:nrow(x),function(i) eachCase(x[i,],eff=tau),simplify='array'),\n 1:2,mean)\n })\n\n cond <- strsplit(names(res),'_')\n cond <- lapply(cond,function(x) gsub('err|tau','',x))\n cond <- lapply(cond,function(x) c(x[1],x[2],strsplit(x[3],'W')[[1]]))\n cond <- do.call('rbind',cond)\n out <- data.frame(tab0[[1]],stringsAsFactors=FALSE)\n out <- cbind(cond[rep(1,3),],c('Bias','Coverage','Width'),out)\n\n for(i in 2:length(tab0))\n out <- rbind(out,cbind(cond[rep(i,3),],\n c('Bias','Coverage','Width'),\n data.frame(tab0[[i]],stringsAsFactors=FALSE)))\n\n\n names(out) <- c('n','error','ATE','TE randomness','meas','Limitless','Local-OLS','Permutation')\n\n out\n}\n\n\n###########################################################################################\n### Table 4 simulation (polynomial)\n###########################################################################################\n\n\n#' @export\n## dgms <- function(tp){\n\n## ### the DGMs\n## curve(0.5*x,from=-1,to=1,ylim=c(-2,2),xlab='r',ylab='$\\\\EE[Y|R=r]$',main='Linear')\n## abline(v=0,lty=2)\n## curve(ifelse(abs(x)>0.5, 3*x+sign(x)*(0.5-3)*0.5,0.5*x),from=-1,to=1,ylim=c(-2,2),xlab='r',ylab='$\\\\EE[Y|R=r]$',main='Anti-Symmetric')\n## abline(v=0,lty=2)\n## #curve(ifelse(x>0.5,3*x+(0.5-3)*0.5,0.5*x),from=-1,to=1,ylim=c(-2,2),xlab='r',ylab='$\\\\EE[Y|R=r]$',main='One-Sided')\n## curve(mu4,from=-1,to=1,ylim=c(-2,2),xlab='r',ylab='$\\\\EE[Y|R=r]$',main='One-Sided')\n## abline(v=0,lty=2)\n## }\n\ndgms <- function(){\n lin <- function(x) 0.5*x\n as <- function(x) ifelse(abs(x)>0.5,3*x+sign(x)*(0.5-3)*0.5,lin(x))\n mu4 <- function(x) sin(3*x)\n p <- ggplot(data = data.frame(x = 0), mapping = aes(x = x))+xlim(-1,1)+\n theme(axis.line=element_blank(),\n axis.text.x=element_blank(),\n axis.text.y=element_blank(),\n axis.ticks=element_blank(),\n #axis.title.x='$r$',\n #axis.title.y='$\\\\EE[Y|R=r]$',\n legend.position=\"none\",\n ## panel.background=element_blank(),\n ## panel.border=element_blank(),\n ## panel.grid.major=element_blank(),\n ## panel.grid.minor=element_blank(),\n ## plot.background=element_blank()\n )+xlab('$r$')+ylab('$\\\\EE[Y|R=r]$')\n\n gridExtra::grid.arrange(p+stat_function(fun=lin)+ggtitle('Linear'),\n p+stat_function(fun=as)+ggtitle('Anti-Symmetric'),\n p+stat_function(fun=mu4)+ggtitle('Sine'),nrow=1)\n}\n\nresTab <- function(run,full=FALSE){\n llr <- run[c(nrow(run)-1,nrow(run)),]\n run <- run[-c(nrow(run)-1,nrow(run)),]\n\n pvals <- run[seq(1,nrow(run)-1,2),]\n ests <- run[seq(2,nrow(run),2),]\n\n runPsh <- pvals[seq(1,nrow(pvals),2),]\n runPik <- pvals[seq(2,nrow(pvals),2),]\n\n runEstsh <- ests[seq(1,nrow(ests),2),]\n runEstik <- ests[seq(2,nrow(ests),2),]\n\n\n tabFun <- function(runP,runEst,full){\n tab <- rbind(\n level=apply(runP,1,function(x) mean(x<0.05,na.rm=TRUE)),\n RMSE=apply(runEst,1,function(x) sqrt(mean(x^2,na.rm=TRUE))))\n if(full) tab <- rbind(tab,\n bias=rowMeans(runEst,na.rm=TRUE),\n sd=apply(runEst,1,sd,na.rm=TRUE))\n tab\n }\n list(tabSH=tabFun(runPsh,runEstsh,full=full),\n tabIK=tabFun(runPik,runEstik,full=full),\n tabLLR=tabFun(rbind(llr[1,]),rbind(llr[2,]),full=full))\n}\n\n\nresTab <- function(run,full=FALSE){\n run <- run[,apply(run,2,function(x) !any(is.na(x)))]\n tabFun <- function(ests)\n rbind(\n bias=rowMeans(rbind(ests)),\n RMSE=sqrt(rowMeans(rbind(ests^2))))\n\n tabFunP <- function(ps)\n apply(rbind(ps),1,function(x) mean(x<0.05,na.rm=TRUE))\n\n\n out <- sapply(c('sh','ik','ll'),function(mm) tabFun(run[grep(paste0(mm,'.est'),rownames(run)),]),\n simplify=FALSE)\n\n if(full) out <- sapply(c('sh','ik','ll'),\n function(mm) rbind(out[[mm]],level= tabFunP(run[grep(paste0(mm,'.p'),rownames(run)),])),\n simplify=FALSE)\n\n out\n}\n\n#' @export\nprntTab <- function(totalPoly,maxDeg=4,full=TRUE,md=FALSE){\n tab <- NULL\n\n if(maxDeg>(nrow(totalPoly[[1]])-2)/4){\n maxDeg <- (nrow(totalPoly[[1]])-2)/4\n if(!full)\n warning(paste('There don\\'t seem to be that many degrees in the simulation.\\n Setting maxDeg=',maxDeg))\n }\n\n ctab <- function(runname,full){\n run <- totalPoly[[runname]]\n res <- resTab(run,full=full)\n\n cbind(res[['sh']][,1:maxDeg],\n res[['ik']][,1:maxDeg],\n res[['ll']])\n }\n for(dgm in c('lin','antiSym','wass')){\n tab <- rbind(tab,ctab(paste0(dgm,'_t'),full))\n if(full) if(paste0(dgm,'_norm')%in%names(totalPoly)) tab <- rbind(tab,ctab(paste0(dgm,'_norm'),full))\n }\n if(md){\n colnames(tab) <- c(paste('LRD, deg=',1:maxDeg),paste('OLS, deg=',1:maxDeg),'Loc.Lin')\n rownames(tab) <- paste(rep(c('lin','antiSym','sine'),\n each=nrow(tab)/sum(rownames(tab)=='bias')),#,times=2),\n #rep(c('t err','norm err'),each=nrow(tab)/2),\n rownames(tab))\n }\n return(tab)\n}\n\n#' @export\npolyLatex <- function(tab,full,caption='',label='tab:poly'){\n if(NCOL(tab)!=9) stop('This only works with polynomial degree=1,...,4')\n cat('\n \\\\begin{table}[ht]\n\\\\centering\n\\\\begin{tabular}{cr|llll|llll|l',ifelse(full,'|llll|llll|l}','}'),'\n \\\\hline \\n')\n if(full) cat('&&\\\\multicolumn{9}{c|}{$t_3$ Errors} &\\\\multicolumn{9}{c|}{$\\\\mathcal{N}(0,1)$ Errors} \\\\\\\\ \\n')\n\n cat('&& \\\\multicolumn{4}{c|}{Limitless} & \\\\multicolumn{4}{c|}{OLS} &\\\\makecell[c]{Local\\\\\\\\Linear}',\n ifelse(full,'\\\\multicolumn{4}{c|}{Limitless} & \\\\multicolumn{4}{c|}{OLS} &\\\\makecell[c]{Local\\\\\\\\Linear}',''),'\\\\\\\\\n \\\\multicolumn{2}{r|}{\\\\makecell[r]{Polynomial\\\\\\\\Degree}}&1&2&3&4&1&2&3&4&',ifelse(full,'&1&2&3&4&1&2&3&4&n/a','n/a'),' \\\\\\\\\n')\n for(rr in 1:nrow(tab)){\n if(rr==1) cat('\\\\hline\\n\\\\hline\\n\\\\multirow{',ifelse(full,4,2),'}{*}{',ifelse(full,'\\\\begin{sideways}Linear\\\\end{sideways}','Linear'),'}')\n if(rr==3) cat('\\\\hline\\n\\\\hline\\n\\\\multirow{',ifelse(full,4,2),'}{*}{',ifelse(full,'\\\\begin{sideways}Anti-Sym\\\\end{sideways}','Anti-Sym'),'}')\n if(rr==5) cat('\\\\hline\\n\\\\hline\\n\\\\multirow{',ifelse(full,4,2),'}{*}{',ifelse(full,'\\\\begin{sideways}One-Side\\\\end{sideways}','One-Side'),'}')\n cat('&',rownames(tab)[rr],'&')\n cat(paste(sprintf(\"%.1f\", round(tab[rr,],1)),collapse='&'))\n cat('\\\\\\\\ \\n')\n }\n cat('\n \\\\hline\n\\\\end{tabular}\n\\\\caption{',caption,'}\n\\\\label{',label,'}\n\\\\end{table}\\n',sep='')\n\n}\n\n#' @export\npolyLatex5 <- function(tab,full,caption='',label='tab:poly'){\n if(NCOL(tab)!=11) stop('This only works with polynomial degree=1,...,5')\n tab2 <- tab\n for(i in 1:nrow(tab)) for(j in 1:ncol(tab))\n tab2[i,j] <- ifelse(tab[i,j]>10,\n sprintf(\"%i\",as.integer(round(tab[i,j]))),\n sprintf(\"%.1f\",round(tab[i,j],1)))\n\n cat('\n \\\\begin{table}[ht]\n\\\\centering\n\\\\begin{tabular}{ll|ccccc|ccccc|c',ifelse(full,'|llll|llll|l}','}'),'\n \\\\hline \\n')\n if(full) cat('&&\\\\multicolumn{11}{c|}{$t_3$ Errors} &\\\\multicolumn{11}{c|}{$\\\\mathcal{N}(0,1)$ Errors} \\\\\\\\ \\n')\n\n cat('&& \\\\multicolumn{5}{c|}{Limitless} & \\\\multicolumn{5}{c|}{OLS} &Local',\n ifelse(full,'\\\\multicolumn{5}{c|}{Limitless} & \\\\multicolumn{5}{c|}{OLS} &Local',''),'\\\\\\\\\n && \\\\multicolumn{5}{c|}{Polynomial Degree}&\\\\multicolumn{5}{c|}{Polynomial Degree}&Linear',\n ifelse(full,'\\\\multicolumn{5}{c|}{Polynomial Degree}&\\\\multicolumn{5}{c|}{Polynomial Degree}&Linear',''),'\\\\\\\\\n DGM&Measure&1&2&3&4&5&1&2&3&4&5&',ifelse(full,'&1&2&3&4&1&2&3&4&5&',''),' \\\\\\\\\n')\n for(rr in 1:nrow(tab)){\n if(rr==1) cat('\\\\hline\\n\\\\hline\\n\\\\multirow{',ifelse(full,4,2),'}{*}{',ifelse(full,'\\\\begin{sideways}Linear\\\\end{sideways}','Linear'),'}',sep='')\n if(rr==3) cat('\\\\hline\\n\\\\hline\\n\\\\multirow{',ifelse(full,4,2),'}{*}{',ifelse(full,'\\\\begin{sideways}Anti-Sym\\\\end{sideways}','\\\\makecell[c]{Anti-\\\\\\\\Sym}'),'}',sep='')\n if(rr==5) cat('\\\\hline\\n\\\\hline\\n\\\\multirow{',ifelse(full,4,2),'}{*}{',ifelse(full,'\\\\begin{sideways}One-Side\\\\end{sideways}','Sine'),'}',sep='')\n cat('&',rownames(tab)[rr],'&')\n cat(paste(tab2[rr,],collapse='&'))\n cat('\\\\\\\\ \\n')\n }\n cat('\n \\\\hline\n\\\\end{tabular}\n\\\\caption{',caption,'}\n\\\\label{',label,'}\n\\\\end{table}\\n',sep='')\n\n}\n\n\n", "meta": {"hexsha": "955d5051ad4ebe5a74ae4fb58d70ffb03de2f3b3", "size": 11404, "ext": "r", "lang": "R", "max_stars_repo_path": "R/displaySim.r", "max_stars_repo_name": "adamSales/lrd", "max_stars_repo_head_hexsha": "dcf9637cce7afe241a35f118718533be55c3bd26", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/displaySim.r", "max_issues_repo_name": "adamSales/lrd", "max_issues_repo_head_hexsha": "dcf9637cce7afe241a35f118718533be55c3bd26", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/displaySim.r", "max_forks_repo_name": "adamSales/lrd", "max_forks_repo_head_hexsha": "dcf9637cce7afe241a35f118718533be55c3bd26", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2018-05-07T15:07:54.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-30T19:06:03.000Z", "avg_line_length": 37.761589404, "max_line_length": 176, "alphanum_fraction": 0.5268326903, "num_tokens": 3836, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5964331462646254, "lm_q2_score": 0.5926665999540698, "lm_q1q2_score": 0.35348600489656395}} {"text": "=begin\n= Changes\n== 0.71(2005.07.26)\n* MPolynomial#derivate\n* MPolynomial#map_to\n\n== 0.70(2005.02.02)\n* id => object_id\n\n== 0.69(2004.10.15)\n* MRationalFunctionField\n* MPolynomial#gcd\n* SquareMatrix#inverse depends on ufd?\n\n== 0.68(2004.07.28)\n* fix Mpolynomial#to_s (for tex)\n\n== 0.67(2004.06.10)\n* need_paren_in_coeff?\n* Matrix: entries are regulated.\n* Matrix: type*type is due to wedge.\n* AlgebraicSystem: wedge, superior?\n* Polynomial#sub, MPolynomial#sub\n* SquareMatrix.determinant\n* fix MPolynomial#to_s\n* fix Factors#normalize!\n* (Co)Vector#norm2, inner_product\n\n== 0.66(2004.06.05)\n* fix _hensel_lift (add param 'where')\n* sample-geometry01.rb\n* title of docs\n\n== 0.65(2004.06.04)\n* Polynomial#factor over Polynomial\n* reverse var's order in value_on & convert_to in polynomial-convert.rb\n\n== 0.64(2004.03.01)\n* return value of SquareMatrix#diagonalize is Strut\n\n== 0.63(2004.01.08)\n* fix matrix[i, j] = x\n\n== 0.62(2003.11.13)\n* allow f.gcd_coeff_all()\n\n== 0.61(2003.11.06)\n* corrected Enumerable#any? in finite-set.rb\n\n== 0.60(2003.07.28)\n* AlgebraMatrix(cofactor, cofactor_matrix, adjoint)\n\n== 0.59(2003.07.28)\n* adapted to the version 1.8.0(preview 4)\n* include installer\n\n== 0.58(2002.04.00)\n* AlgebraicExtensionField#[n] is lift[n]\n* abolish the field of 'poly_exps' of the splitting field' and add 'proots'\n* MatrixAlgebra#rank\n* Raise Exception for the inverse of the non invertible square matrix\n* Use \"import-module\" for monomial order (0.57.18.01)\n\n== 0.57 (2002.03.16)\n* New class\n * Set\n * Map\n * Group\n * PermuationGroup\n * AlgebraicExtensionField\n* New methods\n * Galois#group\n * Polynomial#splitting_field\n* Rename MinimalDecompositionField to decompose\n* Move *.rb to lib/\n* Define Polynomial.to_ary and MPolynomial.to_ary\n\n== 0.56 (2002.02.06)\n* MPolynomial#with_ord\n* Orderings belong to MPolynomial.\n* MIndex is not a subclass of Array, now.\n* \"Integer < Numeric\" ==> \"Integer\"\n\n== 0.55 (2001.11.15)\n* Improve Algorithm of Factorization over algebraic fields\n\n== 0.54 (2001.11.05)\n* Elementary Divisor\n* Jordan Form\n* Minimal Decomposition Field\n\n== 0.53 (2001.10.03)\n\n* move \"MatrixAlgebra\" to \"Algebra::MatrixAlgebra\"\n* move \"MatrixAlgebra::Vector\" to \"Algebra::Vector\"\n* move \"MatrixAlgebra::Covector\" to \"Algebra::Covector\",\n* move \"MatrixAlgebra::SquareMatrix\" to \"Algebra::SquareMatrix\"\n\n== 0.52 (2001.09.22)\n\n* One-variate polynomial\n * Fundamental operations (addition, multiplication, quotient/remainder, ...)\n * factorization\n* Multi-variate polynomial\n * Fundamental operations (addition, multiplication, ...)\n * factorization\n * Creating Groebner-basis, quotient/remainder by Groebner-basis.\n* Algebraic systems\n * Creating quotient fields\n * Creating residue class fields\n * Operating matrices.\n* Linear Algebra\n * Diagonalization of Symmetrix Matrix\n\n== 0.40 (2001.03.03)\n\n* Initial Version\n\n=end\n", "meta": {"hexsha": "7976612379a332892c2ba0478a446099d0b20674", "size": 2855, "ext": "rd", "lang": "R", "max_stars_repo_path": "doc-ja/changes.rd", "max_stars_repo_name": "kunishi/algebra-ruby2", "max_stars_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 6, "max_stars_repo_stars_event_min_datetime": "2015-04-25T17:00:02.000Z", "max_stars_repo_stars_event_max_datetime": "2021-07-08T02:59:44.000Z", "max_issues_repo_path": "work/consider/algebra-0.72/doc/changes.rd", "max_issues_repo_name": "rubyworks/stick", "max_issues_repo_head_hexsha": "7e89d1a1ade1db085ddfecf19f774f0ba9bc2b70", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2017-03-10T14:02:43.000Z", "max_issues_repo_issues_event_max_datetime": "2017-03-10T14:02:43.000Z", "max_forks_repo_path": "doc/changes.rd", "max_forks_repo_name": "kunishi/algebra-ruby2", "max_forks_repo_head_hexsha": "ab8e3dce503bf59477b18bfc93d7cdf103507037", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 23.7916666667, "max_line_length": 78, "alphanum_fraction": 0.7243432574, "num_tokens": 929, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.5544704796847396, "lm_q2_score": 0.6370307944803831, "lm_q1q2_score": 0.3532147701894888}} {"text": "#' ---\n#' title: \"Prior probabilities in the interpretation of 'some': analysis of uniform prior wonky world model predictions\"\n#' author: \"Judith Degen\"\n#' date: \"January 26, 2014\"\n#' ---\n\nlibrary(ggplot2)\ntheme_set(theme_bw(18))\nsetwd(\"/Users/titlis/cogsci/conferences_talks/_2015/5_berkeley/\")\nsource(\"rscripts/helpers.r\")\n\n# get prior expectations\npriorexpectations = read.table(file=\"~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/experiments/12_sinking-marbles-prior15/results/data/expectations.txt\",sep=\"\\t\", header=T, quote=\"\")\nrow.names(priorexpectations) = paste(priorexpectations$effect, priorexpectations$object)\n\n# histogram of expectations\nexps = ggplot(priorexpectations, aes(x=expectation_corr)) +\n geom_histogram() +\n scale_x_continuous(name=\"Expected value of prior distribution\",breaks=seq(1,15, by=2)) +\n scale_y_continuous(name=\"Number of cases\",breaks=seq(0,8, by=2))\nggsave(\"priorexpectations-histogram.pdf\",width=5,height=3.7)\n\n\n# get prior allstate-probs\npriorprobs = read.table(file=\"~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/experiments/12_sinking-marbles-prior15/results/data/smoothed_15marbles_priors_withnames.txt\",sep=\"\\t\", header=T, quote=\"\")\nrow.names(priorprobs) = priorprobs$Item\nhead(priorprobs)\n\n# histogram of allstate-probs\nallprobs = ggplot(priorprobs, aes(x=X15)) +\n geom_histogram() +\n scale_x_continuous(name=\"Prior all-state probability\") +\n scale_y_continuous(name=\"Number of cases\")\nggsave(\"priorallprobs-histogram.pdf\")\n\npdf(\"priordistributions.pdf\",width=10,height=4)\ngrid.arrange(exps, allprobs, nrow=1,widths=unit.c(unit(.5, \"npc\"), unit(.5, \"npc\")))\ndev.off()\n\n#####################################\n# plot model predictions: expectations\nload(\"~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/models/wonky_world/results/data/mp-uniform.RData\")\n\n\nlibrary(dplyr)\nlibrary(plyr)\n# plot expectations for best basic model: \ntoplot = droplevels(subset(mp, Quantifier == \"some\" & WonkyWorldPrior == .5))\nnrow(toplot)\npexpectations = ddply(toplot, .(Item), summarise, PosteriorExpectation_predicted=sum(State*PosteriorProbability)/15)\nhead(pexpectations)\nsome = pexpectations#droplevels(subset(pexpectations, Quantifier == \"some\"))\n\ntoplot = some\nnrow(toplot)\nhead(toplot)\ntoplot$Mode = priormodes[as.character(toplot$Item),]$Mode\n\nggplot(toplot, aes(x=PriorExpectation_smoothed, y=PosteriorExpectation_predicted)) +\n geom_point(color=\"#00B0F6\") + #values=c(\"#F8766D\", \"#A3A500\", \"#00BF7D\", \"#E76BF3\", \"#00B0F6\")\n geom_smooth(color=\"#00B0F6\") +\n # geom_abline(intercept=0,slope=1,color=\"gray50\") +\n scale_x_continuous(limits=c(0,1), name=\"Prior expectation\") +\n scale_y_continuous(limits=c(0,1), name=\"Model predicted posterior expectation\")\n\n\n\nload(\"~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/models/wonky_world/results/data/mp-uniform.RData\")\n\n# plot expectations for best basic model: \ntoplot = droplevels(subset(mp, Quantifier == \"some\" & WonkyWorldPrior == .5 & State == 15))\nnrow(toplot)\n\n# adjust speaker optimality at will\ntoplot = droplevels(subset(toplot, SpeakerOptimality == 2))\nnrow(toplot)\nhead(toplot)\n\ntoplot_w = toplot\n# get rRSA predictions for qud=how-many, alts=0_basic, spopt=2\nload(\"~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/models/complex_prior/smoothed_unbinned15/results/data/mp.RData\")\nsummary(mp)\ntoplot = droplevels(subset(mp, QUD == \"how-many\" & Alternatives == \"0_basic\" & State == 15))\nnrow(toplot)\n\n# adjust speaker optimality at will\ntoplot = droplevels(subset(toplot, SpeakerOptimality == 2))\nnrow(toplot)\nhead(toplot)\n\ntoplot_r = toplot\ntoplot_r$Model = \"RSA\"\ntoplot_w$Model = \"wRSA\"\n\n# plot both rRSA and uniform wRSA expectation predictions in same plot\ntoplot = merge(toplot_r,toplot_w, all=T)\nhead(toplot)\nnrow(toplot)\np_probs = ggplot(toplot, aes(x=PriorProbability, y=PosteriorProbability, color=Model)) +\n geom_point() + #color=\"#00B0F6\") + #values=c(\"#F8766D\", \"#A3A500\", \"#00BF7D\", \"#E76BF3\", \"#00B0F6\")\n geom_smooth() + #color=\"#00B0F6\") +\n scale_color_manual(values=c(\"darkred\",wes_palette(\"Darjeeling\")[1])) +\n # geom_abline(intercept=0,slope=1,color=\"gray50\") +\n scale_x_continuous(limits=c(0,1), name=\"Prior mean all-state probability\") +\n scale_y_continuous(limits=c(0,1), name=\"Predicted posterior all-state probability\") \np_probs\nggsave(\"pred_probs.pdf\")\n\np_probs = ggplot(toplot_r, aes(x=PriorProbability, y=PosteriorProbability, color=Model)) +\n geom_point() + #color=\"#00B0F6\") + #values=c(\"#F8766D\", \"#A3A500\", \"#00BF7D\", \"#E76BF3\", \"#00B0F6\")\n geom_smooth() + #color=\"#00B0F6\") +\n scale_color_manual(values=c(\"darkred\")) +\n # geom_abline(intercept=0,slope=1,color=\"gray50\") +\n scale_x_continuous(limits=c(0,1), name=\"Prior all-state probability\") +\n scale_y_continuous(limits=c(0,1), name=\"Posterior all-state probability\") \np_probs\nggsave(\"pred_prob_rsa.pdf\")\n\n\n# plot model predictions: expectations\nload(\"~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/models/wonky_world/results/data/mp-uniform.RData\")\n\n\n# plot expectations for best basic model: \ntoplot = droplevels(subset(mp, Quantifier == \"some\" & WonkyWorldPrior == .5))\nnrow(toplot)\n\npexpectations = ddply(toplot, .(Item, SpeakerOptimality,PriorExpectation), summarise, PosteriorExpectation_predicted=sum(State*PosteriorProbability)/15)\nhead(pexpectations)\nsome = pexpectations#droplevels(subset(pexpectations, Quantifier == \"some\"))\n\ntoplot = droplevels(subset(some, SpeakerOptimality == 2))\nnrow(toplot)\nhead(toplot)\ntoplot_w = toplot\n\n# get rRSA predictions for qud=how-many, alts=0_basic, spopt=2\nload(\"~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/models/complex_prior/smoothed_unbinned15/results/data/toplot-expectations.RData\")\ntoplot_r = toplot\nhead(toplot_w)\nsummary(toplot_r)\ntoplot_r$Model = \"RSA\"\ntoplot_r$PriorExpectation = toplot_r$PriorExpectation_smoothed*15\ntoplot_w$Model = \"wRSA\"\n\n# plot both rRSA and uniform wRSA expectation predictions in same plot\ntoplot = merge(toplot_r,toplot_w, all=T)\nhead(toplot)\nnrow(toplot)\n\np_exps = ggplot(toplot, aes(x=PriorExpectation, y=PosteriorExpectation_predicted*15, color=Model)) +\n geom_point() + #color=\"#00B0F6\") + #values=c(\"#F8766D\", \"#A3A500\", \"#00BF7D\", \"#E76BF3\", \"#00B0F6\")\n geom_smooth() + #color=\"#00B0F6\") +\n scale_color_manual(values=c(\"darkred\",wes_palette(\"Darjeeling\")[1])) +#values=c(\"#007fb1\", \"#4ecdff\")) +\n # geom_abline(intercept=0,slope=1,color=\"gray50\") +\n scale_x_continuous(limits=c(0,15), breaks=seq(1,15,by=2), name=\"Prior mean number of objects\") +\n scale_y_continuous(limits=c(0,15), breaks=seq(1,15,by=2), name=\"Predicted posterior number of objects\") \np_exps\nggsave(\"pred_exps.pdf\")\n\np_exps = ggplot(toplot_r, aes(x=PriorExpectation, y=PosteriorExpectation_predicted*15, color=Model)) +\n geom_point() + #color=\"#00B0F6\") + #values=c(\"#F8766D\", \"#A3A500\", \"#00BF7D\", \"#E76BF3\", \"#00B0F6\")\n geom_smooth() + #color=\"#00B0F6\") +\n scale_color_manual(values=c(\"darkred\")) +#values=c(\"#007fb1\", \"#4ecdff\")) +\n # geom_abline(intercept=0,slope=1,color=\"gray50\") +\n scale_x_continuous(limits=c(0,15), breaks=seq(1,15,by=2), name=\"Prior expectation\") +\n scale_y_continuous(limits=c(0,15), breaks=seq(1,15,by=2), name=\"Posterior expectation\") \np_exps\nggsave(\"pred_exps_rsa.pdf\")\n\nlibrary(gridExtra)\n# share a legend between multiple plots\ng <- ggplotGrob(p_exps + theme(legend.position=\"right\"))$grobs\nlegend <- g[[which(sapply(g, function(x) x$name) == \"guide-box\")]]\np_exps_nolegend = p_exps + theme(legend.position=\"none\")\np_probs_nolegend = p_probs + theme(legend.position=\"none\")\n\npdf(\"rsa-predictions.pdf\",width=12,height=4.9)\ngrid.arrange(p_exps_nolegend, p_probs_nolegend, legend,nrow=1,widths=unit.c(unit(.45, \"npc\"), unit(.45, \"npc\"), unit(.1, \"npc\")))\ndev.off()\n\n\n# expectations\nload(\"~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/experiments/13_sinking-marbles-priordv-15/results/data/r.RData\")\n\nagr = aggregate(ProportionResponse ~ PriorExpectationProportion + quantifier + Item,data=r,FUN=mean)\n\nmin(agr[agr$quantifier == \"Some\",]$ProportionResponse)\nmax(agr[agr$quantifier == \"Some\",]$ProportionResponse)\nagr$Quantifier = factor(x=agr$quantifier, levels=c(\"Some\",\"All\",\"None\",\"long_filler\",\"short_filler\"))\n\np_eexps = ggplot(agr, aes(x=PriorExpectationProportion*15, y=ProportionResponse*15, color=Quantifier, shape=Quantifier)) +\n geom_point() +\n #geom_errorbar(aes(ymin=YMin,ymax=YMax)) +\n geom_smooth(method=\"lm\") +\n scale_color_manual(values=c(wes_palette(\"Darjeeling\")[1:3],\"black\",\"gray40\")) +#values=c(\"#F8766D\", \"black\", \"#00BF7D\", \"gray30\", \"#00B0F6\"),breaks=levels(agr$quantifier),labels=c(\"all\",\"long filler\",\"none\",\"short filler\",\"some\")) +\n scale_y_continuous(breaks=seq(1,15,by=2),name=\"Posterior mean number of objects\") +\n # geom_abline(intercept=0,slope=1,color=\"gray70\") +\n scale_x_continuous(breaks=seq(1,15,by=2),name=\"Prior mean number of objects\") \np_eexps\nggsave(file=\"empirical_exps.pdf\")#,width=5,height=3.7)\n\n\n# allstate-probs\nload(\"~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/experiments/16_sinking-marbles-sliders-certain/results/data/r.RData\")\n\n# exclude people who are doing some sort of bullshit and not responding reasonably to all/none (see subject-variability.pdf for behavior on zero-slider)\ntmp = subset(r,!workerid %in% c(0,22,43,98,100,103,117,118))\nagrr = aggregate(normresponse ~ AllPriorProbability + Proportion + quantifier + Item,data=tmp,FUN=mean)\nagrr = aggregate(normresponse ~ AllPriorProbability + Proportion + quantifier + Item,data=r,FUN=mean)\nub = subset(agrr, Proportion == \"100\")\nub = droplevels(ub)\nub$Quantifier = factor(x=ub$quantifier, levels=c(\"Some\",\"All\",\"None\",\"long_filler\",\"short_filler\"))\n\np_eprobs = ggplot(ub, aes(x=AllPriorProbability, y = normresponse, color=Quantifier, shape=Quantifier)) +\n geom_point() +\n geom_smooth(method=\"lm\") +\n scale_color_manual(values=c(wes_palette(\"Darjeeling\")[1:3],\"black\",\"gray40\")) +#values=c(\"#F8766D\", \"black\", \"#00BF7D\", \"gray30\", \"#00B0F6\"),breaks=levels(agr$quantifier),labels=c(\"all\",\"long filler\",\"none\",\"short filler\",\"some\")) +\n scale_y_continuous(limits=c(0,1),name=\"Posterior probability of all-state \") +\n # geom_abline(intercept=0,slope=1,color=\"gray70\") +\n scale_x_continuous(limits=c(0,1),name=\"Prior probability of all-state\") \np_eprobs\nggsave(file=\"empirical-allprobs.pdf\")#,width=5,height=3.7)\n\nlibrary(gridExtra)\n# share a legend between multiple plots\ng <- ggplotGrob(p_eexps + theme(legend.position=\"right\"))$grobs\nlegend <- g[[which(sapply(g, function(x) x$name) == \"guide-box\")]]\np_eexps_nolegend = p_eexps + theme(legend.position=\"none\")\np_eprobs_nolegend = p_eprobs + theme(legend.position=\"none\")\n\npdf(\"empirical-results.pdf\",width=12,height=4.9)\ngrid.arrange(p_eexps_nolegend, p_eprobs_nolegend, legend,nrow=1,widths=unit.c(unit(.45, \"npc\"), unit(.45, \"npc\"), unit(.1, \"npc\")))\ndev.off()\n\n\nload(\"~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/models/wonky_world/results/data/wr-uniform.RData\")\n\n# plot expectations for best basic model: \ntoplot = droplevels(subset(wr, WonkyWorldPrior == .5 & Wonky == \"true\"))\nnrow(toplot)\ntoplot$Mode = priormodes[as.character(toplot$Item),]$Mode\n\ntoplot = droplevels(subset(toplot, SpeakerOptimality == 2))\nnrow(toplot)\nhead(toplot)\n#toplot$quantifier = capitalize(as.character(toplot$Quantifier))\ntoplot$Quantifier = factor(toplot$Quantifier, levels=c(\"some\",\"all\",\"none\"))\n\np_wmodel = ggplot(toplot, aes(x=PriorExpectation, y=PosteriorProbability,color=Quantifier,shape=Quantifier)) +\n geom_point() + \n geom_smooth() + \n scale_color_manual(values=c(wes_palette(\"Darjeeling\")[1:3],\"black\",\"gray40\")) + \n #scale_color_manual(values=c(\"#F8766D\",\"#00BF7D\",\"#00B0F6\")) +\n scale_x_continuous(breaks=seq(1,15,by=2),name=\"Prior mean number of objects\") +\n scale_y_continuous(breaks=seq(0,1,by=.25),name=\"Predicted posterior wonkiness probability\") +\n theme(plot.margin=unit(c(0,0,0,0),units=\"cm\")) \np_wmodel\nggsave(\"model-wonkiness-uniform.pdf\",width=6.8,height=5)#,width=30,height=10)\n\n############\n# empirical wonkiness posteriors\n############\nload(\"/Users/titlis/cogsci/projects/stanford/projects/thegricean_sinking-marbles/experiments/17_sinking-marbles-normal-sliders/results/data/r.RData\")\nhead(r)\nnrow(r)\n\ntoplot = aggregate(response ~ quantifier + Item + PriorExpectation, FUN=\"mean\", data=r)\ntoplot = droplevels(subset(toplot, quantifier %in% c(\"All\",\"Some\",\"None\")))\ntoplot$Quantifier = factor(tolower(toplot$quantifier), levels=c(\"all\", \"none\",\"some\"))\ntoplot$Mode = priormodes[as.character(toplot$Item),]$Mode\ntoplot$quantifier = capitalize(as.character(toplot$Quantifier))\ntoplot$Quantifier = factor(toplot$quantifier, levels=c(\"Some\",\"All\",\"None\"))\n\np_wempirical = ggplot(toplot, aes(x=PriorExpectation, y=response, color=Quantifier,shape=Quantifier)) +\n geom_point() +\n geom_smooth() +\n scale_color_manual(values=c(wes_palette(\"Darjeeling\")[1:3],\"black\",\"gray40\")) + \n scale_x_continuous(breaks=seq(1,15,by=2),name=\"Prior mean number of objects\") +\n scale_y_continuous(breaks=seq(0,1,by=.25),name=\"Mean empirical wonkiness probability\") +\n theme(plot.margin=unit(c(0,0,0,0),units=\"cm\")) \np_wempirical\nggsave(file=\"empirical-wonkiness.pdf\",width=6.8,height=5)\n\n\nlibrary(gridExtra)\n# share a legend between multiple plots\ng <- ggplotGrob(p_wmodel + theme(legend.position=\"right\"))$grobs\nlegend <- g[[which(sapply(g, function(x) x$name) == \"guide-box\")]]\np_wmodel_nolegend = p_wmodel + theme(legend.position=\"none\")\np_wempirical_nolegend = p_wempirical + theme(legend.position=\"none\")\n\n#pdf(\"rsa-predictions-uniform.pdf\",width=10,height=4)\npdf(\"wonkiness-fullplot.pdf\",width=12,height=5)\ngrid.arrange(p_wmodel_nolegend, p_wempirical_nolegend, legend,nrow=1,widths=unit.c(unit(.45, \"npc\"), unit(.45, \"npc\"), unit(.1, \"npc\")))\ndev.off()\n", "meta": {"hexsha": "239d4e0eac89e72803fe0b7a9f25bcba261fb745", "size": 13812, "ext": "r", "lang": "R", "max_stars_repo_path": "writing/_2015/cogsci_2015/talk/rscripts/plots.r", "max_stars_repo_name": "thegricean/sinking-marbles", "max_stars_repo_head_hexsha": "ccfb17f097b444306e3b559e40ab9d59da84387a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "writing/_2015/cogsci_2015/talk/rscripts/plots.r", "max_issues_repo_name": "thegricean/sinking-marbles", "max_issues_repo_head_hexsha": "ccfb17f097b444306e3b559e40ab9d59da84387a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "writing/_2015/cogsci_2015/talk/rscripts/plots.r", "max_forks_repo_name": "thegricean/sinking-marbles", "max_forks_repo_head_hexsha": "ccfb17f097b444306e3b559e40ab9d59da84387a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.5050505051, "max_line_length": 234, "alphanum_fraction": 0.7430495222, "num_tokens": 4249, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6370308082623216, "lm_q2_score": 0.5544704649604273, "lm_q1q2_score": 0.35321476845132627}} {"text": "# Xiaofeng Xu created this file in May 2020, and updated in Sep 2020, and finalized with 14C on Nov 11 2020\nlibrary(\"RNetCDF\")\nlibrary(\"akima\")\nrm(list=ls())\nsetwd(\"/Users/xxuadmin/BUSINESS/PUBLICATIONS/WorkingOn_Xu_Isotope/SPRUCE_2020Sep\")\n# 13C is based on the PD standard Pee Dee Belemnite (PDB). 13C:12C = 0.0112372.\n# 13C/12C(sample) / 13C/12C(standard - 1)\n# 13C = (delta / 1000 + 1) * 0.0112372 * 12C\n\n# for the spruce site, the 14C = 12C * ((1 + delta14C / 1000) * (1.176e-12/((1+delta13C)*(1+delta13C)/(1-0.025)/(1-0.025)))\n# the 13Cdealta is -25 per mil for standard sample; this is for SPRUCE site based on the data from Erik Hobbie at UNH\n\ndata <- read.csv(\"Peat_Characteristics_T0_20180425_plot.csv\", header=TRUE)\nO13C <- data[1:16,3:4]\nO14C <- data[1:16,5]\n#depth 25, 15, 5, -5, -25, -35, -45, -55, -65, -85, -113, -163, -188, -225, -255\n#CLM depth 0.71, 2.8, 6.2, 11.9, 21.2, 36.6, 61.97, 103.8, 172.8, 286.5, 473.9, 782.97, 1292.5, 2132.6, 3517.8 \n\ndepth <- c(0.0071, 0.0028, 0.0623, 0.1189, 0.2122, 0.366, 0.6197, 1.038, 1.72, 2.86)\n\n#Hommock\n#25 for layer 1, 2, 3\n#15 for layer 4\n# 5 for layer 5, \n#-5 for layer 6,\n#-25, -35, -45 for layer 7\n#-55, -65, and -85 for layer 8\n# -113, -163, and -188 for layer 9\n# -255 for layer 10 2.86\n\n#Hollow\n#-5 for layer 1, 2, 3\n# -15 for layer 4, \n#-25 for layer 5,\n#-35 for layer 6\n#-45 -55, and -65 for layer 7 0.6197\n#-85 and -133 for layer 8 1.038\n# -163 and -188 for layer 9 1.72\n# -225 and -275 for layer 10 2.86\nSO13C = array(0, dim=c(15,2))\n#L13C = O13C[3,1]\nSO13C[1,1] = O13C[1,1]\nSO13C[2,1] = O13C[1,1]\nSO13C[3,1] = O13C[1,1]\nSO13C[4,1] = O13C[2,1]\nSO13C[5,1] = O13C[3,1]\nSO13C[6,1] = O13C[4,1]\nSO13C[7,1] = mean(O13C[5:7,1])\nSO13C[8,1] = mean(O13C[8:10,1])\nSO13C[9,1] = mean(O13C[11:13,1])\nSO13C[10,1] = mean(O13C[14:15,1])\n\nSO13C[1,2] = mean(O13C[3:4,1])\nSO13C[2,2] = mean(O13C[3:4,1])\nSO13C[3,2] = mean(O13C[3:4,1])\nSO13C[4,2] = mean(O13C[4:5,1])\nSO13C[5,2] = mean(O13C[6:7,1])\nSO13C[6,2] = mean(O13C[8:9,1])\nSO13C[7,2] = mean(O13C[8:9,1])\nSO13C[8,2] = mean(O13C[10:11,1])\nSO13C[9,2] = mean(O13C[12:13,1])\nSO13C[10,2] = mean(O13C[14:16,1])\n\n#plot(SO13C[1:10,1],-depth,type=\"l\",xlab=\"soil 13CH4 (mmol/L)\", ylab=\"soil depth (m)\",cex=1,las=1, cex.lab = 1.5, cex.axis = 1.5,lwd=2)\n\nSO14C = array(0, dim=c(15,2))\nSO14C[1,1] = O14C[1]\nSO14C[2,1] = O14C[1]\nSO14C[3,1] = O14C[1]\nSO14C[4,1] = O14C[2]\nSO14C[5,1] = O14C[3]\nSO14C[6,1] = O14C[4]\nSO14C[7,1] = mean(O14C[5:7])\nSO14C[8,1] = mean(O14C[8:10])\nSO14C[9,1] = mean(O14C[11:13])\nSO14C[10,1] = mean(O14C[14:15])\n\nSO14C[1,2] = O14C[4]\nSO14C[2,2] = O14C[4]\nSO14C[3,2] = O14C[4]\nSO14C[4,2] = O14C[5]\nSO14C[5,2] = O14C[6]\nSO14C[6,2] = mean(O14C[7:9])\nSO14C[7,2] = mean(O14C[7:9])\nSO14C[8,2] = mean(O14C[10:11])\nSO14C[9,2] = mean(O14C[12:13])\nSO14C[10,2] = mean(O14C[14:16])\n\n#13C_ave\tDepth_ave\n#-29.058\t25\n#-28.34\t15\n#-28.1075\t5\n#-28.77631579\t-5\n#-27.79684211\t-15\n#-27.006\t-25\n#-26.72888889\t-35\n#-26.45055556\t-45\n#-26.60555556\t-55\n#-26.36611111\t-65\n#-26.05333333\t-85\n#-25.93\t-113\n#-26.39176471\t-163\n#-26.27\t-188\n#-26.63857143\t-225\n#-25.75\t-275\n\n#depth\t14C_mean\t14Cto12C\n#25\t40.65714286\t1.23406E-12\n#15\t54.37692308\t1.24849E-12\n#5\t112.4714286\t1.31665E-12\n#-5\t68.17647059\t1.26596E-12\n#-15\t140.0176471\t1.34839E-12\n#-25\t114.2\t 1.31571E-12\n#-35\t-99.17647059\t1.06314E-12\n#-45\t-180.2058824\t9.66953E-13\n#-55\t-199.9941176\t9.43913E-13\n#-65\t-286.2058824\t8.41779E-13\n#-85\t-358.8117647\t7.55669E-13\n#-113\t-392.4058824\t7.15896E-13\n#-163\t-486.13125\t6.06039E-13\n#-188\t-350.8\t 7.65452E-13\n#-225\t-571.1\t 5.06086E-13\n#-275\t-703.75\t 3.48927E-13\n\ncomputC13 <- function(C12, deltaC)\n{\n (deltaC / 1000.0 + 1.0) * 0.0112372 * C12\n}\n\ncomputC14 <- function(C12, deltaC13, deltaC14)\n{\n C12 * ((1.0 + deltaC14 / 1000) * (1.176e-12/((1+deltaC13)*(1+deltaC13)/(1-0.000025)/(1-0.000025))))\n}\n \n#14C = 12C * ((1 + delta14C / 1000) * (1.176e-12/((1+delta13C)*(1+delta13C)/(1-0.025)/(1-0.025)))\n \n#notice: please copy a file with the name of fileoutput in the following code for variable to be incorporated\nfileinput <- open.nc(\"SPRUCE-finalspinup-peatland-carbon-initial.nc\") # 2012 year climate data\n#filerestart <- open.nc(\"SPR_I20TRCLM45CN_adspinup.clm2.r.1201-01-01-00000.nc\")\nfileoutput <- open.nc(\"SPRUCE-finalspinup-peatland-ISOcarbon-initial.nc\",write=TRUE)\n\n#depth <- c(0.0071, 0.0028, 0.0623, 0.1189, 0.2122, 0.366, 0.6197, 1.038, 1.72, 2.86)\n#thick <- c(0.0175128179, 0.0275789693, 0.0454700332, 0.0749674110, 0.1236003651, 0.2037825510, 0.3359806264, 0.5539384054, 0.9132900316, 1.5057607014)\n#realcarbondensity = c(22385, 22385, 22385, 30294, 43978, 95584, 92983, 83658, 83799, 90616)\n\ncwdc_vr <- var.get.nc(fileinput, \"cwdc_vr\")\nlitr1c_vr <- var.get.nc(fileinput, \"litr1c_vr\")\nlitr2c_vr <- var.get.nc(fileinput, \"litr2c_vr\")\nlitr3c_vr <- var.get.nc(fileinput, \"litr3c_vr\")\nsoil1c_vr <- var.get.nc(fileinput, \"soil1c_vr\")\nsoil2c_vr <- var.get.nc(fileinput, \"soil2c_vr\")\nsoil3c_vr <- var.get.nc(fileinput, \"soil3c_vr\")\nsoil4c_vr <- var.get.nc(fileinput, \"soil4c_vr\")\n\ncwdn_vr <- var.get.nc(fileinput, \"cwdn_vr\")\nlitr1n_vr <- var.get.nc(fileinput, \"litr1c_vr\")\nlitr2n_vr <- var.get.nc(fileinput, \"litr2n_vr\")\nlitr3n_vr <- var.get.nc(fileinput, \"litr3n_vr\")\nsoil1n_vr <- var.get.nc(fileinput, \"soil1n_vr\")\nsoil2n_vr <- var.get.nc(fileinput, \"soil2n_vr\")\nsoil3n_vr <- var.get.nc(fileinput, \"soil3n_vr\")\nsoil4n_vr <- var.get.nc(fileinput, \"soil4n_vr\")\n\n#rc13_canair <- var.get.nc(filerestart, \"rc13_canair\")\n#rc13_psnsun <- var.get.nc(filerestart, \"rc13_psnsun\")\n#rc13_psnsha <- var.get.nc(filerestart, \"rc13_psnsha\")\n#leafc_13 <- var.get.nc(filerestart, \"leafc_13\")\n#leafc_storage_13 <- var.get.nc(filerestart, \"leafc_storage_13\")\n#leafc_xfer_13 <- var.get.nc(filerestart, \"leafc_xfer_13\")\n#frootc_13 <- var.get.nc(filerestart, \"frootc_13\")\n#frootc_storage_13 <- var.get.nc(filerestart, \"frootc_storage_13\")\n#frootc_xfer_13 <- var.get.nc(filerestart, \"frootc_xfer_13\")\n#livestemc_13 <- var.get.nc(filerestart, \"livestemc_13\")\n#livestemc_storage_13 <- var.get.nc(filerestart, \"livestemc_storage_13\")\n#livestemc_xfer_13 <- var.get.nc(filerestart, \"livestemc_xfer_13\")\n#deadstemc_13 <- var.get.nc(filerestart, \"deadstemc_13\")\n#deadstemc_storage_13 <- var.get.nc(filerestart, \"deadstemc_storage_13\")\n#deadstemc_xfer_13 <- var.get.nc(filerestart, \"deadstemc_xfer_13\")\n#livecrootc_13 <- var.get.nc(filerestart, \"livecrootc_13\")\n#deadstemc_13 <- var.get.nc(filerestart, \"deadstemc_13\")\n\ncwdc_13_vr = cwdc_vr\nlitr1c_13_vr = litr1c_vr\nlitr2c_13_vr = litr2c_vr\nlitr3c_13_vr = litr3c_vr\nsoil1c_13_vr = soil1c_vr\nsoil2c_13_vr = soil2c_vr\nsoil3c_13_vr = soil3c_vr\nsoil4c_13_vr = soil4c_vr\n\n# C14 \ncwdc_14_vr = cwdc_vr\nlitr1c_14_vr = litr1c_vr\nlitr2c_14_vr = litr2c_vr\nlitr3c_14_vr = litr3c_vr\nsoil1c_14_vr = soil1c_vr\nsoil2c_14_vr = soil2c_vr\nsoil3c_14_vr = soil3c_vr\nsoil4c_14_vr = soil4c_vr\n\nbacteriac_vr = litr1c_vr\nfungic_vr = litr1c_vr\ndomc_vr = litr1c_vr\nseedc = litr1c_vr\ncol_ctrunc_vr = litr1c_vr\n\ntotlitc = litr1c_vr\ntotcolc = litr1c_vr\nprod10c = litr1c_vr\nprod100c = litr1c_vr\n\nbacteriac_13_vr = bacteriac_vr\nfungic_13_vr = fungic_vr\ndomc_13_vr = domc_vr\nseedc_13 = seedc\ncol_ctrunc_13_vr = col_ctrunc_vr\n\ntotlitc_13 = totlitc\ntotcolc_13 = totcolc\nprod10c_13 = prod10c\nprod100c_13 = prod100c\n\n#C14\nbacteriac_14_vr = bacteriac_vr\nfungic_14_vr = fungic_vr\ndomc_14_vr = domc_vr\nseedc_14 = seedc\ncol_ctrunc_14_vr = col_ctrunc_vr\n\ntotlitc_14 = totlitc\ntotcolc_14 = totcolc\nprod10c_14 = prod10c\nprod100c_14 = prod100c\n\nfor(i in 1:10)\n{\ncwdc_13_vr[i,1] = computC13(cwdc_vr[i,1], SO13C[i])\nlitr1c_13_vr[i,1] = computC13(litr1c_vr[i,1], SO13C[i])\nlitr2c_13_vr[i,1] = computC13(litr2c_vr[i,1], SO13C[i])\nlitr3c_13_vr[i,1] = computC13(litr3c_vr[i,1], SO13C[i])\nsoil1c_13_vr[i,1] = computC13(soil1c_vr[i,1], SO13C[i])\nsoil2c_13_vr[i,1] = computC13(soil2c_vr[i,1], SO13C[i])\nsoil3c_13_vr[i,1] = computC13(soil3c_vr[i,1], SO13C[i])\nsoil4c_13_vr[i,1] = computC13(soil4c_vr[i,1], SO13C[i])\n\nbacteriac_13_vr[i,1] = computC13(bacteriac_vr[i,1], SO13C[i])\nfungic_13_vr[i,1] = computC13(fungic_vr[i,1], SO13C[i])\ndomc_13_vr[i,1] = computC13(domc_vr[i,1], SO13C[i])\nseedc_13[i,1] = computC13(seedc[i,1], SO13C[i])\ncol_ctrunc_13_vr[i,1] = computC13(col_ctrunc_vr[i,1], SO13C[i])\ntotlitc_13[i,1] = computC13(totlitc[i,1], SO13C[i])\ntotcolc_13[i,1] = computC13(totcolc[i,1], SO13C[i])\nprod10c_13[i,1] = computC13(prod10c[i,1], SO13C[i])\nprod100c_13[i,1] = computC13(prod100c[i,1], SO13C[i])\n\ncwdc_13_vr[i,2] = computC13(cwdc_vr[i,2], SO13C[i])\nlitr1c_13_vr[i,2] = computC13(litr1c_vr[i,2], SO13C[i])\nlitr2c_13_vr[i,2] = computC13(litr2c_vr[i,2], SO13C[i])\nlitr3c_13_vr[i,2] = computC13(litr3c_vr[i,2], SO13C[i])\nsoil1c_13_vr[i,2] = computC13(soil1c_vr[i,2], SO13C[i])\nsoil2c_13_vr[i,2] = computC13(soil2c_vr[i,2], SO13C[i])\nsoil3c_13_vr[i,2] = computC13(soil3c_vr[i,2], SO13C[i])\nsoil4c_13_vr[i,2] = computC13(soil4c_vr[i,2], SO13C[i])\n\nbacteriac_13_vr[i,2] = computC13(bacteriac_vr[i,2], SO13C[i])\nfungic_13_vr[i,2] = computC13(fungic_vr[i,2], SO13C[i])\ndomc_13_vr[i,2] = computC13(domc_vr[i,2], SO13C[i])\nseedc_13[i,2] = computC13(seedc[i,2], SO13C[i])\ncol_ctrunc_13_vr[i,2] = computC13(col_ctrunc_vr[i,2], SO13C[i])\ntotlitc_13[i,2] = computC13(totlitc[i,2], SO13C[i])\ntotcolc_13[i,2] = computC13(totcolc[i,2], SO13C[i])\nprod10c_13[i,2] = computC13(prod10c[i,2], SO13C[i])\nprod100c_13[i,2] = computC13(prod100c[i,2], SO13C[i])\n}\n\nfor(i in 11:15)\n{\ncwdc_13_vr[i,1] = 0.0\nlitr1c_13_vr[i,1] = 0.0\nlitr2c_13_vr[i,1] = 0.0\nlitr3c_13_vr[i,1] = 0.0\nsoil1c_13_vr[i,1] = 0.0\nsoil2c_13_vr[i,1] = 0.0\nsoil3c_13_vr[i,1] = 0.0\nsoil4c_13_vr[i,1] = 0.0\n \nbacteriac_13_vr[i,1] = 0.0\nfungic_13_vr[i,1] = 0.0\ndomc_13_vr[i,1] = 0.0\nseedc_13[i,1] = 0.0\ncol_ctrunc_13_vr[i,1] = 0.0\n\ntotlitc_13[i,1] = 0.0\ntotcolc_13[i,1] = 0.0\nprod10c_13[i,1] = 0.0\nprod100c_13[i,1] = 0.0\n \ncwdc_13_vr[i,2] = 0.0\nlitr1c_13_vr[i,2] = 0.0\nlitr2c_13_vr[i,2] = 0.0\nlitr3c_13_vr[i,2] = 0.0\nsoil1c_13_vr[i,2] = 0.0\nsoil2c_13_vr[i,2] = 0.0\nsoil3c_13_vr[i,2] = 0.0\nsoil4c_13_vr[i,2] = 0.0\n \nbacteriac_13_vr[i,2] = 0.0\nfungic_13_vr[i,2] = 0.0\ndomc_13_vr[i,2] = 0.0\nseedc_13[i,2] = 0.0\ncol_ctrunc_13_vr[i,2] = 0.0\n \ntotlitc_13[i,2] = 0.0\ntotcolc_13[i,2] = 0.0\nprod10c_13[i,2] = 0.0\nprod100c_13[i,2] = 0.0\n}\n\nfor(i in 1:10)\n{\n cwdc_14_vr[i,1] = computC14(cwdc_vr[i,1], cwdc_13_vr[i,1], SO14C[i])\n litr1c_14_vr[i,1] = computC14(litr1c_vr[i,1], litr1c_13_vr[i,1], SO14C[i])\n litr2c_14_vr[i,1] = computC14(litr2c_vr[i,1], litr2c_13_vr[i,1], SO14C[i])\n litr3c_14_vr[i,1] = computC14(litr3c_vr[i,1], litr3c_13_vr[i,1], SO14C[i])\n soil1c_14_vr[i,1] = computC14(soil1c_vr[i,1], soil1c_13_vr[i,1], SO14C[i])\n soil2c_14_vr[i,1] = computC14(soil2c_vr[i,1], soil2c_13_vr[i,1], SO14C[i])\n soil3c_14_vr[i,1] = computC14(soil3c_vr[i,1], soil3c_13_vr[i,1], SO14C[i])\n soil4c_14_vr[i,1] = computC14(soil4c_vr[i,1], soil4c_13_vr[i,1], SO14C[i])\n \n bacteriac_14_vr[i,1] = computC14(bacteriac_vr[i,1], bacteriac_13_vr[i,1], SO14C[i])\n fungic_14_vr[i,1] = computC14(fungic_vr[i,1], fungic_13_vr[i,1], SO14C[i])\n domc_14_vr[i,1] = computC14(domc_vr[i,1], domc_13_vr[i,1], SO14C[i])\n seedc_14[i,1] = computC14(seedc[i,1], seedc_13[i,1], SO14C[i])\n col_ctrunc_14_vr[i,1] = computC14(col_ctrunc_vr[i,1], col_ctrunc_13_vr[i,1], SO14C[i])\n totlitc_14[i,1] = computC14(totlitc[i,1], totlitc_13[i,1], SO14C[i])\n totcolc_14[i,1] = computC14(totcolc[i,1], totcolc_13[i,1], SO14C[i])\n prod10c_14[i,1] = computC14(prod10c[i,1], prod10c_13[i,1], SO14C[i])\n prod100c_14[i,1] = computC14(prod100c[i,1], prod100c_13[i,1], SO14C[i])\n \n cwdc_14_vr[i,2] = computC14(cwdc_vr[i,2], cwdc_13_vr[i,2], SO14C[i])\n litr1c_14_vr[i,2] = computC14(litr1c_vr[i,2], litr1c_13_vr[i,2], SO14C[i])\n litr2c_14_vr[i,2] = computC14(litr2c_vr[i,2], litr2c_13_vr[i,2], SO14C[i])\n litr3c_14_vr[i,2] = computC14(litr3c_vr[i,2], litr3c_13_vr[i,2], SO14C[i])\n soil1c_14_vr[i,2] = computC14(soil1c_vr[i,2], soil1c_13_vr[i,2], SO14C[i])\n soil2c_14_vr[i,2] = computC14(soil2c_vr[i,2], soil2c_13_vr[i,2], SO14C[i])\n soil3c_14_vr[i,2] = computC14(soil3c_vr[i,2], soil3c_13_vr[i,2], SO14C[i])\n soil4c_14_vr[i,2] = computC14(soil4c_vr[i,2], soil4c_13_vr[i,2], SO14C[i])\n \n bacteriac_14_vr[i,2] = computC14(bacteriac_vr[i,2], bacteriac_13_vr[i,2], SO14C[i])\n fungic_14_vr[i,2] = computC14(fungic_vr[i,2], fungic_13_vr[i,2], SO14C[i])\n domc_14_vr[i,2] = computC14(domc_vr[i,2], domc_13_vr[i,2], SO14C[i])\n seedc_14[i,2] = computC14(seedc[i,2], seedc_13[i,2], SO14C[i])\n col_ctrunc_14_vr[i,2] = computC14(col_ctrunc_vr[i,2], col_ctrunc_13_vr[i,2], SO14C[i])\n totlitc_14[i,2] = computC14(totlitc[i,2], totlitc_13[i,2], SO14C[i])\n totcolc_14[i,2] = computC14(totcolc[i,2], totcolc_13[i,2], SO14C[i])\n prod10c_14[i,2] = computC14(prod10c[i,2], prod10c_13[i,2], SO14C[i])\n prod100c_14[i,2] = computC14(prod100c[i,2], prod100c_13[i,2], SO14C[i])\n}\n\nfor(i in 11:15)\n{\n cwdc_14_vr[i,1] = 0.0\n litr1c_14_vr[i,1] = 0.0\n litr2c_14_vr[i,1] = 0.0\n litr3c_14_vr[i,1] = 0.0\n soil1c_14_vr[i,1] = 0.0\n soil2c_14_vr[i,1] = 0.0\n soil3c_14_vr[i,1] = 0.0\n soil4c_14_vr[i,1] = 0.0\n \n bacteriac_14_vr[i,1] = 0.0\n fungic_14_vr[i,1] = 0.0\n domc_14_vr[i,1] = 0.0\n seedc_14[i,1] = 0.0\n col_ctrunc_14_vr[i,1] = 0.0\n \n totlitc_14[i,1] = 0.0\n totcolc_14[i,1] = 0.0\n prod10c_14[i,1] = 0.0\n prod100c_14[i,1] = 0.0\n \n cwdc_14_vr[i,2] = 0.0\n litr1c_14_vr[i,2] = 0.0\n litr2c_14_vr[i,2] = 0.0\n litr3c_14_vr[i,2] = 0.0\n soil1c_14_vr[i,2] = 0.0\n soil2c_14_vr[i,2] = 0.0\n soil3c_14_vr[i,2] = 0.0\n soil4c_14_vr[i,2] = 0.0\n \n bacteriac_14_vr[i,2] = 0.0\n fungic_14_vr[i,2] = 0.0\n domc_14_vr[i,2] = 0.0\n seedc_14[i,2] = 0.0\n col_ctrunc_14_vr[i,2] = 0.0\n \n totlitc_14[i,2] = 0.0\n totcolc_14[i,2] = 0.0\n prod10c_14[i,2] = 0.0\n prod100c_14[i,2] = 0.0\n}\n\n\n# \n#rc13_canair = c(0.005582864, 0.002791432)\n#rc13_psnsha = c(0.005544063, 0.002771556)\n#rc13_psnsun = c(0.0055442, 0.002771556)\n#\n\n#levgrnd = 15\n#column = 2\n#var.def.nc(fileoutput,\"levgrnd\",\"NC_FLOAT\",\"levgrnd\")\n#var.def.nc(fileoutput,\"column\",\"NC_FLOAT\",\"column\")\n\nvar.def.nc(fileoutput,\"cwdc_13_vr\",\"NC_FLOAT\",c(\"levgrnd\",\"column\"))\nvar.def.nc(fileoutput,\"litr1c_13_vr\",\"NC_FLOAT\",c(\"levgrnd\",\"column\"))\nvar.def.nc(fileoutput,\"litr2c_13_vr\",\"NC_FLOAT\",c(\"levgrnd\",\"column\"))\nvar.def.nc(fileoutput,\"litr3c_13_vr\",\"NC_FLOAT\",c(\"levgrnd\",\"column\"))\nvar.def.nc(fileoutput,\"soil1c_13_vr\",\"NC_FLOAT\",c(\"levgrnd\",\"column\"))\nvar.def.nc(fileoutput,\"soil2c_13_vr\",\"NC_FLOAT\",c(\"levgrnd\",\"column\"))\nvar.def.nc(fileoutput,\"soil3c_13_vr\",\"NC_FLOAT\",c(\"levgrnd\",\"column\"))\nvar.def.nc(fileoutput,\"soil4c_13_vr\",\"NC_FLOAT\",c(\"levgrnd\",\"column\"))\nvar.def.nc(fileoutput,\"bacteriac_13_vr\",\"NC_FLOAT\",c(\"levgrnd\",\"column\"))\nvar.def.nc(fileoutput,\"fungic_13_vr\",\"NC_FLOAT\",c(\"levgrnd\",\"column\"))\nvar.def.nc(fileoutput,\"domc_13_vr\",\"NC_FLOAT\",c(\"levgrnd\",\"column\"))\nvar.def.nc(fileoutput,\"seedc_13\",\"NC_FLOAT\",c(\"levgrnd\",\"column\"))\nvar.def.nc(fileoutput,\"col_ctrunc_13_vr\",\"NC_FLOAT\",c(\"levgrnd\",\"column\"))\nvar.def.nc(fileoutput,\"totlitc_13\",\"NC_FLOAT\",c(\"levgrnd\",\"column\"))\nvar.def.nc(fileoutput,\"totcolc_13\",\"NC_FLOAT\",c(\"levgrnd\",\"column\"))\nvar.def.nc(fileoutput,\"prod10c_13\",\"NC_FLOAT\",c(\"levgrnd\",\"column\"))\nvar.def.nc(fileoutput,\"prod100c_13\",\"NC_FLOAT\",c(\"levgrnd\",\"column\"))\n\nvar.def.nc(fileoutput,\"cwdc_14_vr\",\"NC_FLOAT\",c(\"levgrnd\",\"column\"))\nvar.def.nc(fileoutput,\"litr1c_14_vr\",\"NC_FLOAT\",c(\"levgrnd\",\"column\"))\nvar.def.nc(fileoutput,\"litr2c_14_vr\",\"NC_FLOAT\",c(\"levgrnd\",\"column\"))\nvar.def.nc(fileoutput,\"litr3c_14_vr\",\"NC_FLOAT\",c(\"levgrnd\",\"column\"))\nvar.def.nc(fileoutput,\"soil1c_14_vr\",\"NC_FLOAT\",c(\"levgrnd\",\"column\"))\nvar.def.nc(fileoutput,\"soil2c_14_vr\",\"NC_FLOAT\",c(\"levgrnd\",\"column\"))\nvar.def.nc(fileoutput,\"soil3c_14_vr\",\"NC_FLOAT\",c(\"levgrnd\",\"column\"))\nvar.def.nc(fileoutput,\"soil4c_14_vr\",\"NC_FLOAT\",c(\"levgrnd\",\"column\"))\nvar.def.nc(fileoutput,\"bacteriac_14_vr\",\"NC_FLOAT\",c(\"levgrnd\",\"column\"))\nvar.def.nc(fileoutput,\"fungic_14_vr\",\"NC_FLOAT\",c(\"levgrnd\",\"column\"))\nvar.def.nc(fileoutput,\"domc_14_vr\",\"NC_FLOAT\",c(\"levgrnd\",\"column\"))\nvar.def.nc(fileoutput,\"seedc_14\",\"NC_FLOAT\",c(\"levgrnd\",\"column\"))\nvar.def.nc(fileoutput,\"col_ctrunc_14_vr\",\"NC_FLOAT\",c(\"levgrnd\",\"column\"))\nvar.def.nc(fileoutput,\"totlitc_14\",\"NC_FLOAT\",c(\"levgrnd\",\"column\"))\nvar.def.nc(fileoutput,\"totcolc_14\",\"NC_FLOAT\",c(\"levgrnd\",\"column\"))\nvar.def.nc(fileoutput,\"prod10c_14\",\"NC_FLOAT\",c(\"levgrnd\",\"column\"))\nvar.def.nc(fileoutput,\"prod100c_14\",\"NC_FLOAT\",c(\"levgrnd\",\"column\"))\n\nvar.put.nc(fileoutput, \"cwdc_vr\",cwdc_vr)\nvar.put.nc(fileoutput, \"litr1c_vr\",litr1c_vr)\nvar.put.nc(fileoutput, \"litr2c_vr\",litr2c_vr)\nvar.put.nc(fileoutput, \"litr3c_vr\",litr3c_vr)\nvar.put.nc(fileoutput, \"soil1c_vr\",soil1c_vr)\nvar.put.nc(fileoutput, \"soil2c_vr\",soil2c_vr)\nvar.put.nc(fileoutput, \"soil3c_vr\",soil3c_vr)\nvar.put.nc(fileoutput, \"soil4c_vr\",soil4c_vr)\n\nvar.put.nc(fileoutput, \"cwdn_vr\",cwdn_vr)\nvar.put.nc(fileoutput, \"litr1n_vr\",litr1n_vr)\nvar.put.nc(fileoutput, \"litr2n_vr\",litr2n_vr)\nvar.put.nc(fileoutput, \"litr3n_vr\",litr3n_vr)\nvar.put.nc(fileoutput, \"soil1n_vr\",soil1n_vr)\nvar.put.nc(fileoutput, \"soil2n_vr\",soil2n_vr)\nvar.put.nc(fileoutput, \"soil3n_vr\",soil3n_vr)\nvar.put.nc(fileoutput, \"soil4n_vr\",soil4n_vr)\n\natt.put.nc(fileoutput, \"cwdc_13_vr\",\"missing_value\", \"NC_FLOAT\", -9999)\nvar.put.nc(fileoutput, \"cwdc_13_vr\",cwdc_13_vr)\n\natt.put.nc(fileoutput, \"litr1c_13_vr\",\"missing_value\", \"NC_FLOAT\", -9999)\nvar.put.nc(fileoutput, \"litr1c_13_vr\",litr1c_13_vr)\n\natt.put.nc(fileoutput, \"litr2c_13_vr\",\"missing_value\", \"NC_FLOAT\", -9999)\nvar.put.nc(fileoutput, \"litr2c_13_vr\",litr2c_13_vr)\n\natt.put.nc(fileoutput, \"litr3c_13_vr\",\"missing_value\", \"NC_FLOAT\", -9999)\nvar.put.nc(fileoutput, \"litr3c_13_vr\",litr3c_13_vr)\n\natt.put.nc(fileoutput, \"soil1c_13_vr\",\"missing_value\", \"NC_FLOAT\", -9999)\nvar.put.nc(fileoutput, \"soil1c_13_vr\",soil1c_13_vr)\n\natt.put.nc(fileoutput, \"soil2c_13_vr\",\"missing_value\", \"NC_FLOAT\", -9999)\nvar.put.nc(fileoutput, \"soil2c_13_vr\",soil2c_13_vr)\n\natt.put.nc(fileoutput, \"soil3c_13_vr\",\"missing_value\", \"NC_FLOAT\", -9999)\nvar.put.nc(fileoutput, \"soil3c_13_vr\",soil3c_13_vr)\n\natt.put.nc(fileoutput, \"soil4c_13_vr\",\"missing_value\", \"NC_FLOAT\", -9999)\nvar.put.nc(fileoutput, \"soil4c_13_vr\",soil4c_13_vr)\n\natt.put.nc(fileoutput, \"bacteriac_13_vr\",\"missing_value\", \"NC_FLOAT\", -9999)\nvar.put.nc(fileoutput, \"bacteriac_13_vr\",bacteriac_13_vr)\n\natt.put.nc(fileoutput, \"fungic_13_vr\",\"missing_value\", \"NC_FLOAT\", -9999)\nvar.put.nc(fileoutput, \"fungic_13_vr\",fungic_13_vr)\n\natt.put.nc(fileoutput, \"domc_13_vr\",\"missing_value\", \"NC_FLOAT\", -9999)\nvar.put.nc(fileoutput, \"domc_13_vr\",domc_13_vr)\n\natt.put.nc(fileoutput, \"seedc_13\",\"missing_value\", \"NC_FLOAT\", -9999)\nvar.put.nc(fileoutput, \"seedc_13\",seedc_13)\n\natt.put.nc(fileoutput, \"col_ctrunc_13_vr\",\"missing_value\", \"NC_FLOAT\", -9999)\nvar.put.nc(fileoutput, \"col_ctrunc_13_vr\",col_ctrunc_13_vr)\n\natt.put.nc(fileoutput, \"totlitc_13\",\"missing_value\", \"NC_FLOAT\", -9999)\nvar.put.nc(fileoutput, \"totlitc_13\",totlitc_13)\n\natt.put.nc(fileoutput, \"totcolc_13\",\"missing_value\", \"NC_FLOAT\", -9999)\nvar.put.nc(fileoutput, \"totcolc_13\",totcolc_13)\n\natt.put.nc(fileoutput, \"prod10c_13\",\"missing_value\", \"NC_FLOAT\", -9999)\nvar.put.nc(fileoutput, \"prod10c_13\",prod10c_13)\n\natt.put.nc(fileoutput, \"prod100c_13\",\"missing_value\", \"NC_FLOAT\", -9999)\nvar.put.nc(fileoutput, \"prod100c_13\",prod100c_13)\n\n# 14C\natt.put.nc(fileoutput, \"cwdc_14_vr\",\"missing_value\", \"NC_FLOAT\", -9999)\nvar.put.nc(fileoutput, \"cwdc_14_vr\",cwdc_14_vr)\n\natt.put.nc(fileoutput, \"litr1c_14_vr\",\"missing_value\", \"NC_FLOAT\", -9999)\nvar.put.nc(fileoutput, \"litr1c_14_vr\",litr1c_14_vr)\n\natt.put.nc(fileoutput, \"litr2c_14_vr\",\"missing_value\", \"NC_FLOAT\", -9999)\nvar.put.nc(fileoutput, \"litr2c_14_vr\",litr2c_14_vr)\n\natt.put.nc(fileoutput, \"litr3c_14_vr\",\"missing_value\", \"NC_FLOAT\", -9999)\nvar.put.nc(fileoutput, \"litr3c_14_vr\",litr3c_14_vr)\n\natt.put.nc(fileoutput, \"soil1c_14_vr\",\"missing_value\", \"NC_FLOAT\", -9999)\nvar.put.nc(fileoutput, \"soil1c_14_vr\",soil1c_14_vr)\n\natt.put.nc(fileoutput, \"soil2c_14_vr\",\"missing_value\", \"NC_FLOAT\", -9999)\nvar.put.nc(fileoutput, \"soil2c_14_vr\",soil2c_14_vr)\n\natt.put.nc(fileoutput, \"soil3c_14_vr\",\"missing_value\", \"NC_FLOAT\", -9999)\nvar.put.nc(fileoutput, \"soil3c_14_vr\",soil3c_14_vr)\n\natt.put.nc(fileoutput, \"soil4c_14_vr\",\"missing_value\", \"NC_FLOAT\", -9999)\nvar.put.nc(fileoutput, \"soil4c_14_vr\",soil4c_14_vr)\n\natt.put.nc(fileoutput, \"bacteriac_14_vr\",\"missing_value\", \"NC_FLOAT\", -9999)\nvar.put.nc(fileoutput, \"bacteriac_14_vr\",bacteriac_14_vr)\n\natt.put.nc(fileoutput, \"fungic_14_vr\",\"missing_value\", \"NC_FLOAT\", -9999)\nvar.put.nc(fileoutput, \"fungic_14_vr\",fungic_14_vr)\n\natt.put.nc(fileoutput, \"domc_14_vr\",\"missing_value\", \"NC_FLOAT\", -9999)\nvar.put.nc(fileoutput, \"domc_14_vr\",domc_14_vr)\n\natt.put.nc(fileoutput, \"seedc_14\",\"missing_value\", \"NC_FLOAT\", -9999)\nvar.put.nc(fileoutput, \"seedc_14\",seedc_14)\n\natt.put.nc(fileoutput, \"col_ctrunc_14_vr\",\"missing_value\", \"NC_FLOAT\", -9999)\nvar.put.nc(fileoutput, \"col_ctrunc_14_vr\",col_ctrunc_14_vr)\n\natt.put.nc(fileoutput, \"totlitc_14\",\"missing_value\", \"NC_FLOAT\", -9999)\nvar.put.nc(fileoutput, \"totlitc_14\",totlitc_14)\n\natt.put.nc(fileoutput, \"totcolc_14\",\"missing_value\", \"NC_FLOAT\", -9999)\nvar.put.nc(fileoutput, \"totcolc_14\",totcolc_14)\n\natt.put.nc(fileoutput, \"prod10c_14\",\"missing_value\", \"NC_FLOAT\", -9999)\nvar.put.nc(fileoutput, \"prod10c_14\",prod10c_14)\n\natt.put.nc(fileoutput, \"prod100c_14\",\"missing_value\", \"NC_FLOAT\", -9999)\nvar.put.nc(fileoutput, \"prod100c_14\",prod100c_14)\n\n# new file\n#var.def.nc(fileoutput,\"rc13_canair\",\"NC_FLOAT\",c(\"pft\"))\n#att.put.nc(fileoutput, \"rc13_canair\",\"missing_value\", \"NC_FLOAT\", -9999)\n#var.put.nc(fileoutput, \"rc13_canair\",rc13_canair)\n\n#var.def.nc(fileoutput,\"rc13_psnsun\",\"NC_FLOAT\",c(\"pft\"))\n#att.put.nc(fileoutput, \"rc13_psnsun\",\"missing_value\", \"NC_FLOAT\", -9999)\n#var.put.nc(fileoutput, \"rc13_psnsun\",rc13_psnsun)\n\n#var.def.nc(fileoutput,\"rc13_psnsha\",\"NC_FLOAT\",c(\"pft\"))\n#att.put.nc(fileoutput, \"rc13_psnsha\",\"missing_value\", \"NC_FLOAT\", -9999)\n#var.put.nc(fileoutput, \"rc13_psnsha\",rc13_psnsha)\n\n#var.def.nc(fileoutput,\"leafc_13\",\"NC_FLOAT\",c(\"pft\"))\n#att.put.nc(fileoutput, \"leafc_13\",\"missing_value\", \"NC_FLOAT\", -9999)\n#var.put.nc(fileoutput, \"leafc_13\",leafc_13)\n\n#var.def.nc(fileoutput,\"leafc_storage_13\",\"NC_FLOAT\",c(\"pft\"))\n#att.put.nc(fileoutput, \"leafc_storage_13\",\"missing_value\", \"NC_FLOAT\", -9999)\n#var.put.nc(fileoutput, \"leafc_storage_13\",leafc_storage_13)\n\n#var.def.nc(fileoutput,\"leafc_xfer_13\",\"NC_FLOAT\",c(\"pft\"))\n#att.put.nc(fileoutput, \"leafc_xfer_13\",\"missing_value\", \"NC_FLOAT\", -9999)\n#var.put.nc(fileoutput, \"leafc_xfer_13\",leafc_xfer_13)\n\n#var.def.nc(fileoutput,\"frootc_13\",\"NC_FLOAT\",c(\"pft\"))\n#att.put.nc(fileoutput, \"frootc_13\",\"missing_value\", \"NC_FLOAT\", -9999)\n#var.put.nc(fileoutput, \"frootc_13\",frootc_13)\n\n#var.def.nc(fileoutput,\"frootc_storage_13\",\"NC_FLOAT\",c(\"pft\"))\n#att.put.nc(fileoutput, \"frootc_storage_13\",\"missing_value\", \"NC_FLOAT\", -9999)\n#var.put.nc(fileoutput, \"frootc_storage_13\",frootc_storage_13)\n\n#var.def.nc(fileoutput,\"frootc_xfer_13\",\"NC_FLOAT\",c(\"pft\"))\n#att.put.nc(fileoutput, \"frootc_xfer_13\",\"missing_value\", \"NC_FLOAT\", -9999)\n#var.put.nc(fileoutput, \"frootc_xfer_13\",frootc_xfer_13)\n\n#var.def.nc(fileoutput,\"livestemc_13\",\"NC_FLOAT\",c(\"pft\"))\n#att.put.nc(fileoutput, \"livestemc_13\",\"missing_value\", \"NC_FLOAT\", -9999)\n#var.put.nc(fileoutput, \"livestemc_13\",livestemc_13)\n\n#var.def.nc(fileoutput,\"livestemc_storage_13\",\"NC_FLOAT\",c(\"pft\"))\n#att.put.nc(fileoutput, \"livestemc_storage_13\",\"missing_value\", \"NC_FLOAT\", -9999)\n#var.put.nc(fileoutput, \"livestemc_storage_13\",livestemc_storage_13)\n\n#var.def.nc(fileoutput,\"livestemc_xfer_13\",\"NC_FLOAT\",c(\"pft\"))\n#att.put.nc(fileoutput, \"livestemc_xfer_13\",\"missing_value\", \"NC_FLOAT\", -9999)\n#var.put.nc(fileoutput, \"livestemc_xfer_13\",livestemc_xfer_13)\n\n#var.def.nc(fileoutput,\"deadstemc_13\",\"NC_FLOAT\",c(\"pft\"))\n#att.put.nc(fileoutput, \"deadstemc_13\",\"missing_value\", \"NC_FLOAT\", -9999)\n#var.put.nc(fileoutput, \"deadstemc_13\",deadstemc_13)\n\n#var.def.nc(fileoutput,\"deadstemc_storage_13\",\"NC_FLOAT\",c(\"pft\"))\n#att.put.nc(fileoutput, \"deadstemc_storage_13\",\"missing_value\", \"NC_FLOAT\", -9999)\n#var.put.nc(fileoutput, \"deadstemc_storage_13\",deadstemc_storage_13)\n\n#var.def.nc(fileoutput,\"deadstemc_xfer_13\",\"NC_FLOAT\",c(\"pft\"))\n#att.put.nc(fileoutput, \"deadstemc_xfer_13\",\"missing_value\", \"NC_FLOAT\", -9999)\n#var.put.nc(fileoutput, \"deadstemc_xfer_13\",deadstemc_xfer_13)\n\n#var.def.nc(fileoutput,\"livecrootc_13\",\"NC_FLOAT\",c(\"pft\"))\n#att.put.nc(fileoutput, \"livecrootc_13\",\"missing_value\", \"NC_FLOAT\", -9999)\n#var.put.nc(fileoutput, \"livecrootc_13\",livecrootc_13)\n\n#var.def.nc(fileoutput,\"deadstemc_13\",\"NC_FLOAT\",c(\"pft\"))\n#att.put.nc(fileoutput, \"deadstemc_13\",\"missing_value\", \"NC_FLOAT\", -9999)\n#var.put.nc(fileoutput, \"deadstemc_13\",deadstemc_13)\n\natt.put.nc(fileoutput,\"NC_GLOBAL\",\"title\",\"NC_CHAR\",\"isotopic 13 carbon pools and 14 carbon pools\")\n\nclose.nc(fileinput)\nclose.nc(fileoutput)\n\n", "meta": {"hexsha": "5174f6a3a2d002d743150d8d4465cbbc9616ab01", "size": 25306, "ext": "r", "lang": "R", "max_stars_repo_path": "inputdata/lnd/clm2/inidata/2020Sep/SPRUCE-initial20200923.r", "max_stars_repo_name": "email-clm/clm-microbe", "max_stars_repo_head_hexsha": "3470e673957e4e3c3d730c5979a89d1448e9e4e4", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2019-03-12T01:58:26.000Z", "max_stars_repo_stars_event_max_datetime": "2020-12-16T03:08:25.000Z", "max_issues_repo_path": "inputdata/lnd/clm2/inidata/2020Sep/SPRUCE-initial20200923.r", "max_issues_repo_name": "email-clm/clm-microbe", "max_issues_repo_head_hexsha": "3470e673957e4e3c3d730c5979a89d1448e9e4e4", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 1, "max_issues_repo_issues_event_min_datetime": "2022-01-21T01:51:13.000Z", "max_issues_repo_issues_event_max_datetime": "2022-01-21T01:51:13.000Z", "max_forks_repo_path": "inputdata/lnd/clm2/inidata/2020Sep/SPRUCE-initial20200923.r", "max_forks_repo_name": "email-clm/CLM-Microbe", "max_forks_repo_head_hexsha": "711c87faec2c1bfe2cea1a7ebd07e4373e82a184", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 13, "max_forks_repo_forks_event_min_datetime": "2016-03-08T21:04:52.000Z", "max_forks_repo_forks_event_max_datetime": "2021-05-16T03:29:35.000Z", "avg_line_length": 39.173374613, "max_line_length": 151, "alphanum_fraction": 0.6999525804, "num_tokens": 11365, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO\n\n", "lm_q1_score": 0.7401743505760728, "lm_q2_score": 0.476579651063676, "lm_q1q2_score": 0.3527520337238278}} {"text": "#' ---\n#' title: \"Prior probabilities in the interpretation of 'some': analysis of uniform prior wonky world model predictions\"\n#' author: \"Judith Degen\"\n#' date: \"January 26, 2014\"\n#' ---\n\nlibrary(ggplot2)\ntheme_set(theme_bw(18))\nsetwd(\"/Users/titlis/cogsci/projects/stanford/projects/thegricean_sinking-marbles/writing/_2015/_journal_cognition/pics/\")\nsource(\"../rscripts/helpers.r\")\n\n# get prior modes\npriormodes = read.table(file=\"~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/experiments/12_sinking-marbles-prior15/results/data/modes.txt\",sep=\"\\t\", header=T, quote=\"\")\nrow.names(priormodes) = paste(priormodes$Item)\n\n# get prior expectations\npriorexpectations = read.table(file=\"~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/experiments/24_sinking-marbles-prior-fourstep/results/data/expectations.txt\",sep=\"\\t\", header=T, quote=\"\")\nrow.names(priorexpectations) = priorexpectations$Item\n\n# histogram of expectations\nexps = ggplot(priorexpectations, aes(x=expectation_corr)) +\n geom_histogram() +\n scale_x_continuous(name=\"Expected value of prior distribution\",breaks=seq(1,15, by=2)) +\n scale_y_continuous(name=\"Number of cases\",breaks=seq(0,8, by=2))\nggsave(\"priorexpectations-histogram.pdf\",width=5,height=3.7)\n\n\n# get prior allstate-probs\npriorprobs = read.table(file=\"~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/experiments/24_sinking-marbles-prior-fourstep/results/data/smoothed_15marbles_priors_withnames.txt\",sep=\"\\t\", header=T, quote=\"\")\nrow.names(priorprobs) = priorprobs$Item\nhead(priorprobs)\n\n# histogram of allstate-probs\nallprobs = ggplot(priorprobs, aes(x=X15)) +\n geom_histogram() +\n scale_x_continuous(name=\"Prior all-state probability\") +\n scale_y_continuous(name=\"Number of cases\")\nggsave(\"priorallprobs-histogram.pdf\")\n\nlibrary(gridExtra)\npdf(\"priordistributions.pdf\",width=10,height=4)\ngrid.arrange(exps, allprobs, nrow=1,widths=unit.c(unit(.5, \"npc\"), unit(.5, \"npc\")))\ndev.off()\n\n#####################################\n# plot model predictions: expectations\nload(\"~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/models/wonky_world/results/data/mp-uniform.RData\")\n\n# plot expectations for unreliable speaker model: \ntoplot = droplevels(subset(mp, Quantifier == \"some\"))\nnrow(toplot)\nhead(toplot)\nsummary(toplot)\nub = droplevels(subset(toplot, State == 15))\n\nggplot(ub, aes(x=PriorProbability, y=PosteriorProbability, color=as.factor(SpeakerOptimality))) +\n geom_point() +#color=\"#00B0F6\") + #values=c(\"#F8766D\", \"#A3A500\", \"#00BF7D\", \"#E76BF3\", \"#00B0F6\")\n geom_smooth() +#color=\"#00B0F6\") +\n # geom_abline(intercept=0,slope=1,color=\"gray50\") +\n scale_x_continuous(limits=c(0,1), name=\"Prior all-state probability\") +\n scale_y_continuous(limits=c(0,1), name=\"Model predicted posterior all-state probability\") +\n facet_wrap(~WonkyWorldPrior)\nggsave(\"speakerreliability-ieoptimality.pdf\",height=8,width=11)\n\n# plot expectations for best basic model: \ntoplot = droplevels(subset(mp, QUD == \"how-many\" & Alternatives == \"0_basic\" & Quantifier == \"some\" & WonkyWorldPrior == .5))\nnrow(toplot)\npexpectations = ddply(toplot, .(Item), summarise, PosteriorExpectation_predicted=sum(State*PosteriorProbability)/15)\nhead(pexpectations)\nsome = pexpectations#droplevels(subset(pexpectations, Quantifier == \"some\"))\n\n\n\ntoplot = droplevels(subset(some, SpeakerOptimality == 2))\nnrow(toplot)\nhead(toplot)\ntoplot$Mode = priormodes[as.character(toplot$Item),]$Mode\n\nggplot(toplot, aes(x=PriorExpectation_smoothed, y=PosteriorExpectation_predicted)) +\n geom_point(color=\"#00B0F6\") + #values=c(\"#F8766D\", \"#A3A500\", \"#00BF7D\", \"#E76BF3\", \"#00B0F6\")\n geom_smooth(color=\"#00B0F6\") +\n # geom_abline(intercept=0,slope=1,color=\"gray50\") +\n scale_x_continuous(limits=c(0,1), name=\"Prior expectation\") +\n scale_y_continuous(limits=c(0,1), name=\"Model predicted posterior expectation\")\n\n\npexpectations = ddply(toplot, .(Item, SpeakerOptimality,PriorExpectation_smoothed, PosteriorExpectation_empirical), summarise, PosteriorExpectation_predicted=sum(State*PosteriorProbability)/15)\nhead(pexpectations)\nsome = pexpectations#droplevels(subset(pexpectations, Quantifier == \"some\"))\n\ntoplot = droplevels(subset(some, SpeakerOptimality == 2))\nnrow(toplot)\nhead(toplot)\ntoplot$Mode = priormodes[as.character(toplot$Item),]$Mode\n\nggplot(toplot, aes(x=PriorExpectation_smoothed, y=PosteriorExpectation_predicted)) +\n geom_point(color=\"#00B0F6\") + #values=c(\"#F8766D\", \"#A3A500\", \"#00BF7D\", \"#E76BF3\", \"#00B0F6\")\n geom_smooth(color=\"#00B0F6\") +\n # geom_abline(intercept=0,slope=1,color=\"gray50\") +\n scale_x_continuous(limits=c(0,1), name=\"Prior expectation\") +\n scale_y_continuous(limits=c(0,1), name=\"Model predicted posterior expectation\")\n# geom_text(data=cors, aes(label=r)) +\n\n#scale_size_discrete(range=c(1,2)) +\n#scale_color_manual(values=c(\"red\",\"blue\",\"black\")) \nggsave(\"model-expectations.pdf\",width=5.5,height=4.5)#,width=30,height=10)\nsave(toplot, file=\"../data/toplot-expectations.RData\")\n\n# plot by prior mode instead\nggplot(toplot, aes(x=Mode, y=PosteriorExpectation_predicted)) +\n geom_point(color=\"#00B0F6\") + #values=c(\"#F8766D\", \"#A3A500\", \"#00BF7D\", \"#E76BF3\", \"#00B0F6\")\n geom_smooth(color=\"#00B0F6\") +\n # geom_abline(intercept=0,slope=1,color=\"gray50\") +\n scale_x_continuous(limits=c(0,15), name=\"Prior mode\") +\n scale_y_continuous(limits=c(0,1), name=\"Model predicted posterior expectation\")\n\ntoplot_w = toplot\n# get rRSA predictions for qud=how-many, alts=0_basic, spopt=2\nload(\"~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/models/complex_prior/smoothed_unbinned15/results/data/toplot-expectations.RData\")\ntoplot_r = toplot\nhead(toplot_w)\nsummary(toplot_r)\ntoplot_r$Model = \"RSA\"\ntoplot_w$Model = \"wRSA\"\n\n# plot regular rsa predictions\nggplot(toplot_r, aes(x=PriorExpectation_smoothed*15, y=PosteriorExpectation_predicted*15)) +\n geom_point(color=\"#007fb1\") + #values=c(\"#F8766D\", \"#A3A500\", \"#00BF7D\", \"#E76BF3\", \"#00B0F6\")\n geom_smooth(color=\"#007fb1\") +\n # geom_abline(intercept=0,slope=1,color=\"gray50\") +\n scale_x_continuous(limits=c(0,15), breaks=seq(1,15,by=2), name=\"Prior expected number of objects\") +\n scale_y_continuous(limits=c(0,15), breaks=seq(1,15,by=2), name=\"Posterior predicted number of objects\")\n# geom_text(data=cors, aes(label=r)) +\n\n#scale_size_discrete(range=c(1,2)) +\n#scale_color_manual(values=c(\"red\",\"blue\",\"black\")) \nggsave(\"model-expectations-rrsa.pdf\",width=6.5,height=4.5)#,width=30,height=10)\n\n# plot both rRSA and uniform wRSA expectation predictions in same plot\ntoplot = merge(toplot_r,toplot_w, all=T)\nhead(toplot)\nnrow(toplot)\np_exps = ggplot(toplot, aes(x=PriorExpectation_smoothed*15, y=PosteriorExpectation_predicted*15, color=Model)) +\n geom_point() + #color=\"#00B0F6\") + #values=c(\"#F8766D\", \"#A3A500\", \"#00BF7D\", \"#E76BF3\", \"#00B0F6\")\n geom_smooth() + #color=\"#00B0F6\") +\n scale_color_manual(values=c(\"#007fb1\", \"#4ecdff\")) +\n # geom_abline(intercept=0,slope=1,color=\"gray50\") +\n scale_x_continuous(limits=c(0,15), breaks=seq(1,15,by=2), name=\"Prior expected number of objects\") +\n scale_y_continuous(limits=c(0,15), breaks=seq(1,15,by=2), name=\"Posterior predicted number of objects\")\n# geom_text(data=cors, aes(label=r)) +\n#scale_size_discrete(range=c(1,2)) +\n#scale_color_manual(values=c(\"red\",\"blue\",\"black\")) \n#ggsave(\"graphs/model-expectations.pdf\",width=5.5,height=4.5)#,width=30,height=10)\nggsave(\"model-expectations-binomial-regular.pdf\",width=6.5,height=4.5)\nggsave(\"model-expectations-uniform-regular.pdf\",width=6.5,height=4.5)\n\n\n# plot model predictions: allstate-probs\nload(\"~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/models/wonky_world/results/data/mp-uniform.RData\")\nload(\"~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/models/wonky_world/results/data/mp-binomial.RData\")\n\n# plot expectations for best basic model: \ntoplot = droplevels(subset(mp, QUD == \"how-many\" & Alternatives == \"0_basic\" & Quantifier == \"some\" & WonkyWorldPrior == .5 & State == 15))\nnrow(toplot)\n\n# adjust speaker optimality at will\ntoplot = droplevels(subset(toplot, SpeakerOptimality == 2))\nnrow(toplot)\nhead(toplot)\n\nggplot(toplot, aes(x=PriorProbability, y=PosteriorProbability)) +\n geom_point(color=\"#00B0F6\") + #values=c(\"#F8766D\", \"#A3A500\", \"#00BF7D\", \"#E76BF3\", \"#00B0F6\")\n geom_smooth(color=\"#00B0F6\") +\n # geom_abline(intercept=0,slope=1,color=\"gray50\") +\n scale_x_continuous(limits=c(0,1), name=\"Prior probability of all-state\") +\n scale_y_continuous(limits=c(0,1), name=\"Model predicted posterior probability of all-state\")\n# geom_text(data=cors, aes(label=r)) +\n\n#scale_size_discrete(range=c(1,2)) +\n#scale_color_manual(values=c(\"red\",\"blue\",\"black\")) \nggsave(\"model-allprobs.pdf\",width=5.5,height=4.5)#,width=30,height=10)\nggsave(\"model-uniform-allprobs.pdf\",width=5.5,height=4.5)#,width=30,height=10)\nsave(toplot, file=\"../data/toplot-allprobs.RData\")\n\ntoplot_w = toplot\n# get rRSA predictions for qud=how-many, alts=0_basic, spopt=2\nload(\"~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/models/complex_prior/smoothed_unbinned15/results/data/mp.RData\")\nsummary(mp)\ntoplot = droplevels(subset(mp, QUD == \"how-many\" & Alternatives == \"0_basic\" & State == 15))\nnrow(toplot)\n\n# adjust speaker optimality at will\ntoplot = droplevels(subset(toplot, SpeakerOptimality == 2))\nnrow(toplot)\nhead(toplot)\n\ntoplot_r = toplot\n\n# plot only rrsa\nggplot(toplot_r, aes(x=PriorProbability, y=PosteriorProbability)) +\n geom_point(color=\"#007fb1\") + #values=c(\"#F8766D\", \"#A3A500\", \"#00BF7D\", \"#E76BF3\", \"#00B0F6\")\n geom_smooth(color=\"#007fb1\") + #color=\"#00B0F6\") +\n #scale_color_manual(values=c(\"#007fb1\")) +\n # geom_abline(intercept=0,slope=1,color=\"gray50\") +\n scale_x_continuous(limits=c(0,1), name=\"Prior probability of all-state\") +\n scale_y_continuous(limits=c(0,1), name=\"Model predicted posterior probability of all-state\")\n# geom_text(data=cors, aes(label=r)) +\n#scale_size_discrete(range=c(1,2)) +\n#scale_color_manual(values=c(\"red\",\"blue\",\"black\")) \n#ggsave(\"graphs/model-expectations.pdf\",width=5.5,height=4.5)#,width=30,height=10)\nggsave(\"model-allprobs-rrsa.pdf\",width=6.5,height=4.5)\n\nhead(toplot_w)\nsummary(toplot_r)\ntoplot_r$Model = \"RSA\"\ntoplot_w$Model = \"wRSA\"\n\n# plot both rRSA and uniform wRSA expectation predictions in same plot\ntoplot = merge(toplot_r,toplot_w, all=T)\nhead(toplot)\nnrow(toplot)\np_probs = ggplot(toplot, aes(x=PriorProbability, y=PosteriorProbability, color=Model)) +\n geom_point() + #color=\"#00B0F6\") + #values=c(\"#F8766D\", \"#A3A500\", \"#00BF7D\", \"#E76BF3\", \"#00B0F6\")\n geom_smooth() + #color=\"#00B0F6\") +\n scale_color_manual(values=c(\"#007fb1\", \"#4ecdff\")) +\n # geom_abline(intercept=0,slope=1,color=\"gray50\") +\n scale_x_continuous(limits=c(0,1), name=\"Prior probability of all-state\") +\n scale_y_continuous(limits=c(0,1), name=\"Model predicted posterior probability of all-state\")\n# geom_text(data=cors, aes(label=r)) +\n#scale_size_discrete(range=c(1,2)) +\n#scale_color_manual(values=c(\"red\",\"blue\",\"black\")) \n#ggsave(\"graphs/model-expectations.pdf\",width=5.5,height=4.5)#,width=30,height=10)\nggsave(\"model-allprobs-binomial-regular.pdf\",width=6.5,height=4.5)\nggsave(\"model-allprobs-uniform-regular.pdf\",width=6.5,height=4.5)\n\nlibrary(gridExtra)\n# share a legend between multiple plots\ng <- ggplotGrob(p_exps + theme(legend.position=\"right\"))$grobs\nlegend <- g[[which(sapply(g, function(x) x$name) == \"guide-box\")]]\np_exps_nolegend = p_exps + theme(legend.position=\"none\")\np_probs_nolegend = p_probs + theme(legend.position=\"none\")\n\n#pdf(\"rsa-predictions-uniform.pdf\",width=10,height=4)\npdf(\"rsa-predictions.pdf\",width=10,height=4)\ngrid.arrange(p_exps_nolegend, p_probs_nolegend, legend,nrow=1,widths=unit.c(unit(.45, \"npc\"), unit(.45, \"npc\"), unit(.1, \"npc\")))\ndev.off()\n\ns = subset(r, quantifier==\"Some\" & Proportion == \"100\")\nnrow(s)\n\nlibrary(lmerTest)\nm=lmer(normresponse ~ AllPriorProbability + (1+AllPriorProbability|workerid) + (1|Item), data=s)\nsummary(m)\n\n\n\n#####################################\n# plot model predictions: wonkiness\nload(\"~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/models/wonky_world/results/data/wr-uniform.RData\")\nload(\"~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/models/wonky_world/results/data/wr-binomial.RData\")\n\n# plot expectations for best basic model: \ntoplot = droplevels(subset(wr, WonkyWorldPrior == .5 & Wonky == \"true\"))\nnrow(toplot)\ntoplot$Mode = priormodes[as.character(toplot$Item),]$Mode\n\ntoplot = droplevels(subset(toplot, SpeakerOptimality == 2))\nmod = toplot\nnrow(toplot)\nhead(toplot)\n\np_wmodel = ggplot(toplot, aes(x=PriorExpectation, y=PosteriorProbability,color=Quantifier)) +\n geom_point() + #color=\"#00B0F6\") + #values=c(\"#F8766D\", \"#A3A500\", \"#00BF7D\", \"#E76BF3\", \"#00B0F6\")\n geom_smooth() + #color=\"#00B0F6\") +\n # geom_abline(intercept=0,slope=1,color=\"gray50\") +\n scale_color_manual(values=c(\"#F8766D\",\"#00BF7D\",\"#00B0F6\")) +\n scale_x_continuous(breaks=seq(1,15,by=2),name=\"Prior expected number of objects\") +\n scale_y_continuous(breaks=seq(0,1,by=.25),name=\"Model predicted wonkiness probability\")\n\nggsave(\"model-wonkiness-uniform.pdf\",width=5.5,height=4)#,width=30,height=10)\nggsave(\"model-wonkiness-binomial.pdf\",width=5.5,height=4)#,width=30,height=10)\n\n# plot by mode\nggplot(toplot, aes(x=Mode, y=PosteriorProbability,color=Quantifier)) +\n geom_point() + #color=\"#00B0F6\") + #values=c(\"#F8766D\", \"#A3A500\", \"#00BF7D\", \"#E76BF3\", \"#00B0F6\")\n geom_smooth() + #color=\"#00B0F6\") +\n # geom_abline(intercept=0,slope=1,color=\"gray50\") +\n scale_color_manual(values=c(\"#F8766D\",\"#00BF7D\",\"#00B0F6\")) +\n scale_x_continuous(breaks=seq(1,15,by=2),name=\"Prior expected number of objects\") +\n scale_y_continuous(breaks=seq(0,1,by=.25),name=\"Model predicted wonkiness probability\")\n\n############\n# empirical wonkiness posteriors\n############\nload(\"/Users/titlis/cogsci/projects/stanford/projects/thegricean_sinking-marbles/experiments/17_sinking-marbles-normal-sliders/results/data/r.RData\")\nhead(r)\nnrow(r)\n\nggplot(r, aes(x=response, fill=quantifier)) +\n geom_histogram() +\n facet_grid(workerid~quantifier)\nggsave(\"subject-variability-wonkiness.pdf\",width=7,height=25)\n\ntoplot = aggregate(response ~ quantifier + Item + PriorExpectation, FUN=\"mean\", data=r)\ntoplot = droplevels(subset(toplot, quantifier %in% c(\"All\",\"Some\",\"None\")))\ntoplot$Quantifier = factor(tolower(toplot$quantifier), levels=c(\"all\", \"none\",\"some\"))\ntoplot$Mode = priormodes[as.character(toplot$Item),]$Mode\n\np_wempirical = ggplot(toplot, aes(x=PriorExpectation, y=response, color=Quantifier)) +\n geom_point() +\n geom_smooth() +\n scale_color_manual(values=c(\"#F8766D\",\"#00BF7D\",\"#00B0F6\")) +\n scale_x_continuous(breaks=seq(1,15,by=2),name=\"Prior expected number of objects\") +\n scale_y_continuous(breaks=seq(0,1,by=.25),name=\"Mean empirical wonkiness probability\") \nggsave(file=\"empirical-wonkiness.pdf\",width=5.5,height=4)\n\n\nlibrary(gridExtra)\n# share a legend between multiple plots\ng <- ggplotGrob(p_wmodel + theme(legend.position=\"right\"))$grobs\nlegend <- g[[which(sapply(g, function(x) x$name) == \"guide-box\")]]\np_wmodel_nolegend = p_wmodel + theme(legend.position=\"none\")\np_wempirical_nolegend = p_wempirical + theme(legend.position=\"none\")\n\n#pdf(\"rsa-predictions-uniform.pdf\",width=10,height=4)\npdf(\"wonkiness-fullplot.pdf\",width=12,height=5)\ngrid.arrange(p_wmodel_nolegend, p_wempirical_nolegend, legend,nrow=1,widths=unit.c(unit(.45, \"npc\"), unit(.45, \"npc\"), unit(.1, \"npc\")))\ndev.off()\n\n\n# scatterplot of mdoel vs empirical\nhead(toplot)\ntoplot$PosteriorProbability = toplot$response\nhead(mod)\ntoplot$Type = \"empirical\"\nmod$Type = \"model\"\n\npl = merge(mod, toplot, all=T)\nsummary(pl)\npl$Type = as.factor(as.character(pl$Type))\ntopl = pl %>% select(Item, Quantifier,PosteriorProbability,Type) %>%\n spread(Type,PosteriorProbability)\nsummary(topl)\n\nggplot(topl, aes(x=model,y=empirical,color=Quantifier,group=1)) +\n geom_point() +\n geom_smooth(method=\"lm\") +\n scale_color_manual(values=c(\"#F8766D\",\"#00BF7D\",\"#00B0F6\"))\ncor(topl$model,topl$empirical,use=\"pairwise.complete.obs\") # cor=.69\n\nlibrary(hydroGOF)\ngof(topl$model,topl$empirical,na.rm=T,do.spearman=T)\n\n#plot by mode\nggplot(toplot, aes(x=Mode, y=response, color=Quantifier)) +\n geom_point() +\n geom_smooth() +\n scale_color_manual(values=c(\"#F8766D\",\"#00BF7D\",\"#00B0F6\")) +\n scale_x_continuous(breaks=seq(1,15,by=2),name=\"Prior expected number of objects\") +\n scale_y_continuous(breaks=seq(0,1,by=.25),name=\"Mean empirical wonkiness probability\") \n\n\n\n###############\n## EMPIRICAL PLOTS\n###############\n\n# expectations\nload(\"~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/experiments/13_sinking-marbles-priordv-15/results/data/r.RData\")\n\nagr = aggregate(ProportionResponse ~ PriorExpectationProportion + quantifier + Item,data=r,FUN=mean)\n#agr$CILow = aggregate(ProportionResponse ~ PriorExpectationProportion + quantifier + Item,data=r, FUN=ci.low)$ProportionResponse\n#agr$CIHigh = aggregate(ProportionResponse ~ PriorExpectationProportion + quantifier + Item,data=r,FUN=ci.high)$ProportionResponse\n#agr$YMin = agr$ProportionResponse - agr$CILow\n#agr$YMax = agr$ProportionResponse + agr$CIHigh\n\nmin(agr[agr$quantifier == \"Some\",]$ProportionResponse)\nmax(agr[agr$quantifier == \"Some\",]$ProportionResponse)\n\np_eexps = ggplot(agr, aes(x=PriorExpectationProportion*15, y=ProportionResponse*15, color=quantifier)) +\n geom_point() +\n #geom_errorbar(aes(ymin=YMin,ymax=YMax)) +\n geom_smooth(method=\"lm\") +\n scale_color_manual(values=c(\"#F8766D\", \"black\", \"#00BF7D\", \"gray30\", \"#00B0F6\"),breaks=levels(agr$quantifier),labels=c(\"all\",\"long filler\",\"none\",\"short filler\",\"some\")) +\n scale_y_continuous(breaks=seq(1,15,by=2),name=\"Posterior mean number of objects\") +\n # geom_abline(intercept=0,slope=1,color=\"gray70\") +\n scale_x_continuous(breaks=seq(1,15,by=2),name=\"Prior mean number of objects\") \nggsave(file=\"meanresponses.pdf\",width=5,height=3.7)\n\n\n# allstate-probs\nload(\"~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/experiments/16_sinking-marbles-sliders-certain/results/data/r.RData\")\n\n# exclude people who are doing some sort of bullshit and not responding reasonably to all/none (see subject-variability.pdf for behavior on zero-slider)\ntmp = subset(r,!workerid %in% c(0,22,43,98,100,103,117,118))\nagrr = aggregate(normresponse ~ AllPriorProbability + Proportion + quantifier + Item,data=tmp,FUN=mean)\nagrr = aggregate(normresponse ~ AllPriorProbability + Proportion + quantifier + Item,data=r,FUN=mean)\nub = subset(agrr, Proportion == \"100\")\nub = droplevels(ub)\n\np_eprobs = ggplot(ub, aes(x=AllPriorProbability, y = normresponse, color=quantifier)) +\n geom_point() +\n geom_smooth(method=\"lm\") +\n scale_color_manual(values=c(\"#F8766D\", \"black\", \"#00BF7D\", \"gray30\", \"#00B0F6\"),breaks=levels(agrr$quantifier),labels=c(\"all\",\"long filler\",\"none\",\"short filler\",\"some\")) +\n scale_y_continuous(limits=c(0,1),name=\"Posterior probability of all-state \") +\n # geom_abline(intercept=0,slope=1,color=\"gray70\") +\n scale_x_continuous(limits=c(0,1),name=\"Prior probability of all-state\") \nggsave(file=\"empirical-allprobs.pdf\",width=5,height=3.7)\n\n\nlibrary(gridExtra)\n# share a legend between multiple plots\ng <- ggplotGrob(p_eexps + theme(legend.position=\"right\"))$grobs\nlegend <- g[[which(sapply(g, function(x) x$name) == \"guide-box\")]]\np_eexps_nolegend = p_eexps + theme(legend.position=\"none\")\np_eprobs_nolegend = p_eprobs + theme(legend.position=\"none\")\n\npdf(\"empirical-results.pdf\",width=10,height=4)\ngrid.arrange(p_eexps_nolegend, p_eprobs_nolegend, legend,nrow=1,widths=unit.c(unit(.45, \"npc\"), unit(.45, \"npc\"), unit(.1, \"npc\")))\ndev.off()\n\n\n# plot subejct variability for exclusion\nggplot(r[r$Proportion == \"0\",], aes(x=normresponse,fill=quantifier)) +\n geom_histogram() +\n facet_grid(workerid~quantifier) \nggsave(\"subject-variability.pdf\",width=5.5,height=4)\n\n\n\n\n\n\n\n######################\n### NOAH'S MODEL PREDICTIONS\nrsa_allstate = read.csv(file=\"~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/ndg-code/RSA-allstate.csv\",header=F)\nhead(rsa_allstate)\ncolnames(rsa_allstate) = c(\"BinomialCW\",\"PosteriorAllProbability\")\nggplot(rsa_allstate, aes(x=BinomialCW,y=PosteriorAllProbability)) +\n geom_point(color=\"#00B0F6\") +\n scale_x_continuous(limits=c(0,1), name=\"Binomial coin weight\") +\n scale_y_continuous(limits=c(0,1), name=\"Predicted posterior probability of all-state\") \nggsave(\"noahs-allstate-predictions.pdf\",width=4.5,height=3.5) \n\nrsa_expectation = read.csv(file=\"~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/ndg-code/RSA-expectation.csv\",header=F)\nhead(rsa_expectation)\ncolnames(rsa_expectation) = c(\"PriorExpectation\",\"PosteriorExpectation\")\nggplot(rsa_expectation, aes(x=PriorExpectation/15,y=PosteriorExpectation/15)) +\n geom_point(color=\"#00B0F6\") +\n scale_x_continuous(limits=c(0,1), name=\"Prior expectation\") +\n scale_y_continuous(limits=c(0,1), name=\"Predicted posterior expectation\") \nggsave(\"noahs-expectation-predictions.pdf\",width=4.5,height=3.5) \n\nrsa_expall = read.csv(file=\"~/cogsci/projects/stanford/projects/thegricean_sinking-marbles/ndg-code/RSA-expectedVsallstate.csv\",header=F)\nhead(rsa_expall)\ncolnames(rsa_expall) = c(\"PriorExpectation\",\"PosteriorExpectation\")\nggplot(rsa_expall, aes(x=PriorExpectation/15,y=PosteriorExpectation)) +\n geom_point(color=\"#00B0F6\") +\n scale_x_continuous(limits=c(0,1), name=\"Prior expectation\") +\n scale_y_continuous(limits=c(0,1), name=\"Predicted posterior probability of all-state\") \nggsave(\"noahs-allstate-predictions-bypriorexp.pdf\",width=4.5,height=3.5) \n\n\n", "meta": {"hexsha": "1e83b1f2eda02c5f87df4cdafdeabd2ede72310a", "size": 21567, "ext": "r", "lang": "R", "max_stars_repo_path": "writing/_2015/_journal_cognition/rscripts/plots.r", "max_stars_repo_name": "thegricean/sinking-marbles", "max_stars_repo_head_hexsha": "ccfb17f097b444306e3b559e40ab9d59da84387a", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "writing/_2015/_journal_cognition/rscripts/plots.r", "max_issues_repo_name": "thegricean/sinking-marbles", "max_issues_repo_head_hexsha": "ccfb17f097b444306e3b559e40ab9d59da84387a", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "writing/_2015/_journal_cognition/rscripts/plots.r", "max_forks_repo_name": "thegricean/sinking-marbles", "max_forks_repo_head_hexsha": "ccfb17f097b444306e3b559e40ab9d59da84387a", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.3806451613, "max_line_length": 222, "alphanum_fraction": 0.7403440441, "num_tokens": 6696, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6187804337438501, "lm_q2_score": 0.5698526514141571, "lm_q1q2_score": 0.3526136708121351}} {"text": "subroutine inddup(x,y,n,rw,frac,dup)\nimplicit double precision(a-h,o-z)\nlogical dup(n)\ndimension x(n), y(n), rw(4)\n\nxtol = frac*(rw(2)-rw(1))\nytol = frac*(rw(4)-rw(3))\n\ndup(1) = .false.\ndo i = 2,n {\n\tdup(i) = .false.\n\tdo j = 1,i-1 {\n\t\tdx = abs(x(i)-x(j))\n\t\tdy = abs(y(i)-y(j))\n\t\tif(dx < xtol & dy < ytol) {\n\t\t\tdup(i) = .true.\n\t\t\tbreak\n\t\t}\n\t}\n}\n\nreturn\nend\n", "meta": {"hexsha": "a01a2080b4f6a5b87dccc88d934eb9a0b5f21714", "size": 356, "ext": "r", "lang": "R", "max_stars_repo_path": "VisUncertainty/bin/Debug/R-3.4.4/library/deldir/code.discarded/inddup.r", "max_stars_repo_name": "hyeongmokoo/SAAR_beta1", "max_stars_repo_head_hexsha": "7406f30d7f39a03e8494b2171c2bc09904a36f62", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-08-23T15:35:47.000Z", "max_stars_repo_stars_event_max_datetime": "2020-11-24T12:20:59.000Z", "max_issues_repo_path": "VisUncertainty/bin/Debug/R-3.4.4/library/deldir/code.discarded/inddup.r", "max_issues_repo_name": "hyeongmokoo/SAAR_beta1", "max_issues_repo_head_hexsha": "7406f30d7f39a03e8494b2171c2bc09904a36f62", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 2, "max_issues_repo_issues_event_min_datetime": "2020-08-17T15:14:11.000Z", "max_issues_repo_issues_event_max_datetime": "2020-09-23T21:55:49.000Z", "max_forks_repo_path": "VisUncertainty/bin/Debug/R-3.4.4/library/deldir/code.discarded/inddup.r", "max_forks_repo_name": "hyeongmokoo/SAAR_beta1", "max_forks_repo_head_hexsha": "7406f30d7f39a03e8494b2171c2bc09904a36f62", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 1, "max_forks_repo_forks_event_min_datetime": "2020-11-04T05:34:16.000Z", "max_forks_repo_forks_event_max_datetime": "2020-11-04T05:34:16.000Z", "avg_line_length": 14.8333333333, "max_line_length": 36, "alphanum_fraction": 0.5421348315, "num_tokens": 152, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES\n\n", "lm_q1_score": 0.6224593312018546, "lm_q2_score": 0.5660185351961015, "lm_q1q2_score": 0.3523235188660187}} {"text": "#' barefootr: A package for holding useful functions for Eric\n#'\n#' I use this package to hold some functions that are useful to me.\n#' \n#' @section barefootr functions:\n#' \n#' The functions here make up a mix of tools to calculate and estimate modern suficial processes and back-calculate those processes in ancient rivers. \n#' \n#' \\code{settle} calculates the settling velocity of particles following the formulation by Dietrich (1982).\n#' \n#' \\code{lynds_one} estimates ancient river slope using the first method described by Lynds et al. (2014)\n#' \n#' \\code{lynds_two} estimates ancient river slope using the second method described by Lynds et al. (2014)\n#' \n#' \\code{lynds_three} estimates ancient river slope using the third method described by Lynds et al. (2014)\n#'\n#' \\code{xset2H} estimates ancient river dune heights based on cross-set thicknesses. Methods from Leclair and Paola.\n#' \n#' \\code{H2h} estimates ancient river depths based on dune heights. Methods from Bradley and Venditti.\n#' \n#' \\code{xset2depthSimple} estimates ancient river depths directly from cross-set thicknesses using the simplest assumptions. Methods from Leclair, Paola, and Bradley and Venditti.\n#'\n#' \\code{azStringConvert} Azimuth conversion for 'quadrant' based strike/trend measurements.\n#' \n#' \n#' \n#' \n#' \n#' \n#' \n#' @docType package\n#' @name barefootr\nNULL", "meta": {"hexsha": "54545afef5aa510a15139677ae1858cc2f95d241", "size": 1352, "ext": "r", "lang": "R", "max_stars_repo_path": "R/barefootr.r", "max_stars_repo_name": "ericbarefoot/barefootr", "max_stars_repo_head_hexsha": "f6cf7682f27551bc6b1aaabdcb8f50b31fcc6e9d", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "R/barefootr.r", "max_issues_repo_name": "ericbarefoot/barefootr", "max_issues_repo_head_hexsha": "f6cf7682f27551bc6b1aaabdcb8f50b31fcc6e9d", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "R/barefootr.r", "max_forks_repo_name": "ericbarefoot/barefootr", "max_forks_repo_head_hexsha": "f6cf7682f27551bc6b1aaabdcb8f50b31fcc6e9d", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 40.9696969697, "max_line_length": 180, "alphanum_fraction": 0.75, "num_tokens": 335, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6619228758499942, "lm_q2_score": 0.5312093733737563, "lm_q1q2_score": 0.3516196361020301}} {"text": "# The MIT License (MIT)\n# Copyright (c) 2017 Louise AC Millard, MRC Integrative Epidemiology Unit, University of Bristol\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n# documentation files (the \"Software\"), to deal in the Software without restriction, including without\n# limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\n# the Software, and to permit persons to whom the Software is furnished to do so, subject to the following\n# conditions:\n#\n# The above copyright notice and this permission notice shall be included in all copies or substantial portions\n# of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED\n# TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF\n# CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n# DEALINGS IN THE SOFTWARE.\n\n# splits the pheno into 3 bins with the cut points between values rather at the exact value for the quantile\nequalSizedBins <- function(phenoAvg) {\n\n\t## equal sized bins \n q = quantile(phenoAvg, probs=c(1/3,2/3), na.rm=TRUE)\n\n\tminX = min(phenoAvg, na.rm=TRUE)\n\tmaxX = max(phenoAvg, na.rm=TRUE)\n\n\tphenoBinned = phenoAvg;\n\tif (q[1]==minX) {\n\t\t# edge case - quantile value is lowest value\n\n\t\t# assign min value as cat1\n\t\tidx1 = which(phenoAvg==q[1]);\n\t\tphenoBinned[idx1] = 0;\n\n\t\t# divide remaining values into cat2 and cat3\n\t\tphenoAvgRemaining = phenoAvg[which(phenoAvg!=q[1])];\n\t\tqx = quantile(phenoAvgRemaining, probs=c(0.5), na.rm=TRUE)\n\t\tminXX = min(phenoAvgRemaining, na.rm=TRUE)\n\t\tmaxXX =\tmax(phenoAvgRemaining, na.rm=TRUE)\n\n\t\tif (qx[1]==minXX) {\n\t\t\t# edge case again - quantile value is lowest value\n\t\t\tidx2 = which(phenoAvg==qx[1]);\n\t\t\tidx3 = which(phenoAvg>qx[1]);\n\t\t\tcat(\"Bin 1: ==\", q[1],\", bin 2: ==\",qx[1], \"bin 3: >\", qx[1], \" || \", sep=\"\")\n\t\t}\n\t\telse if (qx[1]==maxXX) {\n\t\t\t# edge case again - quantile value is max value\n\t\t\tidx2 = which(phenoAvgq[1]);\n\t\t\tidx3 = which(phenoAvg==qx[1]);\n\t\t\tcat(\"Bin 1: ==\", q[1],\", bin 2: > \",q[1], \" AND <\", qx[1] , \"bin 3: ==\", qx[1], \" || \", sep=\"\")\n\t\t}\n\t\telse {\n\t\t\tidx2 = which(phenoAvgq[1]);\n\t\t\tidx3 = which(phenoAvg>=qx[1]);\n\t\t\tcat(\"Bin 1: ==\", q[1],\", bin 2: > \",q[1], \" AND <\", qx[1] , \"bin 3: >=\", qx[1], \" || \", sep=\"\")\n\t\t}\n\t\tphenoBinned[idx2] = 1;\n phenoBinned[idx3] = 2;\n\t}\n\telse if (q[2]==maxX) {\n\t\t# edge case - quantile value is highest value\n\n\t\t# assign max value as cat3\n\t\tidx3 = which(phenoAvg==q[2]);\n\t\tphenoBinned[idx3] = 2;\n\n\t\t# divide remaining values into cat1 and cat2\n\t\tphenoAvgRemaining = phenoAvg[which(phenoAvg!=q[2])];\n qx = quantile(phenoAvgRemaining, probs=c(0.5), na.rm=TRUE)\n\t\tminXX = min(phenoAvgRemaining, na.rm=TRUE)\n maxXX = max(phenoAvgRemaining, na.rm=TRUE)\n\n\t\tif (qx[1]==minXX) {\n\t\t\t# edge case again - quantile value is lowest value\n idx1 = which(phenoAvg==qx[1]);\n idx2 = which(phenoAvg>qx[1] & phenoAvg\", qx[1], \" AND < \", q[2], \", bin 3: ==\", q[2], \" || \", sep=\"\")\n }\n else if\t(qx[1]==maxXX) {\n\t\t\t# edge case again - quantile value is max value\n idx1 = which(phenoAvg=qx[1] & phenoAvg=\", qx[1], \" AND < \", q[2], \", bin 3: ==\", q[2], \" || \", sep=\"\")\n\t\t}\n\n phenoBinned[idx1] = 0;\n phenoBinned[idx2] = 1;\n\t}\n else if (q[1] == q[2]) {\n\t\t# both quantiles correspond to the same value so set \n\t\t# cat1 as < this value, cat2 as exactly this value and\n\t\t# cat3 as > this value\n \tphenoBinned = phenoAvg;\n \tidx1 = which(phenoAvgq[2]);\n phenoBinned[idx1] = 0;\n phenoBinned[idx2] = 1;\n phenoBinned[idx3] = 2;\n\n\t\tcat(\"Bin 1: <\", q[1], \", bin 2: ==\", q[2], \", bin 3: >\", q[2], \" || \", sep=\"\")\n \t}\n else {\n\t\t# standard case - split the data into three roughly equal parts where\n\t\t# cat1=q2\n \tphenoBinned = phenoAvg;\n idx1 = which(phenoAvg=q[1] & phenoAvg=q[2]);\n phenoBinned[idx1] = 0;\n phenoBinned[idx2] = 1;\n phenoBinned[idx3] = 2;\n\n\t\tcat(\"Bin 1: <\", q[1], \", bin 2: >=\", q[1], \"AND < \", q[2] ,\", bin 3: >=\", q[2], \" || \", sep=\"\")\n\t}\n\n\tcat(\"cat N: \", length(idx1),\", \",length(idx2),\", \",length(idx3), \" || \", sep=\"\");\n\t\n\treturn(phenoBinned);\n}\n\n", "meta": {"hexsha": "fe4624ec6b78174dc81f2fba1e1f36d9cd7a4e3c", "size": 5240, "ext": "r", "lang": "R", "max_stars_repo_path": "WAS/equalSizedBins.r", "max_stars_repo_name": "kevmanderson/PHESANT", "max_stars_repo_head_hexsha": "cddb747de7b7ce91a687382bb9684ab43d4008a9", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 69, "max_stars_repo_stars_event_min_datetime": "2017-02-27T00:47:58.000Z", "max_stars_repo_stars_event_max_datetime": "2022-03-14T15:42:01.000Z", "max_issues_repo_path": "WAS/equalSizedBins.r", "max_issues_repo_name": "kevmanderson/PHESANT", "max_issues_repo_head_hexsha": "cddb747de7b7ce91a687382bb9684ab43d4008a9", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 27, "max_issues_repo_issues_event_min_datetime": "2017-05-07T13:39:01.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-25T12:23:55.000Z", "max_forks_repo_path": "WAS/equalSizedBins.r", "max_forks_repo_name": "kevmanderson/PHESANT", "max_forks_repo_head_hexsha": "cddb747de7b7ce91a687382bb9684ab43d4008a9", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 47, "max_forks_repo_forks_event_min_datetime": "2017-02-27T12:25:25.000Z", "max_forks_repo_forks_event_max_datetime": "2022-02-02T22:03:16.000Z", "avg_line_length": 40.6201550388, "max_line_length": 111, "alphanum_fraction": 0.575, "num_tokens": 1690, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6859494421679929, "lm_q2_score": 0.5117166047041654, "lm_q1q2_score": 0.35101171954492155}} {"text": "#R Vignere Functions Document\r\n\r\nalphabet <- c(\"a\", \"b\", \"c\", \"d\", \"e\", \"f\", \"g\", \"h\", \"i\", \"j\", \"k\",\r\n\"l\", \"m\", \"n\", \"o\", \"p\", \"q\", \"r\", \"s\",\r\n\"t\", \"u\", \"v\", \"w\", \"x\", \"y\", \"z\")\r\n\r\nenglish_frequencies <- data.frame(\r\n letters = alphabet,\r\n frequencies = c(8.4966, 2.0720, 4.5388, 3.3844, 11.1607, 1.8121, 2.4705,\r\n 3.0034, 7.5448, 0.1965, 1.1016, 5.4893, 3.0129, 6.6544, 7.1635, 3.1671,\r\n 0.1962, 7.5809, 5.7351, 6.9509, 3.6308, 1.0074, 1.2899, 0.2902, 1.7779,\r\n 0.2722) / 100\r\n)\r\n\r\n#Removes all punctuation, upper case letters and spaces from a string\r\nformat_func <- function(string) {\r\n string <- gsub(\"[[:punct:][:blank:]]\", \"\", string)\r\n string <- gsub(\"[0-9]\", \"\", string)\r\n string <- tolower(string)\r\n return(string)\r\n}\r\n\r\n#Function returns the encrypted text by applying the vigenere cipher\r\n#Function requires a key, and a string, returns the ciphertext\r\nencrypt_func <- function(text, key) {\r\n encrypted <- c()\r\n #loop to get alphabetical indexes of the characters in the text\r\n split_text <- strsplit(text, \"\")[[1]] #creates a character class\r\n for (i in 1:nchar(text)) {\r\n letter_index <- which(alphabet %in% split_text[i])\r\n j <- i %% nchar(key)\r\n if (j == 0) {\r\n j <- nchar(key)\r\n }\r\n key_index <- which(alphabet %in% substring(key, j, j))\r\n #applying the relevant shift to the letters, using the vigenere cipher\r\n alphabet_index <- (letter_index + key_index - 2) %% length(alphabet) + 1\r\n encrypted <- paste(encrypted, alphabet[alphabet_index], sep = \"\")\r\n }\r\n return(encrypted)\r\n}\r\n\r\ndecrypt <- function(ciphertext, key) {\r\n decrypted <- c()\r\n for (i in 1:nchar(ciphertext)) {\r\n j <- i %% nchar(key)\r\n if (j == 0) {\r\n j <- nchar(key)\r\n }\r\n key_index <- which(alphabet %in% substring(key, j, j))\r\n cipher_index <- which(alphabet %in% substring(ciphertext, i, i))\r\n alphabet_index <- (cipher_index - key_index) %% 26 + 1\r\n decrypted <- paste(decrypted, alphabet[alphabet_index], sep = \"\")\r\n }\r\n return(decrypted)\r\n}\r\n\r\n#Kasiski Algorithm Functions to find the key length\r\n\r\n\r\n#Repeats function, finds all n letter repeats within the ciphertext\r\n# then counts their frequency, finds the spacing between repeats,\r\n# then finds the most comming factor of all the spacings (kas_mode)\r\nrepeats <- function(ciphertext, n) {\r\n elements <- c()\r\n indexes <- list()\r\n spacings <- list()\r\n for (i in 1:nchar(ciphertext)) {\r\n if (i <= nchar(ciphertext) - n + 1) {\r\n substr <- substring(ciphertext, i, i + n - 1)\r\n if (substr %in% elements == FALSE) {\r\n elements <- c(elements, substr)\r\n data <- gregexpr(substr, ciphertext)\r\n data2 <- list(\"attributes<-\" (data[[1]], NULL))\r\n indexes <- append(indexes, data2)\r\n if (length(data2[[1]]) > 1) {\r\n diff <- c()\r\n for (j in 1:(length(data2[[1]]) - 1)) {\r\n for (k in 1:(length(data2[[1]]) - j)) {\r\n diff <- c(diff, data2[[1]][j + k] - data2[[1]][j])\r\n }\r\n }\r\n spacings <- append(spacings, diff)\r\n }\r\n }\r\n }\r\n }\r\n factors_matrix <- c()\r\n for (i in 2:nchar(ciphertext)) {\r\n counts <- 0\r\n for (d in spacings) {\r\n if ((d %% i) == 0) {\r\n counts <- counts + 1\r\n }\r\n }\r\n if (counts != 0) {\r\n factors_matrix <- rbind(factors_matrix, c(i, counts))\r\n }\r\n }\r\n kas_mode <- 0\r\n mode_val <- 0 \r\n for (r in 1:nrow(factors_matrix)) {\r\n if (factors_matrix[r, 2] >= mode_val) {\r\n kas_mode <- factors_matrix[r, 1]\r\n mode_val <- factors_matrix[r, 2]\r\n }\r\n }\r\n return(kas_mode)\r\n}\r\n\r\n\r\n#Function takes every nth letter starting from index m,\r\n#where m is in range 0:n-1\r\nstr_subset <- function(junk, n, m) {\r\n ifelse(n == 1, junk,\r\npaste(strsplit(junk, split = NULL)[[1]][(1:nchar(junk)) %% n == m],\r\ncollapse = \"\"))\r\n}\r\n\r\n\r\n#Function below returns a list of the ciphertext split into n=key_length\r\n#subsections, so that letter frequency analysis can be used\r\nnth_letter <- function(key_length, ciphertext) {\r\n list_of_substrings <- c()\r\n sub_indexes <- 1:(key_length - 1)\r\n sub_indexes <- append(sub_indexes, 0)\r\n if (key_length == 1) {\r\n sub_indexes <- c(1)\r\n }\r\n for (i in sub_indexes) {\r\n list_of_substrings <- append(list_of_substrings,\r\n str_subset(ciphertext, key_length, i))\r\n }\r\n return(list_of_substrings)\r\n}\r\n\r\nsub_letter_totals <- function(key_length, ciphertext) {\r\n sorted_frequencies <- c()\r\n list_of_substrings <- nth_letter(key_length, ciphertext)\r\n index <- 1\r\n for (sub in list_of_substrings) {\r\n letter_freqs <- c()\r\n sub_split <- strsplit(sub, \"\")[[1]]\r\n for (letter in alphabet) {\r\n count <- length(grep(letter, sub_split))\r\n letter_freqs <- append(letter_freqs, count)\r\n }\r\n sorted_frequencies[[index]] <- letter_freqs\r\n index <- index + 1\r\n }\r\n return(sorted_frequencies)\r\n}\r\n\r\npercentages <- function(vec_of_vecs) {\r\n int <- 1\r\n s_percs <- c()\r\n for (i in vec_of_vecs) {\r\n j <- i / sum(i)\r\n s_percs[[int]] <- j\r\n int <- int + 1\r\n }\r\n return(s_percs)\r\n}\r\n\r\nchi_squared <- function(eng_freqs, sub_percs) {\r\n chis <- c()\r\n ind <- 1\r\n for (sublist in sub_percs) {\r\n chi_stats <- c()\r\n for (i in 1:length(alphabet)) {\r\n chi <- 0\r\n if (i == 1) {\r\n series <- i:26\r\n }\r\n else {\r\n series <- (28 - i):26\r\n series <- c(series, 1:(27 - i))\r\n }\r\n for (j in seq_along(sublist)) {\r\n value <- ((sublist[j] - eng_freqs[[2]][series[j]]) ^ 2) / (eng_freqs[[2]][series[j]])\r\n chi <- chi + value\r\n }\r\n chi_stats <- c(chi_stats, chi)\r\n }\r\n chis[[ind]] <- chi_stats\r\n ind <- ind + 1\r\n }\r\n return(chis)\r\n}\r\n\r\n#Function which returns the n most likely letters for every key letter.\r\n#It takes in two arguments, the vector list of chi squared values, and n.\r\n#It returns a vector, of length == key length.\r\nlikely_letters <- function(chi_vector, n) {\r\n n_likely <- c()\r\n step <- 1\r\n for (chis in chi_vector) {\r\n letters <- c()\r\n sorted_freqs <- chis[order(chis)]\r\n for (int in 1:n) {\r\n letters <- c(letters, alphabet[match(sorted_freqs[int], chis)])\r\n }\r\n n_likely[[step]] <- letters\r\n step <- step + 1\r\n }\r\n return(n_likely)\r\n}\r\n\r\n### Twist Algorithm Implementation, used to find the key length\r\n\r\ntwist_subsets_func <- function(key_limit, text) {\r\n all_key_lengths <- c()\r\n for (m in 1:(key_limit + 1)) {\r\n nth_sub <- sub_letter_totals(m, text)\r\n perc <- percentages(nth_sub)\r\n all_key_lengths[[m]] <- perc\r\n }\r\n return(all_key_lengths)\r\n}\r\n\r\ntwists <- function(twist_subsets) {\r\n twists <- c()\r\n for (c in 1:length(twist_subsets)) {\r\n twist <- 0\r\n for (r in 1:length(twist_subsets[[c]])) {\r\n list_of_percs <- sort(twist_subsets[[c]][r][[1]], decreasing = TRUE)\r\n twist <- twist + sum(list_of_percs[1:13]) - sum(list_of_percs[14:26])\r\n }\r\n twist <- twist * (100 / c)\r\n twists <- c(twists, twist)\r\n }\r\n return(twists)\r\n}\r\n\r\ntwistplus <- function(twists) {\r\n twistplus <- c()\r\n for (i in seq_along(twists)) {\r\n subtract <- 0\r\n if (i != length(twists)) {\r\n for (j in 1:i) {\r\n subtract <- subtract + (twists[j]/(i))\r\n }\r\n number <- twists[i + 1] - subtract\r\n twistplus <- c(twistplus, number, i + 1)\r\n }\r\n }\r\n mode_value <- 0\r\n sequence <- seq_along(twistplus)\r\n integers <- which(sequence %% 2 == 1)\r\n for (j in integers) {\r\n if(twistplus[j] > mode_value) {\r\n mode <- twistplus[j + 1]\r\n mode_value <- twistplus[j]\r\n }\r\n }\r\n return (mode)\r\n}\r\n\r\n############################\r\n#Testing\r\n############################\r\n\r\n#Code below demonstrates how the Vigenere Cipher is solved with the twistplus algorithm\r\n#to identify the key length.\r\n\r\nnormal_text <- \"there are various kinds of certainty. a belief is psychologically certain when the subject who has it is supremely convinced of its truth. certainty in this sense is similar to incorrigibility, which is the property a belief has of being such that the subject is incapable of giving it up.but psychological certainty is not the same thing as incorrigibility. a belief can be certain in this sense without being incorrigible; this may happen, for example, when the subject receives a very compelling bit of counterevidence to the (previously) certain belief and gives it up for that reason.\"\r\nkeyword <- \"notebook\"\r\n\r\nc_text <- encrypt_func(format_func(normal_text), keyword)\r\ntwists_a <- twists(twist_subsets_func(8, c_text))\r\nmode <- twistplus(twists_a)\r\nprint(mode)\r\n\r\noutput <- sub_letter_totals(mode, c_text)\r\npercs <- percentages(output)\r\nchi_vals <- chi_squared(english_frequencies, percs)\r\nlikely <- likely_letters(chi_vals, 3)\r\nprint(likely)\r\n\r\ndecryp <- decrypt(c_text, \"notebook\")\r\nprint(decryp)\r\n\r\n\r\n#######################\r\n#Testing the Kasiski Algorithm\r\n#######################\r\n\r\n#Try different length ciphertexts and keys to determine the effectiveness of the Kasiski Algorithm\r\n#compared to the Twistplus algorithm. You may find different results for the function repeats(text, n), when\r\n#changing 'n' the length of the repeated fragment of text.\r\nrepeats(c_text, 5)\r\n", "meta": {"hexsha": "afe057a59f2f8adbc32d6303a8e4f4ad83684982", "size": 9884, "ext": "r", "lang": "R", "max_stars_repo_path": "Vignere_Functions.r", "max_stars_repo_name": "MFarchive/Vigenere-Cipher", "max_stars_repo_head_hexsha": "914849d47a37e95bb24bcd488b01bd82fb7be56f", "max_stars_repo_licenses": ["Unlicense"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "Vignere_Functions.r", "max_issues_repo_name": "MFarchive/Vigenere-Cipher", "max_issues_repo_head_hexsha": "914849d47a37e95bb24bcd488b01bd82fb7be56f", "max_issues_repo_licenses": ["Unlicense"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "Vignere_Functions.r", "max_forks_repo_name": "MFarchive/Vigenere-Cipher", "max_forks_repo_head_hexsha": "914849d47a37e95bb24bcd488b01bd82fb7be56f", "max_forks_repo_licenses": ["Unlicense"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 33.8493150685, "max_line_length": 607, "alphanum_fraction": 0.556353703, "num_tokens": 2627, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6076631698328916, "lm_q2_score": 0.5774953651858118, "lm_q1q2_score": 0.3509226641726137}} {"text": "\\name{psm_analysis_weighted}\r\n\\alias{psm_analysis_weighted}\r\n\r\n\\title{\r\nWeighted van Westendorp Price Sensitivity Meter Analysis (PSM)\r\n}\r\n\r\n\\description{\r\n\\code{psm_analysis_weighted()} performs a \\bold{weighted} analysis\r\n of consumer price preferences and price sensitivity known as\r\n \\bold{van Westendorp Price Sensitivity Meter (PSM)}. The function\r\n requires a sample design from the \\pkg{survey} package as the\r\n main input. Custom weights or sample designs from other packages\r\n are not supported.\r\n\r\n To run a PSM analysis \\bold{without} weighting, use the function\r\n \\code{\\link{psm_analysis}}.\r\n\r\n}\r\n\r\n\\usage{\r\npsm_analysis_weighted(\r\n toocheap, cheap, expensive, tooexpensive,\r\n design,\r\n validate = TRUE,\r\n interpolate = FALSE,\r\n interpolation_steps = 0.01,\r\n intersection_method = \"min\",\r\n pi_cheap = NA, pi_expensive = NA,\r\n pi_scale = 5:1,\r\n pi_calibrated = c(0.7, 0.5, 0.3, 0.1, 0))\r\n}\r\n\r\n\\arguments{\r\n \\item{toocheap, cheap, expensive, tooexpensive}{Names\r\n of the variables in the data.frame/matrix that contain the\r\n survey data on the respondents' \"too cheap\", \"cheap\",\r\n \"expensive\" and \"too expensive\" price preferences.\r\n\r\n If the \\code{toocheap} price was not assessed, a\r\n variable of NAs can be used instead. If \\code{toocheap}\r\n is NA for all cases, it is possible to calculate the Point of\r\n Marginal Expensiveness and the Indifference Price Point, but it\r\n is impossible to calculate the Point of Marginal Cheapness and\r\n the Optimal Price Point.}\r\n \\item{design}{A survey design which has been created by the\r\n function \\code{\\link{svydesign}()} from the \\pkg{survey}\r\n package. The data that is used as an input of \\code{svydesign()}\r\n must include all the variable names for \\code{toocheap},\r\n \\code{cheap}, \\code{expensive} and \\code{tooexpensive} variables\r\n specified above.}\r\n \\item{validate}{logical. should only respondents with\r\n consistent price preferences (too cheap < cheap < expensive\r\n < too expensive) be considered in the analysis?}\r\n \\item{interpolate}{logical. should interpolation of the price\r\n curves be applied between the actual prices given by the\r\n respondents? If interpolation is enabled, the output appears\r\n less bumpy in regions with sparse price information. If the\r\n sample size is sufficiently large, interpolation should not\r\n be necessary.}\r\n \\item{interpolation_steps}{numeric. if \\code{interpolate} is\r\n \\code{TRUE}: the size of the interpolation steps. Set by\r\n default to 0.01, which should be appropriate for most goods\r\n in a price range of 0-50 USD/Euro.}\r\n \\item{intersection_method}{\"min\" (default), \"max\", \"mean\" or\r\n \"median\". defines the method how to determine the price\r\n points (range, indifference price, optimal price) if there\r\n are multiple possible intersections of the price curves.\r\n \"min\" uses the lowest possible prices, \"max\" uses the\r\n highest possible prices, \"mean\" calculates the mean among\r\n all intersections and \"median\" uses the median of all\r\n possible intersections}\r\n \\item{pi_cheap, pi_expensive}{Only required for the Newton\r\n Miller Smith extension. Names of the variables in the data\r\n that contain the survey data on the respondents' purchase\r\n intent at their individual cheap/expensive price.}\r\n \\item{pi_scale}{Only required for the Newton Miller Smith\r\n extension. Scale of the purchase intent variables pi_cheap and\r\n pi_expensive. By default assuming a five-point scale with 5\r\n indicating the highest purchase intent.}\r\n \\item{pi_calibrated}{Only required for the Newton Miller Smith\r\n extension. Calibrated purchase probabilities that are assumed\r\n for each value of the purchase intent scale. Must be the same\r\n order as the pi_scale variable so that the first value of\r\n pi_calibrated corresponds to the first value in the pi_scale\r\n variable. Default values are taken from the Sawtooth Software\r\n PSM implementation in Excel: 70\\% for the best value of the\r\n purchase intent scale, 50\\% for the second best value,\r\n 30\\% for the third best value (middle of the scale), 10\\%\r\n for the fourth best value and 0\\% for the worst value.}\r\n}\r\n\r\n\r\n\\details{\r\nThe main logic of the Price Sensitivity Meter Analysis is\r\nexplained in the documentation of the \\code{\\link{psm_analysis}}\r\nfunction. The \\code{psm_analysis_weighted} performs the same\r\nanalysis, but weights the survey data according to a known\r\npopulation.}\r\n\r\n\\value{\r\nThe function output consists of the following elements:\r\n\r\n \\item{\\code{data_input}:}{\\code{data.frame} object. Contains\r\n the data that was used as an input for the analysis.}\r\n \\item{\\code{validated}:}{\\code{logical} object. Indicates\r\n whether the \\code{\"validate\"} option has been used (to\r\n exclude cases with intransitive price preferences).}\r\n \\item{\\code{invalid_cases}:}{\\code{numeric} object. Number\r\n of cases with intransitive price preferences.}\r\n \\item{\\code{total_sample}:}{\\code{\"numeric\"} object.\r\n Total sample size of the input sample \\emph{before}\r\n assessing the transitivity of individual price preferences.}\r\n \\item{\\code{data_vanwestendorp}:}{\\code{data.frame} object.\r\n Output data of the Price Sensitivity Meter analysis.\r\n Contains the \\bold{weighted} cumulative distribution\r\n functions for the four price assessments (too cheap, cheap,\r\n expensive, too expensive) for all prices.}\r\n \\item{\\code{pricerange_lower}:}{\\code{numeric} object. Lower\r\n limit of the acceptable price range as defined by the\r\n Price Sensitivity Meter, also known as \\bold{point of\r\n marginal cheapness}: Intersection of the \"too cheap\" and the\r\n \"expensive\" curves.}\r\n \\item{\\code{pricerange_upper}:}{\\code{numeric} object. Upper\r\n limit of the acceptable price range as defined by the Price\r\n Sensitivity Meter, also known as \\bold{point of marginal\r\n expensiveness}: Intersection of the \"too expensive\" and the\r\n \"cheap\" curves.}\r\n \\item{\\code{idp}:}{\\code{numeric} object. \\bold{Indifference\r\n Price Point} as defined by the Price Sensitivity Meter:\r\n Intersection of the \"cheap\" and the \"expensive\" curves.}\r\n \\item{\\code{opp}:}{\\code{numeric} object. \\bold{Optimal\r\n Price Point} as defined by the Price Sensitivity Meter:\r\n Intersection of the \"too cheap\" and the \"too expensive\"\r\n curves.}\r\n \\item{\\code{weighted}:}{\\code{logical} object. Indicating\r\n if weighted data was used in the analysis. Outputs from\r\n \\code{psm_analysis_weighted()} always have the value\r\n \\code{TRUE}. When data is unweighted, use the function\r\n \\code{\\link{psm_analysis}.}}\r\n \\item{\\code{survey_design}:}{\\code{survey.design2} object.\r\n Returning the full survey design as specified with the\r\n \\code{\\link[survey]{svydesign}} function from the \\pkg{survey} package.}\r\n \\item{\\code{NMS}:}{\\code{logical} object. Indicates whether\r\n the additional analyses of the Newton Miller Smith Extension\r\n were performed.}\r\n}\r\n\r\n\\references{\r\n Van Westendorp, P (1976) \"NSS-Price Sensitivity Meter (PSM) --\r\n A new approach to study consumer perception of price\"\r\n \\emph{Proceedings of the ESOMAR 29th Congress}, 139--167. Online\r\n available at \\url{https://www.researchworld.com/a-new-approach-to-study-consumer-perception-of-price/}.\r\n\r\n Newton, D, Miller, J, Smith, P, (1993) \"A market acceptance\r\n extension to traditional price sensitivity measurement\"\r\n \\emph{Proceedings of the American Marketing Association\r\n Advanced Research Techniques Forum}.\r\n\r\n Sawtooth Software (2016) \"Templates for van Westendorp PSM for\r\n Lighthouse Studio and Excel\". Online available at\r\n \\url{https://sawtoothsoftware.com/resources/software-downloads/tools/van-westendorp-price-sensitivity-meter}\r\n}\r\n\r\n\\examples{\r\n\r\n# assuming a skewed sample with only 1/3 women and 2/3 men\r\n\r\ninput_data <- data.frame(tch = round(rnorm(n = 250, mean = 8, sd = 1.5), digits = 2),\r\n ch = round(rnorm(n = 250, mean = 12, sd = 2), digits = 2),\r\n ex = round(rnorm(n = 250, mean = 13, sd = 1), digits = 2),\r\n tex = round(rnorm(n = 250, mean = 15, sd = 1), digits = 2),\r\n gender = sample(x = c(\"male\", \"female\"),\r\n size = 250,\r\n replace = TRUE,\r\n prob = c(2/3, 1/3)))\r\n\r\n# ... and in which women have on average 1.5x the price acceptance of men\r\ninput_data$tch[input_data$gender == \"female\"] <- input_data$tch[input_data$gender == \"female\"] * 1.5\r\ninput_data$ch[input_data$gender == \"female\"] <- input_data$ch[input_data$gender == \"female\"] * 1.5\r\ninput_data$ex[input_data$gender == \"female\"] <- input_data$ex[input_data$gender == \"female\"] * 1.5\r\ninput_data$tex[input_data$gender == \"female\"] <- input_data$tex[input_data$gender == \"female\"] * 1.5\r\n\r\n# creating a sample design object using the survey package\r\n# ... assuming that gender is balanced equally in the population of 10000\r\n\r\ninput_data$gender_pop <- 5000\r\n\r\ninput_design <- survey::svydesign(ids = ~ 1, # no clusters\r\n probs = NULL, # hence no cluster samling probabilities,\r\n strata = input_data$gender, # stratified by gender\r\n fpc = input_data$gender_pop, # strata size in the population\r\n data = input_data)\r\n # data object used as input: no need to specify single variables\r\n\r\n\r\noutput_weighted_psm <- psm_analysis_weighted(toocheap = \"tch\",\r\n cheap = \"ch\",\r\n expensive = \"ex\",\r\n tooexpensive = \"tex\",\r\n design = input_design)\r\n\r\nsummary(output_weighted_psm)\r\n}\r\n\r\n", "meta": {"hexsha": "38a308ff30bea39a777c94e442773bf2cb3c55d7", "size": 9678, "ext": "rd", "lang": "R", "max_stars_repo_path": "man/psm_analysis_weighted.rd", "max_stars_repo_name": "cran/pricesensitivitymeter", "max_stars_repo_head_hexsha": "9bcdce34f9fed026c96dd28073704df239746c93", "max_stars_repo_licenses": ["MIT"], "max_stars_count": null, "max_stars_repo_stars_event_min_datetime": null, "max_stars_repo_stars_event_max_datetime": null, "max_issues_repo_path": "man/psm_analysis_weighted.rd", "max_issues_repo_name": "cran/pricesensitivitymeter", "max_issues_repo_head_hexsha": "9bcdce34f9fed026c96dd28073704df239746c93", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "man/psm_analysis_weighted.rd", "max_forks_repo_name": "cran/pricesensitivitymeter", "max_forks_repo_head_hexsha": "9bcdce34f9fed026c96dd28073704df239746c93", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 46.9805825243, "max_line_length": 111, "alphanum_fraction": 0.6980781153, "num_tokens": 2433, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. NO", "lm_q1_score": 0.7606506526772883, "lm_q2_score": 0.4610167793123159, "lm_q1q2_score": 0.35067271407909445}} {"text": "# Data exploration and models for TSM\n\nrequire(mgcv)\nrequire(data.table)\nrequire(lme4)\nrequire(MuMIn) # for dredge\nsource('scripts/findPeaksGAM.r') # for location and number of peaks\n\n\n#############\n## functions\n#############\n\n\n#############\n# Read in dataset\n#############\ndat <- fread('temp/warmingtolerance_byspecies.csv', stringsAsFactors=TRUE)\n\n# make critical the first factor\ndat$tmax_metric <- relevel(dat$tmax_metric, 'crit')\n\n\n#####################\n## Examine dataset\n#####################\n# how much data by animal type\n\tnrow(dat) # 406\n\n\t# Tmax raw\n\ti <- complete.cases(dat[,.(Realm, lat, Tmax)])\n\tsum(i)\n\tdat[i, table(Realm)]\n\tdat[i, table(animal.type, Realm)]\n\tdat[i, length(unique(Class))]\n\tdat[i, range(lat), by=Realm]\n\n\t# Tmax acclimation temp\n\ti <- complete.cases(dat[, .(Realm, lat, tmax.accsum.elev, Phylum, Class, Order, Family, Genus)])\n\tsum(i)\n\tdat[i, table(Realm)]\n\tdat[i, table(animal.type, Realm)]\n\n\t# Operative temperature\n\ti <- complete.cases(dat[, .(Realm, lat, tb_favorableGHCND95, Phylum, Class, Order, Family, Genus)])\n\tsum(i)\n\tdat[i, table(Realm)]\n\tdat[i, table(animal.type, Realm)]\n\n\t# TSM present time, without acclimation GHCND\n\ti <- complete.cases(dat[, .(Realm, lat, tmax_metric, tsm_favorableGHCND95_noacc, Phylum, Class, Order, Family, Genus)]) \n\tsum(i)\n\tdat[i, table(Realm)]\n\tdat[i, table(animal.type, Realm)]\n\n\t# TSM present time, with acclimation GHCND\n\ti <- complete.cases(dat[, .(Realm, lat, tmax_metric, tsm_favorableGHCND95, Phylum, Class, Order, Family, Genus)]) \n\tsum(i)\n\tdat[i, table(Realm)]\n\tdat[i, table(animal.type, Realm)]\n\n\n# how many phyla by habitat\naggregate(list(nphyla=dat$Phylum, nclass=dat$Class, norder=dat$Family, nfamily=dat$Family, ngenera=dat$Genus), by=list(Realm=dat$Realm), FUN=function(x) length(unique(x)))\n\n# how many classes?\n\t# Tmax acclimation temp\n\ti <- complete.cases(dat[, .(Realm, lat, tmax.accsum.elev, Phylum, Class, Order, Family, Genus)])\n\tsum(i)\n\tt(t(table(dat$Class[i])))\n\n\t# TSM present time, with acclimation\n\ti <- complete.cases(dat[, .(Realm, lat, tmax_metric, tsm_favorable, Phylum, Class, Order, Family, Genus)]) \n\ttable(dat$Class[i])\n\n\n# latitudinal range\n\t# Tmax\n\ti <- complete.cases(dat[,.(Realm, lat, Tmax, Phylum, Class, Order, Family, Genus)])\n\tsum(i)\n\taggregate(list(range=dat$lat[i]), by=list(habitat=dat$Realm[i]), FUN=range)\n\n\t# TSM present time, with acclimation\n\ti <- complete.cases(dat[, .(Realm, lat, tsm_favorableGHCND95, Phylum, Class, Order, Family, Genus)]) \n\tsum(i)\n\taggregate(list(range=dat$lat[i]), by=list(habitat=dat$Realm[i]), FUN=range)\n\n\n# acclimation effect size\n\t# acclimation temperature\ndat[Realm=='Terrestrial', summary(Tmax - tmax.accsum.elev)]\ndat[Realm=='Terrestrial', sd(Tmax - tmax.accsum.elev, na.rm=TRUE)]\n\ndat[Realm=='Marine', summary(Tmax - tmax.accsum.elev)]\ndat[Realm=='Marine', sd(Tmax - tmax.accsum.elev, na.rm=TRUE)]\n\n\n\n# odd values\n\t# tsm < 0\n\tdat[,sum(tsm_maxhr<0, na.rm=TRUE)]\n\tdat[tsm_favorable<0 | tsm_favorable95<0 | tsm_favorableGHCND95<0, .(Species, Genus, animal.type, Realm, lat, long_max, elev.grid, tmax_metric, Tmax, tmax.accsum.elev, thabmaxhr, tsm_maxhr, tsm_maxhr_accsum, tsm_favorable, tsm_favorable95, tsm_favorableGHCND95)]\n\n\n##################################\n# Average in bands and write out\n##################################\n\n# averages near equator vs. farther\n\tdat[lat > -10 & lat < 10 & Realm=='Terrestrial', .(mean(tsm_favorableGHCND95), sd(tsm_favorableGHCND95)/.N, .N)]\n\tdat[lat > -3 & lat < 3 & Realm=='Terrestrial', .(mean(tsm_favorableGHCND95), sd(tsm_favorableGHCND95)/.N, .N)]\n\tdat[(lat > -35 & lat < -25) & Realm=='Terrestrial', .(mean(tsm_favorableGHCND95), sd(tsm_favorableGHCND95)/.N, .N)]\n\tdat[(lat > 20 & lat < 30) & Realm=='Terrestrial', .(mean(tsm_favorableGHCND95), sd(tsm_favorableGHCND95)/.N, .N)]\n\tdat[((lat > -35 & lat < -15) | (lat > 15 & lat < 35)) & Realm=='Terrestrial', .(mean(tsm_favorableGHCND95), sd(tsm_favorableGHCND95)/.N, .N)]\n\t\n# average in bands\n\tTSMbylat <- dat[Realm=='Terrestrial' & !is.na(tsm_favorableGHCND95), .(mean=mean(tsm_favorableGHCND95), se=sd(tsm_favorableGHCND95)/.N, n=.N), by=.(latband=floor(lat/10)*10+5)]\n\n\t\t# small plot to check\n\t\tsetkey(TSMbylat, latband)\n\t\tTSMbylat[,plot(latband, mean, type='o', pch=16, cex=0.5)]\n\t\tTSMbylat[,arrows(latband, mean-se, latband, mean+se, length=0, angle=90, code=3)]\n\n# write out\nwrite.csv(TSMbylat, file='temp/warmingtolerance_bylatband_land.csv', row.names=FALSE)\n\n#############\n# Models\n#############\n\n#### projections dataframe\n\tnewdat <- data.frame(Realm=rep(c('Marine', 'Terrestrial'), c(161,161)), lat=rep(-80:80, 2)) # for projection onto a regular vector of latitudes\n\t\tnewdat$tmax_metric <- 'crit'\n\n#### models for body temperature (Tb)\t\t\n\t# present-time body temperature in favorable microclimates, 95% max hr with GHCND\n\t\ti <- complete.cases(dat[,c('Realm', 'lat', 'tb_favorableGHCND95', 'Phylum', 'Class', 'Order', 'Family', 'Genus')]); sum(i); nrow(dat)\n\tmodTbGHCND95dat <- dat[i,]\n\tmodTbGHCND95 <- uGamm(tb_favorableGHCND95 ~ Realm + s(lat, by=Realm), random=list(Phylum=~1, Class=~1, Order=~1, Family=~1, Genus=~1), data=modTbGHCND95dat) # use uGamm instead of gamm, since former can be used with dredge. Just a wrapper function for gamm.\n#\t\tsummary(modTbGHCND95$gam)\n\t\n\t\t## predictions from GAMM\n\t\ttemp <- predict(modTbGHCND95$gam, newdata=newdat, se.fit=TRUE)\n\t\tnewdat$tb_favorableGHCND95 <- temp$fit\n\t\tnewdat$tb_favorableGHCND95se <- temp$se.fit\n\t\t\n\t\t\t# plot predictions\n#\t\t\tplot(tb_favorableGHCND95 ~ lat, data=newdat[newdat$Realm=='Terrestrial',], type='l', col='green', ylim=c(-10,30), xlim=c(-80,80))\n#\t\t\t\tlines(tb_favorableGHCND95 + tb_favorableGHCND95se ~ lat, data=newdat[newdat$Realm=='Terrestrial',], col='green', lty=2)\n#\t\t\t\tlines(tb_favorableGHCND95 - tb_favorableGHCND95se ~ lat, data=newdat[newdat$Realm=='Terrestrial',], col='green', lty=2)\n#\t\t\tlines(tb_favorableGHCND95 ~ lat, data=newdat[newdat$Realm=='Marine',], col='blue')\n#\t\t\t\tlines(tb_favorableGHCND95 - tb_favorableGHCND95se ~ lat, data=newdat[newdat$Realm=='Marine',], col='blue', lty=2)\n#\t\t\t\tlines(tb_favorableGHCND95 + tb_favorableGHCND95se ~ lat, data=newdat[newdat$Realm=='Marine',], col='blue', lty=2)\n#\n#\t\t\tpoints(tb_favorableGHCND95 ~ lat, data=dat[dat$Realm=='Terrestrial',], col='green', cex=0.5)\n#\t\t\tpoints(tb_favorableGHCND95 ~ lat, data=dat[dat$Realm=='Marine',], col='blue', cex=0.5)\n\n\n\t# present-time body temperature in full sun, 95% max hr with GHCND\n\t\ti <- complete.cases(dat[,c('Realm', 'lat', 'tb_sunGHCND95', 'Phylum', 'Class', 'Order', 'Family', 'Genus')]); sum(i); nrow(dat)\n\tmodTbsunGHCND95 <- uGamm(tb_sunGHCND95 ~ Realm + s(lat, by=Realm), random=list(Phylum=~1, Class=~1, Order=~1, Family=~1, Genus=~1), data=dat[i,]) # use uGamm instead of gamm, since former can be used with dredge. Just a wrapper function for gamm.\n#\t\tsummary(modTbsunGHCND95$gam)\n\n\t\t## predictions from GAMM\n\t\ttemp <- predict(modTbsunGHCND95$gam, newdata=newdat, se.fit=TRUE)\n\t\tnewdat$tb_sunGHCND95 <- temp$fit\n\t\tnewdat$tb_sunGHCND95se <- temp$se.fit\n\t\t\n\t\t\t# plot predictions\n#\t\t\tplot(tb_sunGHCND95 ~ lat, data=newdat[newdat$Realm=='Terrestrial',], type='l', col='green', ylim=c(-10,60), xlim=c(-80,80))\n#\t\t\t\tlines(tb_sunGHCND95 + tb_sunGHCND95se ~ lat, data=newdat[newdat$Realm=='Terrestrial',], col='green', lty=2)\n#\t\t\t\tlines(tb_sunGHCND95 - tb_sunGHCND95se ~ lat, data=newdat[newdat$Realm=='Terrestrial',], col='green', lty=2)\n#\t\t\tlines(tb_sunGHCND95 ~ lat, data=newdat[newdat$Realm=='Marine',], col='blue')\n#\t\t\t\tlines(tb_sunGHCND95 - tb_sunGHCND95se ~ lat, data=newdat[newdat$Realm=='Marine',], col='blue', lty=2)\n#\t\t\t\tlines(tb_sunGHCND95 + tb_sunGHCND95se ~ lat, data=newdat[newdat$Realm=='Marine',], col='blue', lty=2)\n#\n#\t\t\tpoints(tb_sunGHCND95 ~ lat, data=dat[dat$Realm=='Terrestrial',], col='green', cex=0.5)\n#\t\t\tpoints(tb_sunGHCND95 ~ lat, data=dat[dat$Realm=='Marine',], col='blue', cex=0.5)\n#\n#\t\t\tlines(tb_favorableGHCND95 ~ lat, data=newdat[newdat$Realm=='Marine',], col='black')\n#\t\t\t\tlines(tb_favorableGHCND95 - tb_favorableGHCND95se ~ lat, data=newdat[newdat$Realm=='Marine',], col='black', lty=2)\n#\t\t\t\tlines(tb_favorableGHCND95 + tb_favorableGHCND95se ~ lat, data=newdat[newdat$Realm=='Marine',], col='black', lty=2)\n\n\n\n#### models for Tmax\n\t# Tmax (summer-acclimated)\n\t\ti <- complete.cases(dat[,c('Realm', 'lat', 'tmax.accsum.elev', 'Phylum', 'Class', 'Order', 'Family', 'Genus')]); sum(i); nrow(dat)\n\tmodTmaxdat <- dat[i,]\n\tmodTmax <- uGamm(tmax.accsum.elev ~ Realm + tmax_metric + s(lat, by=Realm), random=list(Phylum=~1, Class=~1, Order=~1, Family=~1, Genus=~1), data=modTmaxdat) # use uGamm instead of gamm, since former can be used with dredge. Just a wrapper function for gamm.\n#\t\tsummary(modTmax$gam)\n\n\t\t## predictions from GAMM\n\t\ttemp <- predict(modTmax$gam, newdata=newdat, se.fit=TRUE)\n\t\tnewdat$tmax <- temp$fit\n\t\tnewdat$tmaxse <- temp$se.fit\n\t\t\t\n\t\t\t# plot predictions\n#\t\tplot(tmax ~ lat, data=newdat[newdat$Realm=='Terrestrial',], type='l', col='green', ylim=c(10,50), xlim=c(-80,80))\n#\t\t\tlines(tmax + tmaxse ~ lat, data=newdat[newdat$Realm=='Terrestrial',], col='green', lty=2)\n#\t\t\tlines(tmax - tmaxse ~ lat, data=newdat[newdat$Realm=='Terrestrial',], col='green', lty=2)\n#\t\tlines(tmax ~ lat, data=newdat[newdat$Realm=='Marine',], col='blue')\n#\t\t\tlines(tmax - tmaxse ~ lat, data=newdat[newdat$Realm=='Marine',], col='blue', lty=2)\n#\t\t\tlines(tmax + tmaxse ~ lat, data=newdat[newdat$Realm=='Marine',], col='blue', lty=2)\n#\n#\t\tpoints(tmax.accsum.elev ~ lat, data=dat[dat$Realm=='Terrestrial',], col='green', cex=0.5)\n#\t\tpoints(tmax.accsum.elev ~ lat, data=dat[dat$Realm=='Marine',], col='blue', cex=0.5)\n\n\n\t# Tmax with species-specific ARR data\n\ti <- complete.cases(dat[,c('Realm', 'lat', 'tmax.accsumbyspp.elev', 'Phylum', 'Class', 'Order', 'Family', 'Genus')]); sum(i); nrow(dat)\n\tmodTmaxARRbyspp <- uGamm(tmax.accsumbyspp.elev ~ Realm + tmax_metric + s(lat, by=Realm), random=list(Phylum=~1, Class=~1, Order=~1, Family=~1, Genus=~1), data=dat[i,]) \n#\t\tsummary(modTmaxARRbyspp$gam)\n\n\t\t## predictions from GAMM\n\t\ttemp <- predict(modTmaxARRbyspp$gam, newdata=newdat, se.fit=TRUE)\n\t\tnewdat$tmaxARRbyspp <- temp$fit\n\t\tnewdat$tmaxARRbysppse <- temp$se.fit\n\n\n\n#### models for TSM\n\t\t\n\t# present-time TSM (annual, no acclimation)\n\t\t# gamm\n\t\ti <- complete.cases(dat[,c('Realm', 'lat', 'tmax_metric', 'tsm_ann_elev', 'Phylum', 'Class', 'Order', 'Family', 'Genus')]); sum(i); nrow(dat)\n\tmodTSMann <- uGamm(tsm_ann_elev ~ Realm + tmax_metric + s(lat, by=Realm), random=list(Phylum=~1, Class=~1, Order=~1, Family=~1, Genus=~1), data=dat[i,]) # use uGamm instead of gamm, since former can be used with dredge. Just a wrapper function for gamm.\n#\t\tsummary(modTSMann$gam)\n\n\t\t## predictions from GAMM\n\t\ttemp <- predict(modTSMann$gam, newdata=newdat, se.fit=TRUE)\n\t\tnewdat$tsm_ann <- temp$fit\n\t\tnewdat$tsm_annse <- temp$se.fit\n\n\t\t\t# plot predictions\n#\t\t\tplot(tsm_ann ~ lat, data=newdat[newdat$Realm=='Terrestrial' & newdat$abslat<50,], type='l', col='green', ylim=c(-10,30), xlim=c(-80,80))\n#\t\t\t\tlines(tsm_ann + tsm_annse ~ lat, data=newdat[newdat$Realm=='Terrestrial' & newdat$abslat<50,], col='green', lty=2)\n#\t\t\t\tlines(tsm_ann - tsm_annse ~ lat, data=newdat[newdat$Realm=='Terrestrial' & newdat$abslat<50,], col='green', lty=2)\n#\t\t\tlines(tsm_ann ~ lat, data=newdat[newdat$Realm=='Marine',], col='blue')\n#\t\t\t\tlines(tsm_ann - tsm_annse ~ lat, data=newdat[newdat$Realm=='Marine',], col='blue', lty=2)\n#\t\t\t\tlines(tsm_ann + tsm_annse ~ lat, data=newdat[newdat$Realm=='Marine',], col='blue', lty=2)\n#\n#\t\t\tpoints(tsm_ann_elev ~ lat, data=dat[dat$Realm=='Terrestrial',], col='green', cex=0.5)\n#\t\t\tpoints(tsm_ann ~ lat, data=dat[dat$Realm=='Marine',], col='blue', cex=0.5)\n\n\n\t# present-time TSM (summer)\n\t\t# gamm\n\t\ti <- complete.cases(dat[,c('Realm', 'lat', 'tmax_metric', 'tsm_sum_elev', 'Phylum', 'Class', 'Order', 'Family', 'Genus')]); sum(i); nrow(dat)\n\tmodTSMsum <- uGamm(tsm_sum_elev ~ Realm + tmax_metric + s(lat, by=Realm), random=list(Phylum=~1, Class=~1, Order=~1, Family=~1, Genus=~1), data=dat[i,]) # use uGamm instead of gamm, since former can be used with dredge. Just a wrapper function for gamm.\n#\t\tsummary(modTSMsum$gam)\n\n\t\t## predictions from GAMM\n\t\ttemp <- predict(modTSMsum$gam, newdata=newdat, se.fit=TRUE)\n\t\tnewdat$tsm_sum <- temp$fit\n\t\tnewdat$tsm_sumse <- temp$se.fit\n\n\t\t\t# plot predictions\n#\t\t\tplot(tsm_sum ~ lat, data=newdat[newdat$Realm=='Terrestrial' & newdat$abslat<50,], type='l', col='green', ylim=c(-10,30), xlim=c(-80,80))\n#\t\t\t\tlines(tsm_sum + tsm_sumse ~ lat, data=newdat[newdat$Realm=='Terrestrial' & newdat$abslat<50,], col='green', lty=2)\n#\t\t\t\tlines(tsm_sum - tsm_sumse ~ lat, data=newdat[newdat$Realm=='Terrestrial' & newdat$abslat<50,], col='green', lty=2)\n#\t\t\tlines(tsm_sum ~ lat, data=newdat[newdat$Realm=='Marine',], col='blue')\n#\t\t\t\tlines(tsm_sum - tsm_sumse ~ lat, data=newdat[newdat$Realm=='Marine',], col='blue', lty=2)\n#\t\t\t\tlines(tsm_sum + tsm_sumse ~ lat, data=newdat[newdat$Realm=='Marine',], col='blue', lty=2)\n#\n#\t\t\tpoints(tsm_sum_elev ~ lat, data=dat[dat$Realm=='Terrestrial',], col='green', cex=0.5)\n#\t\t\tpoints(tsm_sum_elev ~ lat, data=dat[dat$Realm=='Marine',], col='blue', cex=0.5)\n\n\n\t# present-time TSM (hottest month)\n\t\t# gamm\n\t\ti <- complete.cases(dat[,c('Realm', 'lat', 'tmax_metric', 'tsm_maxmo_elev', 'Phylum', 'Class', 'Order', 'Family', 'Genus')]); sum(i); nrow(dat)\n\tmodTSMmaxmo <- uGamm(tsm_maxmo_elev ~ Realm + tmax_metric + s(lat, by=Realm), random=list(Phylum=~1, Class=~1, Order=~1, Family=~1, Genus=~1), data=dat[i,]) # use uGamm instead of gamm, since former can be used with dredge. Just a wrapper function for gamm.\n#\t\tsummary(modTSMmaxmo$gam)\n\n\t\t## predictions from GAMM\n\t\ttemp <- predict(modTSMmaxmo$gam, newdata=newdat, se.fit=TRUE)\n\t\tnewdat$tsm_maxmo <- temp$fit\n\t\tnewdat$tsm_maxmose <- temp$se.fit\n\n\t\t\t# plot predictions\n#\t\t\tplot(tsm_maxmo ~ lat, data=newdat[newdat$Realm=='Terrestrial' & newdat$abslat<50,], type='l', col='green', ylim=c(-10,30), xlim=c(-80,80))\n#\t\t\t\tlines(tsm_maxmo + tsm_maxmose ~ lat, data=newdat[newdat$Realm=='Terrestrial' & newdat$abslat<50,], col='green', lty=2)\n#\t\t\t\tlines(tsm_maxmo - tsm_maxmose ~ lat, data=newdat[newdat$Realm=='Terrestrial' & newdat$abslat<50,], col='green', lty=2)\n#\t\t\tlines(tsm_maxmo ~ lat, data=newdat[newdat$Realm=='Marine',], col='blue')\n#\t\t\t\tlines(tsm_maxmo - tsm_maxmose ~ lat, data=newdat[newdat$Realm=='Marine',], col='blue', lty=2)\n#\t\t\t\tlines(tsm_maxmo + tsm_maxmose ~ lat, data=newdat[newdat$Realm=='Marine',], col='blue', lty=2)\n#\n#\t\t\tpoints(tsm_maxmo_elev ~ lat, data=dat[dat$Realm=='Terrestrial',], col='green', cex=0.5)\n#\t\t\tpoints(tsm_maxmo_elev ~ lat, data=dat[dat$Realm=='Marine',], col='blue', cex=0.5)\n\n\n\t# present-time TSM in exposed microclimates (95% hottest hour GHCND Tb)\n\t# with summer acclimation corrections\n\t\t# gamm\n\t\ti <- complete.cases(dat[,c('Realm', 'lat', 'tmax_metric', 'tsm_exposedGHCND95', 'Phylum', 'Class', 'Order', 'Family', 'Genus')]); sum(i); nrow(dat)\n\tmodTSMexp <- uGamm(tsm_exposedGHCND95 ~ Realm + tmax_metric + s(lat, by=Realm), random=list(Phylum=~1, Class=~1, Order=~1, Family=~1, Genus=~1), data=dat[i,]) # use uGamm instead of gamm, since former can be used with dredge. Just a wrapper function for gamm.\n#\t\tsummary(modTSMexp$lme)\n#\t\tsummary(modTSMexp$gam)\n\n\t\t## predictions from GAMM\n\t\ttemp <- predict(modTSMexp$gam, newdata=newdat, se.fit=TRUE)\n\t\tnewdat$tsm_exposedGHCND95 <- temp$fit\n\t\tnewdat$tsm_exposedGHCND95se <- temp$se.fit\n\t\t\t\n\t\t\t# plot predictions\n#\t\t\tplot(tsm_exposed ~ lat, data=newdat[newdat$Realm=='Terrestrial' & newdat$abslat<50,], type='l', col='green', ylim=c(-25,20), xlim=c(-80,80))\n#\t\t\t\tlines(tsm_exposed + tsm_exposedse ~ lat, data=newdat[newdat$Realm=='Terrestrial' & newdat$abslat<50,], col='green', lty=2)\n#\t\t\t\tlines(tsm_exposed - tsm_exposedse ~ lat, data=newdat[newdat$Realm=='Terrestrial' & newdat$abslat<50,], col='green', lty=2)\n#\t\t\tlines(tsm_exposed ~ lat, data=newdat[newdat$Realm=='Marine',], col='blue')\n#\t\t\t\tlines(tsm_exposed - tsm_exposedse ~ lat, data=newdat[newdat$Realm=='Marine',], col='blue', lty=2)\n#\t\t\t\tlines(tsm_exposed + tsm_exposedse ~ lat, data=newdat[newdat$Realm=='Marine',], col='blue', lty=2)\n#\n#\t\t\tpoints(tsm_exposed ~ lat, data=dat[dat$Realm=='Terrestrial',], col='green', cex=0.5)\n#\t\t\tpoints(tsm_exposed ~ lat, data=dat[dat$Realm=='Marine',], col='blue', cex=0.5)\n\n\n\n\t# present-time TSM in favorable microclimates (95% hottest hour with GHCND Tb) (WITH acclimation, Marine BT)\n\t\t# gamm\n\t\ti <- complete.cases(dat[,c('Realm', 'lat', 'tmax_metric', 'tsm_favorableGHCND95', 'Phylum', 'Class', 'Order', 'Family', 'Genus')]); sum(i); nrow(dat)\n\tmodGHCND95dat <- dat[i,]\n\tmodGHCND95 <- uGamm(tsm_favorableGHCND95 ~ Realm + tmax_metric + s(lat, by=Realm), random=list(Phylum=~1, Class=~1, Order=~1, Family=~1, Genus=~1), data=modGHCND95dat, control=lmeControl(niterEM=0, msMaxIter=100)) # use uGamm instead of gamm, since former can be used with dredge. Just a wrapper function for gamm.\n#\t\tsummary(modGHCND95$lme)\n#\t\tsummary(modGHCND95$gam)\n\t\t\n\t\n\t\t## predictions from GAMM\n\t\ttemp <- predict(modGHCND95$gam, newdata=newdat, se.fit=TRUE)\n\t\tnewdat$tsm_favorableGHCND95 <- temp$fit\n\t\tnewdat$tsm_favorableGHCND95se <- temp$se.fit\n\t\t\t\n\t\t\t# plot predictions\n#\t\t\tplot(tsm_favorableGHCND95 ~ lat, data=newdat[newdat$Realm=='Terrestrial',], type='l', col='green', ylim=c(-10,30), xlim=c(-80,80))\n#\t\t\t\tlines(tsm_favorableGHCND95 + tsm_favorableGHCND95se ~ lat, data=newdat[newdat$Realm=='Terrestrial',], col='green', lty=2)\n#\t\t\t\tlines(tsm_favorableGHCND95 - tsm_favorableGHCND95se ~ lat, data=newdat[newdat$Realm=='Terrestrial',], col='green', lty=2)\n#\t\t\tlines(tsm_favorableGHCND95 ~ lat, data=newdat[newdat$Realm=='Marine',], col='blue')\n#\t\t\t\tlines(tsm_favorableGHCND95 - tsm_favorableGHCND95se ~ lat, data=newdat[newdat$Realm=='Marine',], col='blue', lty=2)\n#\t\t\t\tlines(tsm_favorableGHCND95 + tsm_favorableGHCND95se ~ lat, data=newdat[newdat$Realm=='Marine',], col='blue', lty=2)\n#\n#\t\t\tpoints(tsm_favorableGHCND95 ~ lat, data=dat[i & Realm=='Terrestrial',], col='green', cex=0.5)\n#\t\t\tpoints(tsm_favorableGHCND95 ~ lat, data=dat[i & Realm=='Marine',], col='blue', cex=0.5)\n#\n#\t\t\t\tdat[i & Realm=='Marine' & demers_pelag=='pelagic' & big==TRUE & mobility=='swim', points(tsm_favorableGHCND95 ~ lat, col='red', cex=0.5)]\n#\t\t\t\n#\n#\t\t\tlines(tsm_favorable95 ~ lat, data=newdat[newdat$Realm=='Terrestrial',], col='red')\n#\t\t\t\tlines(tsm_favorable95 - tsm_favorable95se ~ lat, data=newdat[newdat$Realm=='Terrestrial',], col='red', lty=2)\n#\t\t\t\tlines(tsm_favorable95 + tsm_favorable95se ~ lat, data=newdat[newdat$Realm=='Terrestrial',], col='red', lty=2)\n#\n#\t\n#\t\t\tdatorig <- fread('temp/warmingtolerance_byspecies_2017-12-19.csv')\n#\t\t\t# use 95% warmest hour for TSMs. favorable microclimates (shade or wet skin + behavioral thermoregulation of 10degC)\n#\t\t\tdatorig[, tsm_favorable95_10 := as.numeric(rep(NA, .N))]\n#\t\t\tdatorig[habitat=='terrestrial' & animal.type!='amphibian', tsm_favorable95_10 := tsm_NM_2m_airshade95_accsum.elev]\n#\t\t\tdatorig[habitat=='terrestrial' & animal.type=='amphibian', tsm_favorable95_10 := tsm_NM_shade_body_wet95_accsum.elev]\n#\t\t\tdatorig[habitat=='marine', tsm_favorable95_10 := tsm_95hr_marineBT10_accsum]\n#\n#\t\t\tpoints(tsm_favorable95_10 ~ lat, data=datorig[habitat=='marine',], col='red', cex=0.3, pch=16)\n\n\t\t# minimum marine TSM vs. minimum terrestrial TSM\n\t\tmin(newdat$tsm_favorableGHCND95[newdat$Realm=='Terrestrial']) - min(newdat$tsm_favorableGHCND95[newdat$Realm=='Marine'])\n\t\n\n\t# Species-specific ARR data: present-time TSM in favorable microclimates (95% hottest hour with GHCND Tb) (WITH acclimation, Marine BT)\n\ti <- complete.cases(dat[,c('Realm', 'lat', 'tmax_metric', 'tsm_favorableGHCND95byspp', 'Phylum', 'Class', 'Order', 'Family', 'Genus')]); sum(i); nrow(dat)\n\tmodGHCND95ARRbysppdat <- dat[i,]\n\tmodGHCND95ARRbyspp <- uGamm(tsm_favorableGHCND95byspp ~ Realm + tmax_metric + s(lat, by=Realm), random=list(Phylum=~1, Class=~1, Order=~1, Family=~1, Genus=~1), data=modGHCND95ARRbysppdat, control=lmeControl(niterEM=50, msMaxIter=1000))\n#\t\tsummary(modGHCND95ARRbyspp$gam)\n\n\n\n\n\n\t# present-time TSM in favorable microclimates (95% hottest hour GHCND Tb) (with acclimation, WITHOUT marine behavioral thermoregulation)\n\t\t# gamm\n\t\ti <- complete.cases(dat[,c('Realm', 'lat', 'tmax_metric', 'tsm_favorableGHCND95_nomarineBT', 'Phylum', 'Class', 'Order', 'Family', 'Genus')]); sum(i); nrow(dat)\n\tmodnoMBT <- uGamm(tsm_favorableGHCND95_nomarineBT ~ Realm + tmax_metric + s(lat, by=Realm), random=list(Phylum=~1, Class=~1, Order=~1, Family=~1, Genus=~1), data=dat[i,], control=lmeControl(niterEM=0, msMaxIter=100))\n#\t\tsummary(modnoMBT$gam)\n\n\t\t## predictions from GAMM\n\t\ttemp <- predict(modnoMBT$gam, newdata=newdat, se.fit=TRUE)\n\t\tnewdat$tsm_favorableGHCND95_nomarineBT <- temp$fit\n\t\tnewdat$tsm_favorableGHCND95_nomarineBTse <- temp$se.fit\n\t\t\t\n\t\t\t# plot predictions. TSMs with thermoregulation in marine animals in red.\n#\t\t\tplot(tsm_favorableGHCND95_nomarineBT ~ lat, data=newdat[newdat$Realm=='Terrestrial',], type='l', col='green', ylim=c(-10,30), xlim=c(-80,80))\n#\t\t\t\tlines(tsm_favorableGHCND95_nomarineBT + tsm_favorableGHCND95_nomarineBTse ~ lat, data=newdat[newdat$Realm=='Terrestrial',], col='green', lty=2)\n#\t\t\t\tlines(tsm_favorableGHCND95_nomarineBT - tsm_favorableGHCND95_nomarineBTse ~ lat, data=newdat[newdat$Realm=='Terrestrial',], col='green', lty=2)\n#\t\t\tlines(tsm_favorableGHCND95_nomarineBT ~ lat, data=newdat[newdat$Realm=='Marine',], col='red')\n#\t\t\t\tlines(tsm_favorableGHCND95_nomarineBT - tsm_favorableGHCND95_nomarineBTse ~ lat, data=newdat[newdat$Realm=='Marine',], col='red', lty=2) #w/out marine BT in red\n#\t\t\t\tlines(tsm_favorableGHCND95_nomarineBT + tsm_favorableGHCND95_nomarineBTse ~ lat, data=newdat[newdat$Realm=='Marine',], col='red', lty=2)\n#\n#\t\t\t# overlay with marine BT\n#\t\t\tlines(tsm_favorableGHCND95 ~ lat, data=newdat[newdat$Realm=='Marine',], col='blue')\n#\t\t\t\tlines(tsm_favorableGHCND95 - tsm_favorableGHCND95se ~ lat, data=newdat[newdat$Realm=='Marine',], col='blue', lty=2)\n#\t\t\t\tlines(tsm_favorableGHCND95 + tsm_favorableGHCND95se ~ lat, data=newdat[newdat$Realm=='Marine',], col='blue', lty=2)\n#\n#\t\t\tpoints(tsm_favorableGHCND95_nomarineBT ~ lat, data=dat[dat$Realm=='Terrestrial',], col='green', cex=0.5)\n#\t\t\tpoints(tsm_favorableGHCND95_nomarineBT ~ lat, data=dat[dat$Realm=='Marine',], col='blue', cex=0.5)\n\n\n\t# present-time TSM in favorable microclimates (95% hottest hour with GHCND Tb) (WITH acclimation, MOREs Marine BT)\n\t\t# gamm\n\t\ti <- complete.cases(dat[,c('Realm', 'lat', 'tmax_metric', 'tsm_favorableGHCND95_marBTmore', 'Phylum', 'Class', 'Order', 'Family', 'Genus')]); sum(i); nrow(dat)\n\tmodGHCND95_marBTmoredat <- dat[i,]\n\tmodGHCND95_marBTmore <- uGamm(tsm_favorableGHCND95_marBTmore ~ Realm + tmax_metric + s(lat, by=Realm), random=list(Phylum=~1, Class=~1, Order=~1, Family=~1, Genus=~1), data=modGHCND95_marBTmoredat, control=lmeControl(niterEM=0, msMaxIter=100)) # use uGamm instead of gamm, since former can be used with dredge. Just a wrapper function for gamm.\n#\t\tsummary(modGHCND95_marBTmore$gam)\n#\t\t\tsummary(modGHCND95$gam) # to compare\n\n\t# present-time TSM in favorable microclimates (95% hottest hour with GHCND Tb) (WITH acclimation, LESS Marine BT)\n\t\t# gamm\n\t\ti <- complete.cases(dat[,c('Realm', 'lat', 'tmax_metric', 'tsm_favorableGHCND95_marBTless', 'Phylum', 'Class', 'Order', 'Family', 'Genus')]); sum(i); nrow(dat)\n\tmodGHCND95_marBTlessdat <- dat[i,]\n\tmodGHCND95_marBTless <- uGamm(tsm_favorableGHCND95_marBTless ~ Realm + tmax_metric + s(lat, by=Realm), random=list(Phylum=~1, Class=~1, Order=~1, Family=~1, Genus=~1), data=modGHCND95_marBTlessdat, control=lmeControl(niterEM=0, msMaxIter=100)) # use uGamm instead of gamm, since former can be used with dredge. Just a wrapper function for gamm.\n#\t\tsummary(modGHCND95_marBTless$gam)\n#\t\t\tsummary(modGHCND95_marBTmore$gam) # to compare\n#\t\t\tsummary(modGHCND95$gam) # to compare\n\n\n\t# present-time TSM in favorable microclimates (95% hottest hour, GHCND, WITH marine BT)\n\t# NO acclimation corrections\n\t\t# gamm\n\t\ti <- complete.cases(dat[,c('Realm', 'lat', 'tmax_metric', 'tsm_favorableGHCND95_noacc', 'Phylum', 'Class', 'Order', 'Family', 'Genus')]); sum(i); nrow(dat)\n\tmodTSMfav_noaccdat <- dat[i,]\n\tmodTSMfav_noacc <- uGamm(tsm_favorableGHCND95_noacc ~ Realm + tmax_metric + s(lat, by=Realm), random=list(Phylum=~1, Class=~1, Order=~1, Family=~1, Genus=~1), data=modTSMfav_noaccdat) # use uGamm instead of gamm, since former can be used with dredge. Just a wrapper function for gamm.\n#\t\tsummary(modTSMfav_noacc$gam)\n\n\t\t## predictions from GAMM\n\t\ttemp <- predict(modTSMfav_noacc$gam, newdata=newdat, se.fit=TRUE)\n\t\tnewdat$tsm_favorable_noacc <- temp$fit\n\t\tnewdat$tsm_favorable_noaccse <- temp$se.fit\n\t\t\t\n\t\t\t# plot predictions\n#\t\t\tplot(tsm_favorable_noacc ~ lat, data=newdat[newdat$Realm=='Terrestrial' & newdat$abslat<50,], type='l', col='green', ylim=c(-10,30), xlim=c(-80,80))\n#\t\t\t\tlines(tsm_favorable_noacc + tsm_favorable_noaccse ~ lat, data=newdat[newdat$Realm=='Terrestrial' & newdat$abslat<50,], col='green', lty=2)\n#\t\t\t\tlines(tsm_favorable_noacc - tsm_favorable_noaccse ~ lat, data=newdat[newdat$Realm=='Terrestrial' & newdat$abslat<50,], col='green', lty=2)\n#\t\t\tlines(tsm_favorable_noacc ~ lat, data=newdat[newdat$Realm=='Marine',], col='blue')\n#\t\t\t\tlines(tsm_favorable_noacc - tsm_favorable_noaccse ~ lat, data=newdat[newdat$Realm=='Marine',], col='blue', lty=2)\n#\t\t\t\tlines(tsm_favorable_noacc + tsm_favorable_noaccse ~ lat, data=newdat[newdat$Realm=='Marine',], col='blue', lty=2)\n#\n#\t\t\tpoints(tsm_favorable_noacc ~ lat, data=dat[dat$Realm=='Terrestrial',], col='green', cex=0.5)\n#\t\t\tpoints(tsm_favorable_noacc ~ lat, data=dat[dat$Realm=='Marine',], col='blue', cex=0.5)\n\n\n\n\t# present-time TSM in favorable microclimates (95% hottest hour, GHCND, WITH marine BT)\n\t# NO acclimation corrections, but acclimation temperature included as a fixed effect\n\t\t# gamm\n\t\ti <- complete.cases(dat[,c('Realm', 'lat', 'tmax_metric', 'tsm_favorableGHCND95_noacc', 'tmax_acc', 'Phylum', 'Class', 'Order', 'Family', 'Genus')]); sum(i); nrow(dat)\n\tmodTSMfav_acctermdat <- dat[i,]\n\tmodTSMfav_accterm <- uGamm(tsm_favorableGHCND95_noacc ~ Realm + tmax_metric + tmax_acc + s(lat, by=Realm), random=list(Phylum=~1, Class=~1, Order=~1, Family=~1, Genus=~1), data=modTSMfav_acctermdat) # use uGamm instead of gamm, since former can be used with dredge. Just a wrapper function for gamm.\n#\t\tsummary(modTSMfav_accterm$gam)\n\n\n\n# Write out predictions\nwrite.csv(newdat, file='temp/warmingtolerance_bylatlon.csv', row.names=FALSE)\n\n\n#############################\n## Calculate peak locations\n## (need models from above)\n#############################\n\n\n\t# present-time body temperature in favorable microclimates, 95% max hr with GHCND\t\t\n\t\t# how many peaks?\n\t\tpeaksmeanTbGHCND95_terr <- findPeaksGAM(modTbGHCND95$gam, newdat[newdat$Realm=='Terrestrial',], xvar='lat', xtol=4) # from the main prediction\n\t\t\tpeaksmeanTbGHCND95_terr$npeaks\n\t\t\tpeaksmeanTbGHCND95_terr$peaklocs\t\t\t\n\t\tpeaksTbGHCND95_terr <- findPeaksGAM_CI(mod=modTbGHCND95$gam, newdat=newdat[newdat$Realm=='Terrestrial',], n=1000, xvar='lat', xtol=4) # xtol sets lat window to 4° in each direction\n\t\tpeaksmeanTbGHCND95_mar <- findPeaksGAM(modTbGHCND95$gam, newdat[newdat$Realm=='Marine',], xvar='lat', xtol=4) # from the main prediction\t\t\t\n\t\tpeaksTbGHCND95_mar <- findPeaksGAM_CI(mod=modTbGHCND95$gam, newdat=newdat[newdat$Realm=='Marine',], n=1000, xvar='lat', xtol=4)\n\t\t\n\t\t# write out\n\t\tsaveRDS(peaksTbGHCND95_terr, file='temp/peaks_modTbGHCND95_terr.rds')\n\t\tsaveRDS(peaksTbGHCND95_mar, file='temp/peaks_modTbGHCND95_mar.rds')\n\n\n\n#### models for Tmax\n\t# Tmax (summer-acclimated)\n\t\t# how many peaks?\n\t\tpeaksmeanTmax_terr <- findPeaksGAM(modTmax$gam, newdat[newdat$Realm=='Terrestrial',], xvar='lat', xtol=4) # from the main prediction\n\t\t\tpeaksmeanTmax_terr$npeaks\n\t\t\tpeaksmeanTmax_terr$peaklocs\t\t\t\n\t\tpeaksTmax_terr <- findPeaksGAM_CI(mod=modTmax$gam, newdat=newdat[newdat$Realm=='Terrestrial',], n=1000, xvar='lat', xtol=4) # xtol sets lat window to 4° in each direction\n\t\tpeaksmeanTmax_mar <- findPeaksGAM(modTmax$gam, newdat[newdat$Realm=='Marine',], xvar='lat', xtol=4) # from the main prediction\t\t\t\n\t\tpeaksTmax_mar <- findPeaksGAM_CI(mod=modTmax$gam, newdat=newdat[newdat$Realm=='Marine',], n=1000, xvar='lat', xtol=4)\n\t\t\n\t\t# write out\n\t\tsaveRDS(peaksTmax_terr, file='temp/peaks_modTmax_terr.rds')\n\t\tsaveRDS(peaksTmax_mar, file='temp/peaks_modTmax_mar.rds')\n\n\n#### models for TSM\n\t# present-time TSM in favorable microclimates (95% hottest hour with GHCND Tb) (WITH acclimation, Marine BT)\n\t\t# how many valleys?\n\t\tpeaksmeanTSM_favorableGHCND95_terr <- findPeaksGAM(modGHCND95$gam, newdat[newdat$Realm=='Terrestrial',], xvar='lat', xtol=4, findmaxima=FALSE) # from the main prediction\n\t\t\tpeaksmeanTSM_favorableGHCND95_terr$npeaks\n\t\t\tpeaksmeanTSM_favorableGHCND95_terr$peaklocs\t\t\t\n\t\tpeaksTSM_favorableGHCND95_terr <- findPeaksGAM_CI(mod=modGHCND95$gam, newdat=newdat[newdat$Realm=='Terrestrial',], n=1000, xvar='lat', xtol=4, findmaxima=FALSE) # xtol sets lat window to 4° in each direction\n\t\tpeaksmeanTSM_favorableGHCND95_mar <- findPeaksGAM(modGHCND95$gam, newdat[newdat$Realm=='Marine',], xvar='lat', xtol=4, findmaxima=FALSE)\n\t\tpeaksTSM_favorableGHCND95_mar <- findPeaksGAM_CI(mod=modGHCND95$gam, newdat=newdat[newdat$Realm=='Marine',], n=1000, xvar='lat', xtol=4, findmaxima=FALSE)\n\t\t\n\t\t# write out\n\t\tsaveRDS(peaksTSM_favorableGHCND95_terr, file='temp/peaks_modGHCND95_terr.rds')\n\t\tsaveRDS(peaksTSM_favorableGHCND95_mar, file='temp/peaks_modGHCND95_mar.rds')\n\n\n\n#############################\n## Calculate RVI\n## (need models from above)\n#############################\n\n#### models for operative temperature (Te)\n\t# present-time body temperature in favorable microclimates, 95% max hr with GHCND\n\t\t# fit all subsets\n\t\toptions(na.action = \"na.fail\")\n\t\tmodTbGHCND95s <- dredge(modTbGHCND95, beta=FALSE, evaluate=TRUE, rank='AICc', trace=1)\n#\t\tsubset(modTbGHCND95s, delta < 6)\n\n\t\tmodavgTbGHCND95 <- model.avg(modTbGHCND95s)\n#\t\tsummary(modavgTEGHCND95)\n\n\n#### models for Tmax\n\t# Tmax (summer-acclimated)\n\t\t# fit all subsets\n\t\toptions(na.action = \"na.fail\")\n\t\tmodTmaxs <- dredge(modTmax, beta=FALSE, evaluate=TRUE, rank='AICc', trace=1)\n#\t\tsubset(modTmaxs)\n\n\t\tmodavgTmax <- model.avg(modTmaxs)\n\t\t#summary(modavgTmax)\n\n\n#### models for TSM\n\t# present-time TSM in favorable microclimates (95% hottest hour with GHCND) (WITH acclimation, Marine BT)\n\t\t# fit all subsets\n\t\toptions(na.action = \"na.fail\")\n\t\tmodGHCND95s <- dredge(modGHCND95, beta=FALSE, evaluate=TRUE, rank='AICc', trace=1)\n#\t\tsubset(modGHCND95s, delta < 6)\n\n\t\tmodavgGHCND95 <- model.avg(modGHCND95s)\n#\t\tsummary(modavgGHCND95)\n\n\n\t# Species-specific ARR data: present-time TSM in favorable microclimates (95% hottest hour with GHCND Tb) (WITH acclimation, Marine BT)\n\t\t# fit all subsets\n\t\toptions(na.action = \"na.fail\")\n\t\tmodGHCND95ARRbyspps <- dredge(modGHCND95ARRbyspp, beta=FALSE, evaluate=TRUE, rank='AICc', trace=1)\n#\t\tsubset(modGHCND95ARRbyspps, delta < 6)\n\n\t\tmodavgGHCND95ARRbyspp <- model.avg(modGHCND95ARRbyspps)\n#\t\tsummary(modavgGHCND95ARRbyspp)\n\n\t# present-time TSM in favorable microclimates (95% hottest hour with GHCND) (with acclimation, MORE Marine BT)\n\t\t# fit all subsets\n\t\toptions(na.action = \"na.fail\")\n\t\tmodGHCND95_marBTmores <- dredge(modGHCND95_marBTmore, beta=FALSE, evaluate=TRUE, rank='AICc', trace=1)\n#\t\tsubset(modGHCND95_marBTmores, delta < 6)\n\n\t\tmodavgGHCND95_marBTmore <- model.avg(modGHCND95_marBTmores)\n#\t\tsummary(modavgGHCND95_marBTmore)\n\n\t# present-time TSM in favorable microclimates (95% hottest hour with GHCND) (with acclimation, LESS Marine BT)\n\t\t# fit all subsets\n\t\toptions(na.action = \"na.fail\")\n\t\tmodGHCND95_marBTlesss <- dredge(modGHCND95_marBTless, beta=FALSE, evaluate=TRUE, rank='AICc', trace=1)\n#\t\tsubset(modGHCND95_marBTlesss, delta < 6)\n\n\t\tmodavgGHCND95_marBTless <- model.avg(modGHCND95_marBTlesss)\n#\t\tsummary(modavgGHCND95_marBTless)\n\n\n\n\t# present-time TSM in favorable microclimates (95% hottest hour, GHCND, WITH marine BT)\n\t# NO acclimation corrections\n\t\t# fit all subsets\n\t\toptions(na.action = \"na.fail\")\n\t\tmodTSMfav_noaccs <- dredge(modTSMfav_noacc, beta=FALSE, evaluate=TRUE, rank='AICc', trace=1)\n#\t\tsubset(modTSMfav_noaccs, delta < 6)\n\n\t\tmodavgTSMfav_noacc <- model.avg(modTSMfav_noaccs)\n#\t\tsummary(modavgTSMfav_noacc)\n\n\t# present-time TSM in favorable microclimates (95% hottest hour, GHCND, WITH marine BT)\n\t# NO acclimation corrections, but acclimation temperature included as a fixed effect\n\t\t# fit all subsets\n\t\toptions(na.action = \"na.fail\")\n\t\tmodTSMfav_accterms <- dredge(modTSMfav_accterm, beta=FALSE, evaluate=TRUE, rank='AICc', trace=1)\n#\t\tsubset(modTSMfav_accterms, delta < 6)\n\n\t\tmodavgTSMfav_accterm <- model.avg(modTSMfav_accterms)\n#\t\tsummary(modavgTSMfav_accterm)\n\n\n\n\n####################################################\n### Write out table of peaks and valleys in GAMMS\n####################################################\nout <- data.frame(Variable=c('T_b terrestrial', 'T_b marine', 'T_max terrestrial', 'T_max marine', 'TSM_favorable terrestrial', 'TSM_favorable marine'), Peak1=character(6), Peak2=character(6), Peak3=character(6), stringsAsFactors=FALSE)\n\n# calculate quantiles\nqTbGHCND95_terr1 <- quantile(sapply(peaksTbGHCND95_terr$peaklocs, FUN=function(x, min=-50, max=0){ret <- x[x>min & xmin & xmin & xmin & xmin & xmin & xmin & xmin & xmin & xmin & xmin & x|t|)'],2),\n\t\t\tRVI = round(ifelse(length(indxrvi)>0, no=NA, yes=modavgsout[[i]]$importance[indxrvi]),2),\n\t\t\tedf = NA,\n\t\t\tF = NA)\n\t\tout2 <- rbind(out2, temp)\n\t}\n\n\t# smooth terms\n\tfor(j in 1:nrow(summ$s.table)){\n\t\tvar <- gsub('s\\\\(lat\\\\)\\\\:Realm', '', rownames(summ$s.table)[j])\n\t\ttemp <- data.frame(\n\t\t\tmodel = names(modsout)[i],\n\t\t\tr2='',\n\t\t\tn='',\n\t\t\tvariable = paste('Latitude:', var, sep=''),\n\t\t\tsmooth = 1,\n\t\t\testimate = NA,\n\t\t\tse = NA,\n\t\t\tt = NA,\n\t\t\tp = signif(summ$s.table[j, 'p-value'],2),\n\t\t\tRVI = round(ifelse(var=='Marine', no=NA, yes=modavgsout[[i]]$importance['s(lat, by = Realm)']),2),\n\t\t\tedf = round(summ$s.table[j, 'edf'],2),\n\t\t\tF = round(summ$s.table[j, 'F'],2))\n\t\tout2 <- rbind(out2, temp)\n\t}\n}\n\n# format p-values\norig <- options(scipen=1)\n# rnd <- out2$p < 0.00001\nout2$p <- as.character(out2$p)\n# out2$p[rnd] <- '< 0.00001'\n\nout2$p\n\noptions(scipen=orig)\n\n# write out\nout2\nwrite.csv(out2, file='tables/TableS2_gamm_models.csv', row.names=FALSE, na='')\n", "meta": {"hexsha": "9a1176f3a9c3ed223cc3a926160e2fdf78baeb69", "size": 39194, "ext": "r", "lang": "R", "max_stars_repo_path": "data/pinsky/pinskylab-hotWater-250832d/scripts/thermal_safety_vs_lat_bylatlon_models.r", "max_stars_repo_name": "HuckleyLab/phyto-mhw", "max_stars_repo_head_hexsha": "8e067c73310fb4a4520d5a72f68717030ce90e14", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 2, "max_stars_repo_stars_event_min_datetime": "2020-10-13T02:37:26.000Z", "max_stars_repo_stars_event_max_datetime": "2021-04-27T04:41:09.000Z", "max_issues_repo_path": "data/pinsky/pinskylab-hotWater-250832d/scripts/thermal_safety_vs_lat_bylatlon_models.r", "max_issues_repo_name": "HuckleyLab/phyto-mhw", "max_issues_repo_head_hexsha": "8e067c73310fb4a4520d5a72f68717030ce90e14", "max_issues_repo_licenses": ["MIT"], "max_issues_count": 8, "max_issues_repo_issues_event_min_datetime": "2020-07-19T10:54:37.000Z", "max_issues_repo_issues_event_max_datetime": "2021-10-17T19:53:09.000Z", "max_forks_repo_path": "data/pinsky/pinskylab-hotWater-250832d/scripts/thermal_safety_vs_lat_bylatlon_models.r", "max_forks_repo_name": "HuckleyLab/phyto-mhw", "max_forks_repo_head_hexsha": "8e067c73310fb4a4520d5a72f68717030ce90e14", "max_forks_repo_licenses": ["MIT"], "max_forks_count": null, "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null, "avg_line_length": 55.4370579915, "max_line_length": 345, "alphanum_fraction": 0.6955401337, "num_tokens": 13988, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6150878555160665, "lm_q2_score": 0.5698526514141572, "lm_q1q2_score": 0.3505094453184785}} {"text": "[[[\n RELATIVE COMPLEXITY!\n Additional steps in my new construction for\n a self-delimiting universal Turing machine.\n\n We show that\n\n H(beta) <= n + H(n) + c for n-bit beta \n \n H(x,y) <= H(x) + H(y) + c\n \n H(H(x)|x) <= c\n \n H(x,y) <= H(x) + H(y|x) + c\n]]]\n \n[\n Here is the self-delimiting universal Turing machine\n with NO free data. P is the program.\n [Run-utm-on p expands to this.]\n]\ndefine (U p)\n cadr try no-time-limit 'eval read-exp p\n\ndefine U\nvalue (lambda (p) (car (cdr (try no-time-limit (' (eval \n (read-exp))) p))))\n\n[Here is the version of U with one piece of free data:]\n\ndefine (U2 p q) [q is a program for U for the free data]\n cadr try no-time-limit \n display cons 'read-exp [run ((read-exp) (' q))]\n cons cons \"' \n cons q \n nil \n nil \n p\n\ndefine U2\nvalue (lambda (p q) (car (cdr (try no-time-limit (displa\n y (cons (' (read-exp)) (cons (cons ' (cons q nil))\n nil))) p))))\n\n[Here's the version given two things, not one:]\n\ndefine (U3 p q r) [q, r are programs for U for the free data]\n cadr try no-time-limit \n display cons 'read-exp [run ((read-exp) (' q) (' r))]\n cons cons \"' \n cons q \n nil \n cons cons \"' \n cons r \n nil \n nil \n p\n\ndefine U3\nvalue (lambda (p q r) (car (cdr (try no-time-limit (disp\n lay (cons (' (read-exp)) (cons (cons ' (cons q nil\n )) (cons (cons ' (cons r nil)) nil)))) p))))\n\n[\n Consider an n-bit string beta.\n We show that H(beta) <= n + H(n) + 912.\n]\ndefine pi\n let (loop k)\n if = k 0 nil\n cons read-bit (loop - k 1)\n (loop eval read-exp)\n\ndefine pi\nvalue ((' (lambda (loop) (loop (eval (read-exp))))) (' (\n lambda (k) (if (= k 0) nil (cons (read-bit) (loop \n (- k 1)))))))\n\n[Size it.]\nlength bits pi\n\nexpression (length (bits pi))\nvalue 912\n\n[Use it.]\n(U\n append bits pi \n append bits 12\n '(0 0 1 1 1 1 1 1 0 0 0 1)\n)\n\nexpression (U (append (bits pi) (append (bits 12) (' (0 0 1 1\n 1 1 1 1 0 0 0 1)))))\nvalue (0 0 1 1 1 1 1 1 0 0 0 1)\n\n[\n Proof that H(x,y) <= H(x) + H(y) + 432.\n]\ndefine rho\n cons eval read-exp cons eval read-exp nil\n\ndefine rho\nvalue (cons (eval (read-exp)) (cons (eval (read-exp)) ni\n l))\n\n[Size it.]\nlength bits rho\n\nexpression (length (bits rho))\nvalue 432\n\n[Use it.]\n(U\n append bits rho\n append bits pi\n append bits 5\n append '(1 1 1 1 1)\n append bits pi\n append bits 9\n '(0 0 0 0 0 0 0 0 0)\n)\n\nexpression (U (append (bits rho) (append (bits pi) (append (b\n its 5) (append (' (1 1 1 1 1)) (append (bits pi) (\n append (bits 9) (' (0 0 0 0 0 0 0 0 0)))))))))\nvalue ((1 1 1 1 1) (0 0 0 0 0 0 0 0 0))\n\n[\n Proof that H(H(x)|x) <= 208.\n]\ndefine (alpha x*) [x* = minimum-size program for x]\n length x* \n\ndefine alpha\nvalue (lambda (x*) (length x*))\n\n [get H(x) from x*]\n[Size it.]\nlength bits alpha\n\nexpression (length (bits alpha))\nvalue 208\n\n[Use it.]\n\n(U2 \n \n[This is the program to calculate H(x):]\n\nbits alpha \n\n[This is the program x* for x,]\n[supposedly smallest possible:]\n\nbits' + 1 1 \n\n)\n\nexpression (U2 (bits alpha) (bits (' (+ 1 1))))\ndisplay ((read-exp) (' (0 0 1 0 1 0 0 0 0 0 1 0 1 0 1 1 0 \n 0 1 0 0 0 0 0 0 0 1 1 0 0 0 1 0 0 1 0 0 0 0 0 0 0 \n 1 1 0 0 0 1 0 0 1 0 1 0 0 1 0 0 0 0 1 0 1 0)))\nvalue 64\n\n[Check size of program is correct]\n* 8 + 1 display size display '+ 1 1\n\nexpression (* 8 (+ 1 (display (size (display (' (+ 1 1)))))))\ndisplay (+ 1 1)\ndisplay 7\nvalue 64\n\n[\n Proof that H(x,y) <= H(x) + H(y|x) + 2872.\n\n The 2872-bit prefix gamma proves this.\n\n Gamma does the job, but it's slow.\n So below we will present delta, which is a greatly\n sped up version of gamma. The speed up is\n achieved by introducing a new primitive function\n to do the job. The was-read mechanism used below\n is much faster than our technique here using try\n to get the bits of the program p = x* as we run it.\n]\n\ndefine gamma\n\n [read program p bit by bit until we get it all]\n\n let (loop p)\n if = success car try no-time-limit 'eval read-exp p\n [then] p \n [else] (loop append p cons read-bit nil)\n\n let x* (loop nil) [get x* = program for x]\n let x run-utm-on x* [get x from x*]\n let y [get y from x* by running]\n eval cons 'read-exp [((read-exp) (' x*))]\n cons cons \"' \n cons x*\n nil \n nil \n\n [form the pair x, y]\n cons x cons y nil\n\ndefine gamma\nvalue ((' (lambda (loop) ((' (lambda (x*) ((' (lambda (x\n ) ((' (lambda (y) (cons x (cons y nil)))) (eval (c\n ons (' (read-exp)) (cons (cons ' (cons x* nil)) ni\n l)))))) (car (cdr (try no-time-limit (' (eval (rea\n d-exp))) x*)))))) (loop nil)))) (' (lambda (p) (if\n (= success (car (try no-time-limit (' (eval (read\n -exp))) p))) p (loop (append p (cons (read-bit) ni\n l)))))))\n\n[Size it.]\nlength bits gamma\n\nexpression (length (bits gamma))\nvalue 2872\n\n[Use it.]\n\nrun-utm-on\n\n[get pair x, y by combining ]\n[a program for x and a program to get y from x]\n\nappend \n\n bits gamma\n\nappend\n\n [x* = program to calculate x = 2]\n [[Supposedly x* is smallest possible,]] \n [[but this works for ANY x* for x.]]\n\n bits' + 1 1 \n\n [program to calculate y = x+1 from x*]\n\n bits' lambda(x*) + 1 run-utm-on x*\n\nexpression (car (cdr (try no-time-limit (' (eval (read-exp)))\n (append (bits gamma) (append (bits (' (+ 1 1))) (\n bits (' (lambda (x*) (+ 1 (car (cdr (try no-time-l\n imit (' (eval (read-exp))) x*))))))))))))\nvalue (2 3)\n\n[\n This technique for getting a program as well as its output\n by inching along using try is slow.\n\n Now let's speed up gamma by adding a new primitive function.\n Was-read gives the binary data read so far in the current try. \n With it we will prove that H(x,y) <= H(x) + H(y|x) + 2104.\n]\ndefine delta [knows that its own size is 2104 bits]\n let (skip n s) [skip first n bits of bit string s]\n if = n 0 s (skip - n 1 cdr s) [used to erase delta from was-read]\n let x eval read-exp [get x]\n let x* (skip 2104 was-read) [get program for x]\n let y [calculate y from the program for x by]\n eval cons 'read-exp [running ((read-exp) (' x*))]\n cons cons \"' \n cons x*\n nil \n nil \n [form the pair x, y]\n cons x cons y nil \n\ndefine delta\nvalue ((' (lambda (skip) ((' (lambda (x) ((' (lambda (x*\n ) ((' (lambda (y) (cons x (cons y nil)))) (eval (c\n ons (' (read-exp)) (cons (cons ' (cons x* nil)) ni\n l)))))) (skip 2104 (was-read))))) (eval (read-exp)\n )))) (' (lambda (n s) (if (= n 0) s (skip (- n 1) \n (cdr s))))))\n\n \n[Size it.]\nlength bits delta\n\nexpression (length (bits delta))\nvalue 2104\n\n[Use it.]\n\nrun-utm-on\n\n[get pair x, y by combining ]\n[a program for x and a program to get y from x]\n\nappend \n\n bits delta\n\nappend\n\n [x* = program to calculate x = 2]\n [[Supposedly x* is smallest possible,]] \n [[but this works for ANY x* for x.]]\n\n bits' + 1 1\n\n [program to calculate y = x+1 from x*]\n\n bits' lambda(x*) + 1 run-utm-on x*\n\nexpression (car (cdr (try no-time-limit (' (eval (read-exp)))\n (append (bits delta) (append (bits (' (+ 1 1))) (\n bits (' (lambda (x*) (+ 1 (car (cdr (try no-time-l\n imit (' (eval (read-exp))) x*))))))))))))\nvalue (2 3)\n", "meta": {"hexsha": "e20b29f8cd23ee7cec7c6ebe234ad5706047cef4", "size": 7975, "ext": "r", "lang": "R", "max_stars_repo_path": "book-examples/utm2.r", "max_stars_repo_name": "darobin/chaitin-lisp", "max_stars_repo_head_hexsha": "a06fd5647a1d69d41ec725616fa0ebcc71e55bec", "max_stars_repo_licenses": ["MIT"], "max_stars_count": 5, "max_stars_repo_stars_event_min_datetime": "2018-02-28T09:21:07.000Z", "max_stars_repo_stars_event_max_datetime": "2021-01-09T03:29:32.000Z", "max_issues_repo_path": "book-examples/utm2.r", "max_issues_repo_name": "darobin/chaitin-lisp", "max_issues_repo_head_hexsha": "a06fd5647a1d69d41ec725616fa0ebcc71e55bec", "max_issues_repo_licenses": ["MIT"], "max_issues_count": null, "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "book-examples/utm2.r", "max_forks_repo_name": "darobin/chaitin-lisp", "max_forks_repo_head_hexsha": "a06fd5647a1d69d41ec725616fa0ebcc71e55bec", "max_forks_repo_licenses": ["MIT"], "max_forks_count": 2, "max_forks_repo_forks_event_min_datetime": "2016-06-23T14:37:37.000Z", "max_forks_repo_forks_event_max_datetime": "2019-04-19T13:09:35.000Z", "avg_line_length": 25.0786163522, "max_line_length": 72, "alphanum_fraction": 0.517492163, "num_tokens": 2531, "lm_name": "Qwen/Qwen-72B", "lm_label": "1. YES\n2. YES", "lm_q1_score": 0.6406358548398982, "lm_q2_score": 0.5467381519846138, "lm_q1q2_score": 0.35026006337024923}} {"text": "#' Estimating the direct sampling (DSC) environmental contours\r\n#'\r\n#' @description\r\n#' This function estimates the direct sampling (DSC) environmental contours with standardization, as proposed in Huesby et al. (2015),\r\n#' for a given sample data set or a fitted joint distribution of class \\code{ht} or \\code{wln}.\r\n#' \r\n#' @param object either a fitted joint distribution of class \\code{wln} or \\code{ht}, or an existing sample data\r\n#' set containing \\code{hs} and \\code{tp} as columns. See details.\r\n#' \r\n#' @param output_rp the required return periods (in years) for the estimated contours.\r\n#' \r\n#' @param npy the (optional) number of data points per year. This argument is only needed if the input\r\n#' \\code{object} is a sample data set.\r\n#' \r\n#' @param n_point the number of points to output around each contour. The default value is 100.\r\n#' \r\n#' @details\r\n#' The direct sampling contour is estimated in the origianl physical scales of \\eqn{hs} and \\eqn{tp} by direct\r\n#' Monte Carlo simulations rather than applying the RosenBlatt transformation.\r\n#' \r\n#' The function can be applied to an existing sample set, which can be generated by function \\code{\\link{sample_jdistr}}\r\n#' or otherwise by importing a CSV file using function \\code{\\link[data.table]{fread}}. The input sample data\r\n#' object must contain \\code{hs} and \\code{tp} as columns. The user must also specify the number of points per year\r\n#' \\code{npy} and a valid \\code{output_rp}, i.e. the maximum \\code{output_rp} must be shorter than the total\r\n#' duration of the data set.\r\n#' \r\n#' Alternatively this function can be applied to a fitted joint distribution object\r\n#' generated by function \\code{\\link{fit_ht}} or \\code{\\link{fit_wln}}. When applied to a\r\n#' \\code{wln} or \\code{ht} object, the contour estimation makes use of the importance\r\n#' sampling technique proposed in Huseby et. al. (2014) to improve the efficiency of the function.\r\n#' \r\n#' @return\r\n#' A set of estimated DSC contours with the specified return periods in the format\r\n#' of a \\code{data.table} with \\code{rp}, \\code{hs}, and \\code{tp} as columns.\r\n#' \r\n#' @examples\r\n#' # Estimating DSC contours based on a fitted model\r\n#' data(ww3_pk)\r\n#' ht = fit_ht(data = ww3_pk, npy = nrow(ww3_pk)/10, margin_thresh_count = 50, dep_thresh_count = 500)\r\n#' ec_ht = estimate_dsc(object = ht, output_rp = c(10,100,1000,10000))\r\n#' plot_ec(ec = ec_ht, raw_data = ww3_pk)\r\n#' \r\n#' # Estimating DSC contours based on a sample data set\r\n#' data(ww3_ts)\r\n#' ec_data = estimate_dsc(object = ww3_ts, output_rp = c(.5, 1, 2), npy = ww3_ts[, .N/10])\r\n#' plot_ec(ec = ec_data, raw_data = ww3_ts)\r\n#' \r\n#' @seealso \\code{\\link{fit_ht}}, \\code{\\link{fit_wln}}, \\code{\\link{sample_jdistr}}, \\code{\\link{plot_ec}}\r\n#' \r\n#' @references\r\n#' Huseby, A., Vanem, E., Natvig, B., 2014. A new Monte Carlo method for environmental contour estimation.\r\n#' Conference Proceedings. DOI:10.1201/b17399-286.\r\n#' \r\n#' Huseby, A., Vanem, E., Natvig, B., 2015. Alternative environmental contours for structural reliability\r\n#' analysis. Struct. Saf. 54, 32-45.\r\n#' \r\n#' @export\r\nestimate_dsc = function(object, output_rp, npy = NULL, n_point = 100){\r\n \r\n if(\"wln\" %in% class(object)){\r\n \r\n res = .estimate_dsc_from_wln(wln = object, output_rp = output_rp, n_point = n_point)\r\n if(!is.null(npy)){\r\n warning(\"Argument npy will be imported from the provided joint distribution object. The supplied npy is ignored.\")\r\n }\r\n \r\n }else if(\"ht\" %in% class(object)){\r\n \r\n res = .estimate_dsc_from_ht(ht = object, output_rp = output_rp, n_point = n_point)\r\n if(!is.null(npy)){\r\n warning(\"Argument npy will be imported from the provided joint distribution object. The supplied npy is ignored.\")\r\n }\r\n \r\n }else if(\"data.table\" %in% class(object)){\r\n \r\n if(is.null(npy)){\r\n stop(\"Argument npy must be provided for estimating contours from sample data.\")\r\n }else{\r\n invalid_rp = output_rp[output_rp>object[, .N/npy]]\r\n if(length(invalid_rp)==length(output_rp)){\r\n stop(\"All output_rp values are invalid as they require extrapolation. Consider fitting a joint distribution first.\")\r\n }else if(length(invalid_rp)>=1 & length(invalid_rp)